blob: 2d4d1599080435a850a7c2dd07b68be22c3f614a [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 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);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000049
50 S.MarkDeclRefReferenced(DRE);
51 S.DiagnoseUseOfDecl(FoundDecl, Loc);
52
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000053 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000054 E = S.DefaultFunctionArrayConversion(E.take());
55 if (E.isInvalid())
56 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000057 return E;
John McCallf89e55a2010-11-18 06:31:45 +000058}
59
John McCall120d63c2010-08-24 20:38:10 +000060static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
61 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000062 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000063 bool CStyle,
64 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000065
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000066static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
67 QualType &ToType,
68 bool InOverloadResolution,
69 StandardConversionSequence &SCS,
70 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000071static OverloadingResult
72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
73 UserDefinedConversionSequence& User,
74 OverloadCandidateSet& Conversions,
75 bool AllowExplicit);
76
77
78static ImplicitConversionSequence::CompareKind
79CompareStandardConversionSequences(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareQualificationConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88static ImplicitConversionSequence::CompareKind
89CompareDerivedToBaseConversions(Sema &S,
90 const StandardConversionSequence& SCS1,
91 const StandardConversionSequence& SCS2);
92
93
94
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000095/// GetConversionCategory - Retrieve the implicit conversion
96/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000097ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098GetConversionCategory(ImplicitConversionKind Kind) {
99 static const ImplicitConversionCategory
100 Category[(int)ICK_Num_Conversion_Kinds] = {
101 ICC_Identity,
102 ICC_Lvalue_Transformation,
103 ICC_Lvalue_Transformation,
104 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000105 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Qualification_Adjustment,
107 ICC_Promotion,
108 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000109 ICC_Promotion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 ICC_Conversion,
113 ICC_Conversion,
114 ICC_Conversion,
115 ICC_Conversion,
116 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000117 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000118 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000119 ICC_Conversion,
120 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000121 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000122 ICC_Conversion
123 };
124 return Category[(int)Kind];
125}
126
127/// GetConversionRank - Retrieve the implicit conversion rank
128/// corresponding to the given implicit conversion kind.
129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
130 static const ImplicitConversionRank
131 Rank[(int)ICK_Num_Conversion_Kinds] = {
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Exact_Match,
135 ICR_Exact_Match,
136 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000137 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 ICR_Promotion,
139 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000140 ICR_Promotion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000148 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000149 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000150 ICR_Conversion,
151 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000152 ICR_Complex_Real_Conversion,
153 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000154 ICR_Conversion,
155 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000156 };
157 return Rank[(int)Kind];
158}
159
160/// GetImplicitConversionName - Return the name of this kind of
161/// implicit conversion.
162const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000163 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "No conversion",
165 "Lvalue-to-rvalue",
166 "Array-to-pointer",
167 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000168 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 "Qualification",
170 "Integral promotion",
171 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000172 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "Integral conversion",
174 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000175 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000176 "Floating-integral conversion",
177 "Pointer conversion",
178 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000179 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000180 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000181 "Derived-to-base conversion",
182 "Vector conversion",
183 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000184 "Complex-real conversion",
185 "Block Pointer conversion",
186 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000187 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188 };
189 return Name[Kind];
190}
191
Douglas Gregor60d62c22008-10-31 16:23:19 +0000192/// StandardConversionSequence - Set the standard conversion
193/// sequence to the identity conversion.
194void StandardConversionSequence::setAsIdentityConversion() {
195 First = ICK_Identity;
196 Second = ICK_Identity;
197 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000198 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000199 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000200 ReferenceBinding = false;
201 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000202 IsLvalueReference = true;
203 BindsToFunctionLvalue = false;
204 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000205 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000206 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000207 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000208}
209
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210/// getRank - Retrieve the rank of this standard conversion sequence
211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
212/// implicit conversions.
213ImplicitConversionRank StandardConversionSequence::getRank() const {
214 ImplicitConversionRank Rank = ICR_Exact_Match;
215 if (GetConversionRank(First) > Rank)
216 Rank = GetConversionRank(First);
217 if (GetConversionRank(Second) > Rank)
218 Rank = GetConversionRank(Second);
219 if (GetConversionRank(Third) > Rank)
220 Rank = GetConversionRank(Third);
221 return Rank;
222}
223
224/// isPointerConversionToBool - Determines whether this conversion is
225/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000226/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000228bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 // Note that FromType has not necessarily been transformed by the
230 // array-to-pointer or function-to-pointer implicit conversions, so
231 // check for their presence as well as checking whether FromType is
232 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000233 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000234 (getFromType()->isPointerType() ||
235 getFromType()->isObjCObjectPointerType() ||
236 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000237 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239 return true;
240
241 return false;
242}
243
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244/// isPointerConversionToVoidPointer - Determines whether this
245/// conversion is a conversion of a pointer to a void pointer. This is
246/// used as part of the ranking of standard conversion sequences (C++
247/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000248bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000249StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000250isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000251 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000252 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253
254 // Note that FromType has not necessarily been transformed by the
255 // array-to-pointer implicit conversion, so check for its presence
256 // and redo the conversion to get a pointer.
257 if (First == ICK_Array_To_Pointer)
258 FromType = Context.getArrayDecayedType(FromType);
259
Douglas Gregorf9af5242011-04-15 20:45:44 +0000260 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000261 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262 return ToPtrType->getPointeeType()->isVoidType();
263
264 return false;
265}
266
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000267/// Skip any implicit casts which could be either part of a narrowing conversion
268/// or after one in an implicit conversion.
269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
270 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
271 switch (ICE->getCastKind()) {
272 case CK_NoOp:
273 case CK_IntegralCast:
274 case CK_IntegralToBoolean:
275 case CK_IntegralToFloating:
276 case CK_FloatingToIntegral:
277 case CK_FloatingToBoolean:
278 case CK_FloatingCast:
279 Converted = ICE->getSubExpr();
280 continue;
281
282 default:
283 return Converted;
284 }
285 }
286
287 return Converted;
288}
289
290/// Check if this standard conversion sequence represents a narrowing
291/// conversion, according to C++11 [dcl.init.list]p7.
292///
293/// \param Ctx The AST context.
294/// \param Converted The result of applying this standard conversion sequence.
295/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
296/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000297/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
298/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000299NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
301 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000302 APValue &ConstantValue,
303 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000304 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000305
306 // C++11 [dcl.init.list]p7:
307 // A narrowing conversion is an implicit conversion ...
308 QualType FromType = getToType(0);
309 QualType ToType = getToType(1);
310 switch (Second) {
311 // -- from a floating-point type to an integer type, or
312 //
313 // -- from an integer type or unscoped enumeration type to a floating-point
314 // type, except where the source is a constant expression and the actual
315 // value after conversion will fit into the target type and will produce
316 // the original value when converted back to the original type, or
317 case ICK_Floating_Integral:
318 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
319 return NK_Type_Narrowing;
320 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
321 llvm::APSInt IntConstantValue;
322 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
323 if (Initializer &&
324 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
325 // Convert the integer to the floating type.
326 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
327 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
328 llvm::APFloat::rmNearestTiesToEven);
329 // And back.
330 llvm::APSInt ConvertedValue = IntConstantValue;
331 bool ignored;
332 Result.convertToInteger(ConvertedValue,
333 llvm::APFloat::rmTowardZero, &ignored);
334 // If the resulting value is different, this was a narrowing conversion.
335 if (IntConstantValue != ConvertedValue) {
336 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000337 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000338 return NK_Constant_Narrowing;
339 }
340 } else {
341 // Variables are always narrowings.
342 return NK_Variable_Narrowing;
343 }
344 }
345 return NK_Not_Narrowing;
346
347 // -- from long double to double or float, or from double to float, except
348 // where the source is a constant expression and the actual value after
349 // conversion is within the range of values that can be represented (even
350 // if it cannot be represented exactly), or
351 case ICK_Floating_Conversion:
352 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
353 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
354 // FromType is larger than ToType.
355 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
356 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
357 // Constant!
358 assert(ConstantValue.isFloat());
359 llvm::APFloat FloatVal = ConstantValue.getFloat();
360 // Convert the source value into the target type.
361 bool ignored;
362 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
363 Ctx.getFloatTypeSemantics(ToType),
364 llvm::APFloat::rmNearestTiesToEven, &ignored);
365 // If there was no overflow, the source value is within the range of
366 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000367 if (ConvertStatus & llvm::APFloat::opOverflow) {
368 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000369 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000370 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000371 } else {
372 return NK_Variable_Narrowing;
373 }
374 }
375 return NK_Not_Narrowing;
376
377 // -- from an integer type or unscoped enumeration type to an integer type
378 // that cannot represent all the values of the original type, except where
379 // the source is a constant expression and the actual value after
380 // conversion will fit into the target type and will produce the original
381 // value when converted back to the original type.
382 case ICK_Boolean_Conversion: // Bools are integers too.
383 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
384 // Boolean conversions can be from pointers and pointers to members
385 // [conv.bool], and those aren't considered narrowing conversions.
386 return NK_Not_Narrowing;
387 } // Otherwise, fall through to the integral case.
388 case ICK_Integral_Conversion: {
389 assert(FromType->isIntegralOrUnscopedEnumerationType());
390 assert(ToType->isIntegralOrUnscopedEnumerationType());
391 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392 const unsigned FromWidth = Ctx.getIntWidth(FromType);
393 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394 const unsigned ToWidth = Ctx.getIntWidth(ToType);
395
396 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000397 (FromWidth == ToWidth && FromSigned != ToSigned) ||
398 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000399 // Not all values of FromType can be represented in ToType.
400 llvm::APSInt InitializerValue;
401 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000402 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403 // Such conversions on variables are always narrowing.
404 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000405 }
406 bool Narrowing = false;
407 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000408 // Negative -> unsigned is narrowing. Otherwise, more bits is never
409 // narrowing.
410 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000411 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000412 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000413 // Add a bit to the InitializerValue so we don't have to worry about
414 // signed vs. unsigned comparisons.
415 InitializerValue = InitializerValue.extend(
416 InitializerValue.getBitWidth() + 1);
417 // Convert the initializer to and from the target width and signed-ness.
418 llvm::APSInt ConvertedValue = InitializerValue;
419 ConvertedValue = ConvertedValue.trunc(ToWidth);
420 ConvertedValue.setIsSigned(ToSigned);
421 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422 ConvertedValue.setIsSigned(InitializerValue.isSigned());
423 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000424 if (ConvertedValue != InitializerValue)
425 Narrowing = true;
426 }
427 if (Narrowing) {
428 ConstantType = Initializer->getType();
429 ConstantValue = APValue(InitializerValue);
430 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000431 }
432 }
433 return NK_Not_Narrowing;
434 }
435
436 default:
437 // Other kinds of conversions are not narrowings.
438 return NK_Not_Narrowing;
439 }
440}
441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442/// DebugPrint - Print this standard conversion sequence to standard
443/// error. Useful for debugging overloading issues.
444void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000445 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000446 bool PrintedSomething = false;
447 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Second != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457
458 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000460 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000461 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000462 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000464 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (Third != ICK_Identity) {
469 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 PrintedSomething = true;
474 }
475
476 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000477 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478 }
479}
480
481/// DebugPrint - Print this user-defined conversion sequence to standard
482/// error. Useful for debugging overloading issues.
483void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000485 if (Before.First || Before.Second || Before.Third) {
486 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000487 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000489 if (ConversionFunction)
490 OS << '\'' << *ConversionFunction << '\'';
491 else
492 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000494 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 After.DebugPrint();
496 }
497}
498
499/// DebugPrint - Print this implicit conversion sequence to standard
500/// error. Useful for debugging overloading issues.
501void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000502 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 switch (ConversionKind) {
504 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 Standard.DebugPrint();
507 break;
508 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 UserDefined.DebugPrint();
511 break;
512 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000513 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 break;
John McCall1d318332010-01-12 00:44:57 +0000515 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000516 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000517 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000519 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520 break;
521 }
522
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000523 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524}
525
John McCall1d318332010-01-12 00:44:57 +0000526void AmbiguousConversionSequence::construct() {
527 new (&conversions()) ConversionSet();
528}
529
530void AmbiguousConversionSequence::destruct() {
531 conversions().~ConversionSet();
532}
533
534void
535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
536 FromTypePtr = O.FromTypePtr;
537 ToTypePtr = O.ToTypePtr;
538 new (&conversions()) ConversionSet(O.conversions());
539}
540
Douglas Gregora9333192010-05-08 17:41:32 +0000541namespace {
542 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000543 // template argument information.
544 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000545 TemplateArgument FirstArg;
546 TemplateArgument SecondArg;
547 };
Richard Smith29805ca2013-01-31 05:19:49 +0000548 // Structure used by OverloadCandidate::DeductionFailureInfo to store
549 // template parameter and template argument information.
550 struct DFIParamWithArguments : DFIArguments {
551 TemplateParameter Param;
552 };
Douglas Gregora9333192010-05-08 17:41:32 +0000553}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554
Douglas Gregora9333192010-05-08 17:41:32 +0000555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
557OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000558static MakeDeductionFailureInfo(ASTContext &Context,
559 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000560 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000561 OverloadCandidate::DeductionFailureInfo Result;
562 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000563 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000564 Result.Data = 0;
565 switch (TDK) {
566 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000567 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000568 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000569 case Sema::TDK_TooManyArguments:
570 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000571 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregora9333192010-05-08 17:41:32 +0000573 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000574 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000575 Result.Data = Info.Param.getOpaqueValue();
576 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577
Richard Smith29805ca2013-01-31 05:19:49 +0000578 case Sema::TDK_NonDeducedMismatch: {
579 // FIXME: Should allocate from normal heap so that we can free this later.
580 DFIArguments *Saved = new (Context) DFIArguments;
581 Saved->FirstArg = Info.FirstArg;
582 Saved->SecondArg = Info.SecondArg;
583 Result.Data = Saved;
584 break;
585 }
586
Douglas Gregora9333192010-05-08 17:41:32 +0000587 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000588 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000589 // FIXME: Should allocate from normal heap so that we can free this later.
590 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000591 Saved->Param = Info.Param;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Result.Data = Saved;
595 break;
596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Douglas Gregora9333192010-05-08 17:41:32 +0000598 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000599 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000600 if (Info.hasSFINAEDiagnostic()) {
601 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
602 SourceLocation(), PartialDiagnostic::NullDiagnostic());
603 Info.takeSFINAEDiagnostic(*Diag);
604 Result.HasDiagnostic = true;
605 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000606 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregora9333192010-05-08 17:41:32 +0000608 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000609 Result.Data = Info.Expression;
610 break;
611
Richard Smith29805ca2013-01-31 05:19:49 +0000612 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return Result;
617}
John McCall1d318332010-01-12 00:44:57 +0000618
Douglas Gregora9333192010-05-08 17:41:32 +0000619void OverloadCandidate::DeductionFailureInfo::Destroy() {
620 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
621 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000622 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000623 case Sema::TDK_InstantiationDepth:
624 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000625 case Sema::TDK_TooManyArguments:
626 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000627 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000628 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000630
Douglas Gregora9333192010-05-08 17:41:32 +0000631 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000632 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000633 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000634 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000635 Data = 0;
636 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000637
638 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000639 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000640 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000641 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
642 Diag->~PartialDiagnosticAt();
643 HasDiagnostic = false;
644 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000645 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000647 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000648 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000649 break;
650 }
651}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Richard Smithb8590f32012-05-07 09:03:25 +0000653PartialDiagnosticAt *
654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
655 if (HasDiagnostic)
656 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
657 return 0;
658}
659
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000664 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000665 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000666 case Sema::TDK_TooManyArguments:
667 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000669 case Sema::TDK_NonDeducedMismatch:
670 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000671 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Douglas Gregora9333192010-05-08 17:41:32 +0000673 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000674 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000675 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000676
677 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000679 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
Douglas Gregora9333192010-05-08 17:41:32 +0000681 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000682 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000683 break;
684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685
Douglas Gregora9333192010-05-08 17:41:32 +0000686 return TemplateParameter();
687}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688
Douglas Gregorec20f462010-05-08 20:07:26 +0000689TemplateArgumentList *
690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_TooManyArguments:
696 case Sema::TDK_TooFewArguments:
697 case Sema::TDK_Incomplete:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_Inconsistent:
700 case Sema::TDK_Underqualified:
701 case Sema::TDK_NonDeducedMismatch:
702 case Sema::TDK_FailedOverloadResolution:
703 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000704
Richard Smith29805ca2013-01-31 05:19:49 +0000705 case Sema::TDK_SubstitutionFailure:
706 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707
Richard Smith29805ca2013-01-31 05:19:49 +0000708 // Unhandled
709 case Sema::TDK_MiscellaneousDeductionFailure:
710 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000711 }
712
713 return 0;
714}
715
Douglas Gregora9333192010-05-08 17:41:32 +0000716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000719 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000720 case Sema::TDK_InstantiationDepth:
721 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000722 case Sema::TDK_TooManyArguments:
723 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000724 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000725 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000726 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000727 return 0;
728
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000730 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000731 case Sema::TDK_NonDeducedMismatch:
732 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000733
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000734 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 break;
737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
Douglas Gregora9333192010-05-08 17:41:32 +0000739 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000740}
Douglas Gregora9333192010-05-08 17:41:32 +0000741
742const TemplateArgument *
743OverloadCandidate::DeductionFailureInfo::getSecondArg() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000746 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000749 case Sema::TDK_TooManyArguments:
750 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000751 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000752 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000753 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000754 return 0;
755
Douglas Gregora9333192010-05-08 17:41:32 +0000756 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000757 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000758 case Sema::TDK_NonDeducedMismatch:
759 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000760
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000761 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000763 break;
764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
Douglas Gregora9333192010-05-08 17:41:32 +0000766 return 0;
767}
768
Richard Smith0efa62f2013-01-31 04:03:12 +0000769Expr *
770OverloadCandidate::DeductionFailureInfo::getExpr() {
771 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
772 Sema::TDK_FailedOverloadResolution)
773 return static_cast<Expr*>(Data);
774
775 return 0;
776}
777
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000778void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000779 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000780 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
781 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000782 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
783 i->DeductionFailure.Destroy();
784 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000785}
786
787void OverloadCandidateSet::clear() {
788 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000789 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000790 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000791 Functions.clear();
792}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000793
John McCall5acb0c92011-10-17 18:40:02 +0000794namespace {
795 class UnbridgedCastsSet {
796 struct Entry {
797 Expr **Addr;
798 Expr *Saved;
799 };
800 SmallVector<Entry, 2> Entries;
801
802 public:
803 void save(Sema &S, Expr *&E) {
804 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
805 Entry entry = { &E, E };
806 Entries.push_back(entry);
807 E = S.stripARCUnbridgedCast(E);
808 }
809
810 void restore() {
811 for (SmallVectorImpl<Entry>::iterator
812 i = Entries.begin(), e = Entries.end(); i != e; ++i)
813 *i->Addr = i->Saved;
814 }
815 };
816}
817
818/// checkPlaceholderForOverload - Do any interesting placeholder-like
819/// preprocessing on the given expression.
820///
821/// \param unbridgedCasts a collection to which to add unbridged casts;
822/// without this, they will be immediately diagnosed as errors
823///
824/// Return true on unrecoverable error.
825static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
826 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000827 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
828 // We can't handle overloaded expressions here because overload
829 // resolution might reasonably tweak them.
830 if (placeholder->getKind() == BuiltinType::Overload) return false;
831
832 // If the context potentially accepts unbridged ARC casts, strip
833 // the unbridged cast and add it to the collection for later restoration.
834 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
835 unbridgedCasts) {
836 unbridgedCasts->save(S, E);
837 return false;
838 }
839
840 // Go ahead and check everything else.
841 ExprResult result = S.CheckPlaceholderExpr(E);
842 if (result.isInvalid())
843 return true;
844
845 E = result.take();
846 return false;
847 }
848
849 // Nothing to do.
850 return false;
851}
852
853/// checkArgPlaceholdersForOverload - Check a set of call operands for
854/// placeholders.
855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
856 unsigned numArgs,
857 UnbridgedCastsSet &unbridged) {
858 for (unsigned i = 0; i != numArgs; ++i)
859 if (checkPlaceholderForOverload(S, args[i], &unbridged))
860 return true;
861
862 return false;
863}
864
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000866// overload of the declarations in Old. This routine returns false if
867// New and Old cannot be overloaded, e.g., if New has the same
868// signature as some function in Old (C++ 1.3.10) or if the Old
869// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000870// it does return false, MatchedDecl will point to the decl that New
871// cannot be overloaded with. This decl may be a UsingShadowDecl on
872// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000873//
874// Example: Given the following input:
875//
876// void f(int, float); // #1
877// void f(int, int); // #2
878// int f(int, int); // #3
879//
880// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000881// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882//
John McCall51fa86f2009-12-02 08:47:38 +0000883// When we process #2, Old contains only the FunctionDecl for #1. By
884// comparing the parameter types, we see that #1 and #2 are overloaded
885// (since they have different signatures), so this routine returns
886// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887//
John McCall51fa86f2009-12-02 08:47:38 +0000888// When we process #3, Old is an overload set containing #1 and #2. We
889// compare the signatures of #3 to #1 (they're overloaded, so we do
890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
891// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000892// signature), IsOverload returns false and MatchedDecl will be set to
893// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000894//
895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
896// into a class by a using declaration. The rules for whether to hide
897// shadow declarations ignore some properties which otherwise figure
898// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000899Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
901 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000902 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000903 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000904 NamedDecl *OldD = *I;
905
906 bool OldIsUsingDecl = false;
907 if (isa<UsingShadowDecl>(OldD)) {
908 OldIsUsingDecl = true;
909
910 // We can always introduce two using declarations into the same
911 // context, even if they have identical signatures.
912 if (NewIsUsingDecl) continue;
913
914 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
915 }
916
917 // If either declaration was introduced by a using declaration,
918 // we'll need to use slightly different rules for matching.
919 // Essentially, these rules are the normal rules, except that
920 // function templates hide function templates with different
921 // return types or template parameter lists.
922 bool UseMemberUsingDeclRules =
923 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
924
John McCall51fa86f2009-12-02 08:47:38 +0000925 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000926 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
927 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
928 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
929 continue;
930 }
931
John McCall871b2e72009-12-09 03:35:25 +0000932 Match = *I;
933 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000934 }
John McCall51fa86f2009-12-02 08:47:38 +0000935 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
John McCall871b2e72009-12-09 03:35:25 +0000942 Match = *I;
943 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000944 }
John McCalld7945c62010-11-10 03:01:53 +0000945 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000946 // We can overload with these, which can show up when doing
947 // redeclaration checks for UsingDecls.
948 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000949 } else if (isa<TagDecl>(OldD)) {
950 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000951 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
952 // Optimistically assume that an unresolved using decl will
953 // overload; if it doesn't, we'll have to diagnose during
954 // template instantiation.
955 } else {
John McCall68263142009-11-18 22:49:29 +0000956 // (C++ 13p1):
957 // Only function declarations can be overloaded; object and type
958 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000959 Match = *I;
960 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000961 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000962 }
John McCall68263142009-11-18 22:49:29 +0000963
John McCall871b2e72009-12-09 03:35:25 +0000964 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000965}
966
Rafael Espindola78eeba82012-12-28 14:21:58 +0000967static bool canBeOverloaded(const FunctionDecl &D) {
968 if (D.getAttr<OverloadableAttr>())
969 return true;
970 if (D.hasCLanguageLinkage())
971 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000972
973 // Main cannot be overloaded (basic.start.main).
974 if (D.isMain())
975 return false;
976
Rafael Espindola78eeba82012-12-28 14:21:58 +0000977 return true;
978}
979
John McCallad00b772010-06-16 08:42:20 +0000980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
981 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000982 // If both of the functions are extern "C", then they are not
983 // overloads.
Rafael Espindola78eeba82012-12-28 14:21:58 +0000984 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall7b492022010-08-12 07:09:11 +0000985 return false;
986
John McCall68263142009-11-18 22:49:29 +0000987 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
988 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
989
990 // C++ [temp.fct]p2:
991 // A function template can be overloaded with other function templates
992 // and with normal (non-template) functions.
993 if ((OldTemplate == 0) != (NewTemplate == 0))
994 return true;
995
996 // Is the function New an overload of the function Old?
997 QualType OldQType = Context.getCanonicalType(Old->getType());
998 QualType NewQType = Context.getCanonicalType(New->getType());
999
1000 // Compare the signatures (C++ 1.3.10) of the two functions to
1001 // determine whether they are overloads. If we find any mismatch
1002 // in the signature, they are overloads.
1003
1004 // If either of these functions is a K&R-style function (no
1005 // prototype), then we consider them to have matching signatures.
1006 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1007 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1008 return false;
1009
John McCallf4c73712011-01-19 06:33:43 +00001010 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1011 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001012
1013 // The signature of a function includes the types of its
1014 // parameters (C++ 1.3.10), which includes the presence or absence
1015 // of the ellipsis; see C++ DR 357).
1016 if (OldQType != NewQType &&
1017 (OldType->getNumArgs() != NewType->getNumArgs() ||
1018 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001019 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001020 return true;
1021
1022 // C++ [temp.over.link]p4:
1023 // The signature of a function template consists of its function
1024 // signature, its return type and its template parameter list. The names
1025 // of the template parameters are significant only for establishing the
1026 // relationship between the template parameters and the rest of the
1027 // signature.
1028 //
1029 // We check the return type and template parameter lists for function
1030 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001031 //
1032 // However, we don't consider either of these when deciding whether
1033 // a member introduced by a shadow declaration is hidden.
1034 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +00001035 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1036 OldTemplate->getTemplateParameters(),
1037 false, TPL_TemplateMatch) ||
1038 OldType->getResultType() != NewType->getResultType()))
1039 return true;
1040
1041 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001042 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001043 //
1044 // As part of this, also check whether one of the member functions
1045 // is static, in which case they are not overloads (C++
1046 // 13.1p2). While not part of the definition of the signature,
1047 // this check is important to determine whether these functions
1048 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001049 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1050 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001051 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001052 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1053 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1054 if (!UseUsingDeclRules &&
1055 (OldMethod->getRefQualifier() == RQ_None ||
1056 NewMethod->getRefQualifier() == RQ_None)) {
1057 // C++0x [over.load]p2:
1058 // - Member function declarations with the same name and the same
1059 // parameter-type-list as well as member function template
1060 // declarations with the same name, the same parameter-type-list, and
1061 // the same template parameter lists cannot be overloaded if any of
1062 // them, but not all, have a ref-qualifier (8.3.5).
1063 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1064 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1065 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1066 }
1067 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
Richard Smith21c8fa82013-01-14 05:37:29 +00001070 // We may not have applied the implicit const for a constexpr member
1071 // function yet (because we haven't yet resolved whether this is a static
1072 // or non-static member function). Add it now, on the assumption that this
1073 // is a redeclaration of OldMethod.
1074 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001075 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001076 NewQuals |= Qualifiers::Const;
1077 if (OldMethod->getTypeQualifiers() != NewQuals)
1078 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
John McCall68263142009-11-18 22:49:29 +00001081 // The signatures match; this is not an overload.
1082 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001083}
1084
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001085/// \brief Checks availability of the function depending on the current
1086/// function context. Inside an unavailable function, unavailability is ignored.
1087///
1088/// \returns true if \arg FD is unavailable and current context is inside
1089/// an available function, false otherwise.
1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1091 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1092}
1093
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001094/// \brief Tries a user-defined conversion from From to ToType.
1095///
1096/// Produces an implicit conversion sequence for when a standard conversion
1097/// is not an option. See TryImplicitConversion for more information.
1098static ImplicitConversionSequence
1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1100 bool SuppressUserConversions,
1101 bool AllowExplicit,
1102 bool InOverloadResolution,
1103 bool CStyle,
1104 bool AllowObjCWritebackConversion) {
1105 ImplicitConversionSequence ICS;
1106
1107 if (SuppressUserConversions) {
1108 // We're not in the case above, so there is no conversion that
1109 // we can perform.
1110 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1111 return ICS;
1112 }
1113
1114 // Attempt user-defined conversion.
1115 OverloadCandidateSet Conversions(From->getExprLoc());
1116 OverloadingResult UserDefResult
1117 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1118 AllowExplicit);
1119
1120 if (UserDefResult == OR_Success) {
1121 ICS.setUserDefined();
1122 // C++ [over.ics.user]p4:
1123 // A conversion of an expression of class type to the same class
1124 // type is given Exact Match rank, and a conversion of an
1125 // expression of class type to a base class of that type is
1126 // given Conversion rank, in spite of the fact that a copy
1127 // constructor (i.e., a user-defined conversion function) is
1128 // called for those cases.
1129 if (CXXConstructorDecl *Constructor
1130 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1131 QualType FromCanon
1132 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1133 QualType ToCanon
1134 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1135 if (Constructor->isCopyConstructor() &&
1136 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1137 // Turn this into a "standard" conversion sequence, so that it
1138 // gets ranked with standard conversion sequences.
1139 ICS.setStandard();
1140 ICS.Standard.setAsIdentityConversion();
1141 ICS.Standard.setFromType(From->getType());
1142 ICS.Standard.setAllToTypes(ToType);
1143 ICS.Standard.CopyConstructor = Constructor;
1144 if (ToCanon != FromCanon)
1145 ICS.Standard.Second = ICK_Derived_To_Base;
1146 }
1147 }
1148
1149 // C++ [over.best.ics]p4:
1150 // However, when considering the argument of a user-defined
1151 // conversion function that is a candidate by 13.3.1.3 when
1152 // invoked for the copying of the temporary in the second step
1153 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1154 // 13.3.1.6 in all cases, only standard conversion sequences and
1155 // ellipsis conversion sequences are allowed.
1156 if (SuppressUserConversions && ICS.isUserDefined()) {
1157 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1158 }
1159 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1160 ICS.setAmbiguous();
1161 ICS.Ambiguous.setFromType(From->getType());
1162 ICS.Ambiguous.setToType(ToType);
1163 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1164 Cand != Conversions.end(); ++Cand)
1165 if (Cand->Viable)
1166 ICS.Ambiguous.addConversion(Cand->Function);
1167 } else {
1168 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1169 }
1170
1171 return ICS;
1172}
1173
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001174/// TryImplicitConversion - Attempt to perform an implicit conversion
1175/// from the given expression (Expr) to the given type (ToType). This
1176/// function returns an implicit conversion sequence that can be used
1177/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178///
1179/// void f(float f);
1180/// void g(int i) { f(i); }
1181///
1182/// this routine would produce an implicit conversion sequence to
1183/// describe the initialization of f from i, which will be a standard
1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1185/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1186//
1187/// Note that this routine only determines how the conversion can be
1188/// performed; it does not actually perform the conversion. As such,
1189/// it will not produce any diagnostics if no conversion is available,
1190/// but will instead return an implicit conversion sequence of kind
1191/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001192///
1193/// If @p SuppressUserConversions, then user-defined conversions are
1194/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001195/// If @p AllowExplicit, then explicit user-defined conversions are
1196/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001197///
1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1199/// writeback conversion, which allows __autoreleasing id* parameters to
1200/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001201static ImplicitConversionSequence
1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1203 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001205 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001206 bool CStyle,
1207 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001208 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001209 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001210 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001211 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001212 return ICS;
1213 }
1214
David Blaikie4e4d0842012-03-11 07:00:24 +00001215 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001216 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001217 return ICS;
1218 }
1219
Douglas Gregor604eb652010-08-11 02:15:33 +00001220 // C++ [over.ics.user]p4:
1221 // A conversion of an expression of class type to the same class
1222 // type is given Exact Match rank, and a conversion of an
1223 // expression of class type to a base class of that type is
1224 // given Conversion rank, in spite of the fact that a copy/move
1225 // constructor (i.e., a user-defined conversion function) is
1226 // called for those cases.
1227 QualType FromType = From->getType();
1228 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001229 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1230 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001231 ICS.setStandard();
1232 ICS.Standard.setAsIdentityConversion();
1233 ICS.Standard.setFromType(FromType);
1234 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001236 // We don't actually check at this point whether there is a valid
1237 // copy/move constructor, since overloading just assumes that it
1238 // exists. When we actually perform initialization, we'll find the
1239 // appropriate constructor to copy the returned object, if needed.
1240 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001242 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001243 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001244 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001245
Douglas Gregor604eb652010-08-11 02:15:33 +00001246 return ICS;
1247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001248
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001249 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1250 AllowExplicit, InOverloadResolution, CStyle,
1251 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001252}
1253
John McCallf85e1932011-06-15 23:02:42 +00001254ImplicitConversionSequence
1255Sema::TryImplicitConversion(Expr *From, QualType ToType,
1256 bool SuppressUserConversions,
1257 bool AllowExplicit,
1258 bool InOverloadResolution,
1259 bool CStyle,
1260 bool AllowObjCWritebackConversion) {
1261 return clang::TryImplicitConversion(*this, From, ToType,
1262 SuppressUserConversions, AllowExplicit,
1263 InOverloadResolution, CStyle,
1264 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001265}
1266
Douglas Gregor575c63a2010-04-16 22:27:05 +00001267/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001268/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001269/// converted expression. Flavor is the kind of conversion we're
1270/// performing, used in the error message. If @p AllowExplicit,
1271/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001272ExprResult
1273Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001274 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001275 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001276 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001277}
1278
John Wiegley429bb272011-04-08 18:41:53 +00001279ExprResult
1280Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001281 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001282 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001283 if (checkPlaceholderForOverload(*this, From))
1284 return ExprError();
1285
John McCallf85e1932011-06-15 23:02:42 +00001286 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1287 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001288 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001289 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001290
John McCall120d63c2010-08-24 20:38:10 +00001291 ICS = clang::TryImplicitConversion(*this, From, ToType,
1292 /*SuppressUserConversions=*/false,
1293 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001294 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001295 /*CStyle=*/false,
1296 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001297 return PerformImplicitConversion(From, ToType, ICS, Action);
1298}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001299
1300/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001301/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1303 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001304 if (Context.hasSameUnqualifiedType(FromType, ToType))
1305 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001306
John McCall00ccbef2010-12-21 00:44:39 +00001307 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1308 // where F adds one of the following at most once:
1309 // - a pointer
1310 // - a member pointer
1311 // - a block pointer
1312 CanQualType CanTo = Context.getCanonicalType(ToType);
1313 CanQualType CanFrom = Context.getCanonicalType(FromType);
1314 Type::TypeClass TyClass = CanTo->getTypeClass();
1315 if (TyClass != CanFrom->getTypeClass()) return false;
1316 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1317 if (TyClass == Type::Pointer) {
1318 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1319 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1320 } else if (TyClass == Type::BlockPointer) {
1321 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1322 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1323 } else if (TyClass == Type::MemberPointer) {
1324 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1325 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1326 } else {
1327 return false;
1328 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001329
John McCall00ccbef2010-12-21 00:44:39 +00001330 TyClass = CanTo->getTypeClass();
1331 if (TyClass != CanFrom->getTypeClass()) return false;
1332 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1333 return false;
1334 }
1335
1336 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1337 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1338 if (!EInfo.getNoReturn()) return false;
1339
1340 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1341 assert(QualType(FromFn, 0).isCanonical());
1342 if (QualType(FromFn, 0) != CanTo) return false;
1343
1344 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001345 return true;
1346}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001348/// \brief Determine whether the conversion from FromType to ToType is a valid
1349/// vector conversion.
1350///
1351/// \param ICK Will be set to the vector conversion kind, if this is a vector
1352/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1354 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001355 // We need at least one of these types to be a vector type to have a vector
1356 // conversion.
1357 if (!ToType->isVectorType() && !FromType->isVectorType())
1358 return false;
1359
1360 // Identical types require no conversions.
1361 if (Context.hasSameUnqualifiedType(FromType, ToType))
1362 return false;
1363
1364 // There are no conversions between extended vector types, only identity.
1365 if (ToType->isExtVectorType()) {
1366 // There are no conversions between extended vector types other than the
1367 // identity conversion.
1368 if (FromType->isExtVectorType())
1369 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001371 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001372 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001373 ICK = ICK_Vector_Splat;
1374 return true;
1375 }
1376 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001377
1378 // We can perform the conversion between vector types in the following cases:
1379 // 1)vector types are equivalent AltiVec and GCC vector types
1380 // 2)lax vector conversions are permitted and the vector types are of the
1381 // same size
1382 if (ToType->isVectorType() && FromType->isVectorType()) {
1383 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001384 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001385 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001386 ICK = ICK_Vector_Conversion;
1387 return true;
1388 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001389 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001390
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001391 return false;
1392}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001393
Douglas Gregor7d000652012-04-12 20:48:09 +00001394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1395 bool InOverloadResolution,
1396 StandardConversionSequence &SCS,
1397 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001398
Douglas Gregor60d62c22008-10-31 16:23:19 +00001399/// IsStandardConversion - Determines whether there is a standard
1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1401/// expression From to the type ToType. Standard conversion sequences
1402/// only consider non-class types; for conversions that involve class
1403/// types, use TryImplicitConversion. If a conversion exists, SCS will
1404/// contain the standard conversion sequence required to perform this
1405/// conversion and this routine will return true. Otherwise, this
1406/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1408 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001409 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001410 bool CStyle,
1411 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001412 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413
Douglas Gregor60d62c22008-10-31 16:23:19 +00001414 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001415 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001416 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001417 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001418 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001419 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420
Douglas Gregorf9201e02009-02-11 23:02:49 +00001421 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001422 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001423 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001424 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001425 return false;
1426
Mike Stump1eb44332009-09-09 15:08:12 +00001427 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001428 }
1429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 // The first conversion can be an lvalue-to-rvalue conversion,
1431 // array-to-pointer conversion, or function-to-pointer conversion
1432 // (C++ 4p1).
1433
John McCall120d63c2010-08-24 20:38:10 +00001434 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001435 DeclAccessPair AccessPair;
1436 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001437 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001438 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001439 // We were able to resolve the address of the overloaded function,
1440 // so we can convert to the type of that function.
1441 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001442
1443 // we can sometimes resolve &foo<int> regardless of ToType, so check
1444 // if the type matches (identity) or we are converting to bool
1445 if (!S.Context.hasSameUnqualifiedType(
1446 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1447 QualType resultTy;
1448 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001449 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001450 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1451 // otherwise, only a boolean conversion is standard
1452 if (!ToType->isBooleanType())
1453 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001455
Chandler Carruth90434232011-03-29 08:08:18 +00001456 // Check if the "from" expression is taking the address of an overloaded
1457 // function and recompute the FromType accordingly. Take advantage of the
1458 // fact that non-static member functions *must* have such an address-of
1459 // expression.
1460 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1461 if (Method && !Method->isStatic()) {
1462 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1463 "Non-unary operator on non-static member address");
1464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1465 == UO_AddrOf &&
1466 "Non-address-of operator on non-static member address");
1467 const Type *ClassType
1468 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1469 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001470 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1471 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1472 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001473 "Non-address-of operator for overloaded function expression");
1474 FromType = S.Context.getPointerType(FromType);
1475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001477 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001478 assert(S.Context.hasSameType(
1479 FromType,
1480 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001481 } else {
1482 return false;
1483 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001484 }
John McCall21480112011-08-30 00:57:29 +00001485 // Lvalue-to-rvalue conversion (C++11 4.1):
1486 // A glvalue (3.10) of a non-function, non-array type T can
1487 // be converted to a prvalue.
1488 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001489 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001490 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001491 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001493
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001494 // C11 6.3.2.1p2:
1495 // ... if the lvalue has atomic type, the value has the non-atomic version
1496 // of the type of the lvalue ...
1497 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1498 FromType = Atomic->getValueType();
1499
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500 // If T is a non-class type, the type of the rvalue is the
1501 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001502 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1503 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001505 } else if (FromType->isArrayType()) {
1506 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001507 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001508
1509 // An lvalue or rvalue of type "array of N T" or "array of unknown
1510 // bound of T" can be converted to an rvalue of type "pointer to
1511 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001512 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001513
John McCall120d63c2010-08-24 20:38:10 +00001514 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001515 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001516 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517
1518 // For the purpose of ranking in overload resolution
1519 // (13.3.3.1.1), this conversion is considered an
1520 // array-to-pointer conversion followed by a qualification
1521 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 SCS.Second = ICK_Identity;
1523 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001524 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001525 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001528 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001529 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531
1532 // An lvalue of function type T can be converted to an rvalue of
1533 // type "pointer to T." The result is a pointer to the
1534 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001535 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001536 } else {
1537 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001540 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001541
1542 // The second conversion can be an integral promotion, floating
1543 // point promotion, integral conversion, floating point conversion,
1544 // floating-integral conversion, pointer conversion,
1545 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001546 // For overloading in C, this can also be a "compatible-type"
1547 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001548 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001549 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001550 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551 // The unqualified versions of the types are the same: there's no
1552 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001553 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001554 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001555 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001558 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001559 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001562 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001563 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001564 SCS.Second = ICK_Complex_Promotion;
1565 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001566 } else if (ToType->isBooleanType() &&
1567 (FromType->isArithmeticType() ||
1568 FromType->isAnyPointerType() ||
1569 FromType->isBlockPointerType() ||
1570 FromType->isMemberPointerType() ||
1571 FromType->isNullPtrType())) {
1572 // Boolean conversions (C++ 4.12).
1573 SCS.Second = ICK_Boolean_Conversion;
1574 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001575 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001576 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001577 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001578 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001580 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001581 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001582 SCS.Second = ICK_Complex_Conversion;
1583 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001584 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1585 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001586 // Complex-real conversions (C99 6.3.1.7)
1587 SCS.Second = ICK_Complex_Real;
1588 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001589 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001590 // Floating point conversions (C++ 4.8).
1591 SCS.Second = ICK_Floating_Conversion;
1592 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001593 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001594 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001595 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001596 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001597 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001598 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001599 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001600 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001601 SCS.Second = ICK_Block_Pointer_Conversion;
1602 } else if (AllowObjCWritebackConversion &&
1603 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1604 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001605 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1606 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001607 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001609 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001610 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001612 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001613 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001614 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001615 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001616 SCS.Second = SecondICK;
1617 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001618 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001619 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001620 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001621 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001622 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001623 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001624 // Treat a conversion that strips "noreturn" as an identity conversion.
1625 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001626 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1627 InOverloadResolution,
1628 SCS, CStyle)) {
1629 SCS.Second = ICK_TransparentUnionConversion;
1630 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001631 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1632 CStyle)) {
1633 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001634 // appropriately.
1635 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001636 } else {
1637 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001638 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001639 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001640 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001641
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001642 QualType CanonFrom;
1643 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001644 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001645 bool ObjCLifetimeConversion;
1646 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1647 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001648 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001649 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001651 CanonFrom = S.Context.getCanonicalType(FromType);
1652 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653 } else {
1654 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001655 SCS.Third = ICK_Identity;
1656
Mike Stump1eb44332009-09-09 15:08:12 +00001657 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001658 // [...] Any difference in top-level cv-qualification is
1659 // subsumed by the initialization itself and does not constitute
1660 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001661 CanonFrom = S.Context.getCanonicalType(FromType);
1662 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001663 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001664 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001665 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001666 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1667 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001668 FromType = ToType;
1669 CanonFrom = CanonTo;
1670 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001672 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001673
1674 // If we have not converted the argument type to the parameter type,
1675 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001676 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001677 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001678
Douglas Gregor60d62c22008-10-31 16:23:19 +00001679 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001680}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001681
1682static bool
1683IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1684 QualType &ToType,
1685 bool InOverloadResolution,
1686 StandardConversionSequence &SCS,
1687 bool CStyle) {
1688
1689 const RecordType *UT = ToType->getAsUnionType();
1690 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1691 return false;
1692 // The field to initialize within the transparent union.
1693 RecordDecl *UD = UT->getDecl();
1694 // It's compatible if the expression matches any of the fields.
1695 for (RecordDecl::field_iterator it = UD->field_begin(),
1696 itend = UD->field_end();
1697 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001698 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1699 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001700 ToType = it->getType();
1701 return true;
1702 }
1703 }
1704 return false;
1705}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001706
1707/// IsIntegralPromotion - Determines whether the conversion from the
1708/// expression From (whose potentially-adjusted type is FromType) to
1709/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1710/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001711bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001712 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001713 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001714 if (!To) {
1715 return false;
1716 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717
1718 // An rvalue of type char, signed char, unsigned char, short int, or
1719 // unsigned short int can be converted to an rvalue of type int if
1720 // int can represent all the values of the source type; otherwise,
1721 // the source rvalue can be converted to an rvalue of type unsigned
1722 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001723 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1724 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001725 if (// We can promote any signed, promotable integer type to an int
1726 (FromType->isSignedIntegerType() ||
1727 // We can promote any unsigned integer type whose size is
1728 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001729 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001730 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001732 }
1733
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001734 return To->getKind() == BuiltinType::UInt;
1735 }
1736
Richard Smithe7ff9192012-09-13 21:18:54 +00001737 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738 // A prvalue of an unscoped enumeration type whose underlying type is not
1739 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1740 // following types that can represent all the values of the enumeration
1741 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1742 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001743 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001745 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001746 // with lowest integer conversion rank (4.13) greater than the rank of long
1747 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001748 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001749 // C++11 [conv.prom]p4:
1750 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1751 // can be converted to a prvalue of its underlying type. Moreover, if
1752 // integral promotion can be applied to its underlying type, a prvalue of an
1753 // unscoped enumeration type whose underlying type is fixed can also be
1754 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001755 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1756 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1757 // provided for a scoped enumeration.
1758 if (FromEnumType->getDecl()->isScoped())
1759 return false;
1760
Richard Smithe7ff9192012-09-13 21:18:54 +00001761 // We can perform an integral promotion to the underlying type of the enum,
1762 // even if that's not the promoted type.
1763 if (FromEnumType->getDecl()->isFixed()) {
1764 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1765 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1766 IsIntegralPromotion(From, Underlying, ToType);
1767 }
1768
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001769 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001771 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001772 return Context.hasSameUnqualifiedType(ToType,
1773 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001774 }
John McCall842aef82009-12-09 09:09:27 +00001775
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001776 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1778 // to an rvalue a prvalue of the first of the following types that can
1779 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001780 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001782 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001783 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001784 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001786 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001787 // Determine whether the type we're converting from is signed or
1788 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001789 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001790 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001792 // The types we'll try to promote to, in the appropriate
1793 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001794 QualType PromoteTypes[6] = {
1795 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001796 Context.LongTy, Context.UnsignedLongTy ,
1797 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001798 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001799 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001800 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1801 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001802 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001803 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1804 // We found the type that we can promote to. If this is the
1805 // type we wanted, we have a promotion. Otherwise, no
1806 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001807 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001808 }
1809 }
1810 }
1811
1812 // An rvalue for an integral bit-field (9.6) can be converted to an
1813 // rvalue of type int if int can represent all the values of the
1814 // bit-field; otherwise, it can be converted to unsigned int if
1815 // unsigned int can represent all the values of the bit-field. If
1816 // the bit-field is larger yet, no integral promotion applies to
1817 // it. If the bit-field has an enumerated type, it is treated as any
1818 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001819 // FIXME: We should delay checking of bit-fields until we actually perform the
1820 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001821 using llvm::APSInt;
1822 if (From)
1823 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001824 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001825 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001826 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1827 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1828 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Douglas Gregor86f19402008-12-20 23:49:58 +00001830 // Are we promoting to an int from a bitfield that fits in an int?
1831 if (BitWidth < ToSize ||
1832 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1833 return To->getKind() == BuiltinType::Int;
1834 }
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Douglas Gregor86f19402008-12-20 23:49:58 +00001836 // Are we promoting to an unsigned int from an unsigned bitfield
1837 // that fits into an unsigned int?
1838 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1839 return To->getKind() == BuiltinType::UInt;
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor86f19402008-12-20 23:49:58 +00001842 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001843 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001846 // An rvalue of type bool can be converted to an rvalue of type int,
1847 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001848 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001849 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001850 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001851
1852 return false;
1853}
1854
1855/// IsFloatingPointPromotion - Determines whether the conversion from
1856/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1857/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001858bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001861 /// An rvalue of type float can be converted to an rvalue of type
1862 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001863 if (FromBuiltin->getKind() == BuiltinType::Float &&
1864 ToBuiltin->getKind() == BuiltinType::Double)
1865 return true;
1866
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001867 // C99 6.3.1.5p1:
1868 // When a float is promoted to double or long double, or a
1869 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001870 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001871 (FromBuiltin->getKind() == BuiltinType::Float ||
1872 FromBuiltin->getKind() == BuiltinType::Double) &&
1873 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1874 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001875
1876 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001877 if (!getLangOpts().NativeHalfType &&
1878 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001879 ToBuiltin->getKind() == BuiltinType::Float)
1880 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001881 }
1882
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001883 return false;
1884}
1885
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001886/// \brief Determine if a conversion is a complex promotion.
1887///
1888/// A complex promotion is defined as a complex -> complex conversion
1889/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001890/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001891bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001892 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001893 if (!FromComplex)
1894 return false;
1895
John McCall183700f2009-09-21 23:43:11 +00001896 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001897 if (!ToComplex)
1898 return false;
1899
1900 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001901 ToComplex->getElementType()) ||
1902 IsIntegralPromotion(0, FromComplex->getElementType(),
1903 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001904}
1905
Douglas Gregorcb7de522008-11-26 23:31:11 +00001906/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1907/// the pointer type FromPtr to a pointer to type ToPointee, with the
1908/// same type qualifiers as FromPtr has on its pointee type. ToType,
1909/// if non-empty, will be a pointer to ToType that may or may not have
1910/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001911///
Mike Stump1eb44332009-09-09 15:08:12 +00001912static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001913BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001914 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001915 ASTContext &Context,
1916 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001917 assert((FromPtr->getTypeClass() == Type::Pointer ||
1918 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1919 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920
John McCallf85e1932011-06-15 23:02:42 +00001921 /// Conversions to 'id' subsume cv-qualifier conversions.
1922 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001923 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001924
1925 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001926 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001927 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001928 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001929
John McCallf85e1932011-06-15 23:02:42 +00001930 if (StripObjCLifetime)
1931 Quals.removeObjCLifetime();
1932
Mike Stump1eb44332009-09-09 15:08:12 +00001933 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001934 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001935 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001936 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001937 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001938
1939 // Build a pointer to ToPointee. It has the right qualifiers
1940 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001941 if (isa<ObjCObjectPointerType>(ToType))
1942 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001943 return Context.getPointerType(ToPointee);
1944 }
1945
1946 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001947 QualType QualifiedCanonToPointee
1948 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001949
Douglas Gregorda80f742010-12-01 21:43:58 +00001950 if (isa<ObjCObjectPointerType>(ToType))
1951 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1952 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001953}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001954
Mike Stump1eb44332009-09-09 15:08:12 +00001955static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001956 bool InOverloadResolution,
1957 ASTContext &Context) {
1958 // Handle value-dependent integral null pointer constants correctly.
1959 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1960 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001961 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001962 return !InOverloadResolution;
1963
Douglas Gregorce940492009-09-25 04:25:58 +00001964 return Expr->isNullPointerConstant(Context,
1965 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1966 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001967}
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001969/// IsPointerConversion - Determines whether the conversion of the
1970/// expression From, which has the (possibly adjusted) type FromType,
1971/// can be converted to the type ToType via a pointer conversion (C++
1972/// 4.10). If so, returns true and places the converted type (that
1973/// might differ from ToType in its cv-qualifiers at some level) into
1974/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001975///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001976/// This routine also supports conversions to and from block pointers
1977/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1978/// pointers to interfaces. FIXME: Once we've determined the
1979/// appropriate overloading rules for Objective-C, we may want to
1980/// split the Objective-C checks into a different routine; however,
1981/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001982/// conversions, so for now they live here. IncompatibleObjC will be
1983/// set if the conversion is an allowed Objective-C conversion that
1984/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001985bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001986 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001987 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001988 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001989 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001990 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1991 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001992 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001993
Mike Stump1eb44332009-09-09 15:08:12 +00001994 // Conversion from a null pointer constant to any Objective-C pointer type.
1995 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001996 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001997 ConvertedType = ToType;
1998 return true;
1999 }
2000
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002001 // Blocks: Block pointers can be converted to void*.
2002 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002003 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002004 ConvertedType = ToType;
2005 return true;
2006 }
2007 // Blocks: A null pointer constant can be converted to a block
2008 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002009 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002011 ConvertedType = ToType;
2012 return true;
2013 }
2014
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002015 // If the left-hand-side is nullptr_t, the right side can be a null
2016 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002017 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002018 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002019 ConvertedType = ToType;
2020 return true;
2021 }
2022
Ted Kremenek6217b802009-07-29 21:53:49 +00002023 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002024 if (!ToTypePtr)
2025 return false;
2026
2027 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002028 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
Sebastian Redl07779722008-10-31 14:43:28 +00002032
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002033 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002034 // , including objective-c pointers.
2035 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002036 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002037 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002038 ConvertedType = BuildSimilarlyQualifiedPointerType(
2039 FromType->getAs<ObjCObjectPointerType>(),
2040 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002041 ToType, Context);
2042 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002043 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002044 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002045 if (!FromTypePtr)
2046 return false;
2047
2048 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002049
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002051 // pointer conversion, so don't do all of the work below.
2052 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2053 return false;
2054
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002055 // An rvalue of type "pointer to cv T," where T is an object type,
2056 // can be converted to an rvalue of type "pointer to cv void" (C++
2057 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002058 if (FromPointeeType->isIncompleteOrObjectType() &&
2059 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002061 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002062 ToType, Context,
2063 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002064 return true;
2065 }
2066
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002067 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002068 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002069 ToPointeeType->isVoidType()) {
2070 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071 ToPointeeType,
2072 ToType, Context);
2073 return true;
2074 }
2075
Douglas Gregorf9201e02009-02-11 23:02:49 +00002076 // When we're overloading in C, we allow a special kind of pointer
2077 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002078 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002079 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002080 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002081 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002082 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002083 return true;
2084 }
2085
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002086 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002087 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002088 // An rvalue of type "pointer to cv D," where D is a class type,
2089 // can be converted to an rvalue of type "pointer to cv B," where
2090 // B is a base class (clause 10) of D. If B is an inaccessible
2091 // (clause 11) or ambiguous (10.2) base class of D, a program that
2092 // necessitates this conversion is ill-formed. The result of the
2093 // conversion is a pointer to the base class sub-object of the
2094 // derived class object. The null pointer value is converted to
2095 // the null pointer value of the destination type.
2096 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002097 // Note that we do not check for ambiguity or inaccessibility
2098 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002099 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002100 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002101 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002102 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002103 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002104 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002105 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002106 ToType, Context);
2107 return true;
2108 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002109
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002110 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2111 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2113 ToPointeeType,
2114 ToType, Context);
2115 return true;
2116 }
2117
Douglas Gregorc7887512008-12-19 19:13:09 +00002118 return false;
2119}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002120
2121/// \brief Adopt the given qualifiers for the given type.
2122static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2123 Qualifiers TQs = T.getQualifiers();
2124
2125 // Check whether qualifiers already match.
2126 if (TQs == Qs)
2127 return T;
2128
2129 if (Qs.compatiblyIncludes(TQs))
2130 return Context.getQualifiedType(T, Qs);
2131
2132 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2133}
Douglas Gregorc7887512008-12-19 19:13:09 +00002134
2135/// isObjCPointerConversion - Determines whether this is an
2136/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2137/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002138bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002139 QualType& ConvertedType,
2140 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002141 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002142 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002144 // The set of qualifiers on the type we're converting from.
2145 Qualifiers FromQualifiers = FromType.getQualifiers();
2146
Steve Naroff14108da2009-07-10 23:34:53 +00002147 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002148 const ObjCObjectPointerType* ToObjCPtr =
2149 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002150 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002151 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002152
Steve Naroff14108da2009-07-10 23:34:53 +00002153 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002154 // If the pointee types are the same (ignoring qualifications),
2155 // then this is not a pointer conversion.
2156 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2157 FromObjCPtr->getPointeeType()))
2158 return false;
2159
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002160 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002161 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002162 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002163 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002164 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002165 return true;
2166 }
2167 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002168 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002169 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002170 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002171 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002172 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002173 return true;
2174 }
2175 // Objective C++: We're able to convert from a pointer to an
2176 // interface to a pointer to a different interface.
2177 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002178 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2179 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002180 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002181 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2182 FromObjCPtr->getPointeeType()))
2183 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002184 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002185 ToObjCPtr->getPointeeType(),
2186 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002188 return true;
2189 }
2190
2191 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2192 // Okay: this is some kind of implicit downcast of Objective-C
2193 // interfaces, which is permitted. However, we're going to
2194 // complain about it.
2195 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002197 ToObjCPtr->getPointeeType(),
2198 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002199 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002200 return true;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202 }
Steve Naroff14108da2009-07-10 23:34:53 +00002203 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002204 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002205 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002206 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002208 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002209 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002210 // to a block pointer type.
2211 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002212 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002213 return true;
2214 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002215 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002216 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002218 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002220 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002221 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002222 return true;
2223 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002224 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002225 return false;
2226
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002227 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002228 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002229 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002230 else if (const BlockPointerType *FromBlockPtr =
2231 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002232 FromPointeeType = FromBlockPtr->getPointeeType();
2233 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002234 return false;
2235
Douglas Gregorc7887512008-12-19 19:13:09 +00002236 // If we have pointers to pointers, recursively check whether this
2237 // is an Objective-C conversion.
2238 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2239 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2240 IncompatibleObjC)) {
2241 // We always complain about this conversion.
2242 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002243 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002245 return true;
2246 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002247 // Allow conversion of pointee being objective-c pointer to another one;
2248 // as in I* to id.
2249 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2250 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2251 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2252 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002253
Douglas Gregorda80f742010-12-01 21:43:58 +00002254 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002256 return true;
2257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002258
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002259 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002260 // differences in the argument and result types are in Objective-C
2261 // pointer conversions. If so, we permit the conversion (but
2262 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002263 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002264 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002265 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002266 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002267 if (FromFunctionType && ToFunctionType) {
2268 // If the function types are exactly the same, this isn't an
2269 // Objective-C pointer conversion.
2270 if (Context.getCanonicalType(FromPointeeType)
2271 == Context.getCanonicalType(ToPointeeType))
2272 return false;
2273
2274 // Perform the quick checks that will tell us whether these
2275 // function types are obviously different.
2276 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2277 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2278 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2279 return false;
2280
2281 bool HasObjCConversion = false;
2282 if (Context.getCanonicalType(FromFunctionType->getResultType())
2283 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2284 // Okay, the types match exactly. Nothing to do.
2285 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2286 ToFunctionType->getResultType(),
2287 ConvertedType, IncompatibleObjC)) {
2288 // Okay, we have an Objective-C pointer conversion.
2289 HasObjCConversion = true;
2290 } else {
2291 // Function types are too different. Abort.
2292 return false;
2293 }
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Douglas Gregorc7887512008-12-19 19:13:09 +00002295 // Check argument types.
2296 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2297 ArgIdx != NumArgs; ++ArgIdx) {
2298 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2299 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2300 if (Context.getCanonicalType(FromArgType)
2301 == Context.getCanonicalType(ToArgType)) {
2302 // Okay, the types match exactly. Nothing to do.
2303 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2304 ConvertedType, IncompatibleObjC)) {
2305 // Okay, we have an Objective-C pointer conversion.
2306 HasObjCConversion = true;
2307 } else {
2308 // Argument types are too different. Abort.
2309 return false;
2310 }
2311 }
2312
2313 if (HasObjCConversion) {
2314 // We had an Objective-C conversion. Allow this pointer
2315 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002316 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002317 IncompatibleObjC = true;
2318 return true;
2319 }
2320 }
2321
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002322 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002323}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324
John McCallf85e1932011-06-15 23:02:42 +00002325/// \brief Determine whether this is an Objective-C writeback conversion,
2326/// used for parameter passing when performing automatic reference counting.
2327///
2328/// \param FromType The type we're converting form.
2329///
2330/// \param ToType The type we're converting to.
2331///
2332/// \param ConvertedType The type that will be produced after applying
2333/// this conversion.
2334bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2335 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002336 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002337 Context.hasSameUnqualifiedType(FromType, ToType))
2338 return false;
2339
2340 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2341 QualType ToPointee;
2342 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2343 ToPointee = ToPointer->getPointeeType();
2344 else
2345 return false;
2346
2347 Qualifiers ToQuals = ToPointee.getQualifiers();
2348 if (!ToPointee->isObjCLifetimeType() ||
2349 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002350 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002351 return false;
2352
2353 // Argument must be a pointer to __strong to __weak.
2354 QualType FromPointee;
2355 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2356 FromPointee = FromPointer->getPointeeType();
2357 else
2358 return false;
2359
2360 Qualifiers FromQuals = FromPointee.getQualifiers();
2361 if (!FromPointee->isObjCLifetimeType() ||
2362 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2363 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2364 return false;
2365
2366 // Make sure that we have compatible qualifiers.
2367 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2368 if (!ToQuals.compatiblyIncludes(FromQuals))
2369 return false;
2370
2371 // Remove qualifiers from the pointee type we're converting from; they
2372 // aren't used in the compatibility check belong, and we'll be adding back
2373 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2374 FromPointee = FromPointee.getUnqualifiedType();
2375
2376 // The unqualified form of the pointee types must be compatible.
2377 ToPointee = ToPointee.getUnqualifiedType();
2378 bool IncompatibleObjC;
2379 if (Context.typesAreCompatible(FromPointee, ToPointee))
2380 FromPointee = ToPointee;
2381 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2382 IncompatibleObjC))
2383 return false;
2384
2385 /// \brief Construct the type we're converting to, which is a pointer to
2386 /// __autoreleasing pointee.
2387 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2388 ConvertedType = Context.getPointerType(FromPointee);
2389 return true;
2390}
2391
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002392bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2393 QualType& ConvertedType) {
2394 QualType ToPointeeType;
2395 if (const BlockPointerType *ToBlockPtr =
2396 ToType->getAs<BlockPointerType>())
2397 ToPointeeType = ToBlockPtr->getPointeeType();
2398 else
2399 return false;
2400
2401 QualType FromPointeeType;
2402 if (const BlockPointerType *FromBlockPtr =
2403 FromType->getAs<BlockPointerType>())
2404 FromPointeeType = FromBlockPtr->getPointeeType();
2405 else
2406 return false;
2407 // We have pointer to blocks, check whether the only
2408 // differences in the argument and result types are in Objective-C
2409 // pointer conversions. If so, we permit the conversion.
2410
2411 const FunctionProtoType *FromFunctionType
2412 = FromPointeeType->getAs<FunctionProtoType>();
2413 const FunctionProtoType *ToFunctionType
2414 = ToPointeeType->getAs<FunctionProtoType>();
2415
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002416 if (!FromFunctionType || !ToFunctionType)
2417 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002418
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002419 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002420 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002421
2422 // Perform the quick checks that will tell us whether these
2423 // function types are obviously different.
2424 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2425 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2426 return false;
2427
2428 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2429 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2430 if (FromEInfo != ToEInfo)
2431 return false;
2432
2433 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002434 if (Context.hasSameType(FromFunctionType->getResultType(),
2435 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002436 // Okay, the types match exactly. Nothing to do.
2437 } else {
2438 QualType RHS = FromFunctionType->getResultType();
2439 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002440 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002441 !RHS.hasQualifiers() && LHS.hasQualifiers())
2442 LHS = LHS.getUnqualifiedType();
2443
2444 if (Context.hasSameType(RHS,LHS)) {
2445 // OK exact match.
2446 } else if (isObjCPointerConversion(RHS, LHS,
2447 ConvertedType, IncompatibleObjC)) {
2448 if (IncompatibleObjC)
2449 return false;
2450 // Okay, we have an Objective-C pointer conversion.
2451 }
2452 else
2453 return false;
2454 }
2455
2456 // Check argument types.
2457 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2458 ArgIdx != NumArgs; ++ArgIdx) {
2459 IncompatibleObjC = false;
2460 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2461 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2462 if (Context.hasSameType(FromArgType, ToArgType)) {
2463 // Okay, the types match exactly. Nothing to do.
2464 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2465 ConvertedType, IncompatibleObjC)) {
2466 if (IncompatibleObjC)
2467 return false;
2468 // Okay, we have an Objective-C pointer conversion.
2469 } else
2470 // Argument types are too different. Abort.
2471 return false;
2472 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002473 if (LangOpts.ObjCAutoRefCount &&
2474 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2475 ToFunctionType))
2476 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002477
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002478 ConvertedType = ToType;
2479 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002480}
2481
Richard Trieu6efd4c52011-11-23 22:32:32 +00002482enum {
2483 ft_default,
2484 ft_different_class,
2485 ft_parameter_arity,
2486 ft_parameter_mismatch,
2487 ft_return_type,
2488 ft_qualifer_mismatch
2489};
2490
2491/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2492/// function types. Catches different number of parameter, mismatch in
2493/// parameter types, and different return types.
2494void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2495 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002496 // If either type is not valid, include no extra info.
2497 if (FromType.isNull() || ToType.isNull()) {
2498 PDiag << ft_default;
2499 return;
2500 }
2501
Richard Trieu6efd4c52011-11-23 22:32:32 +00002502 // Get the function type from the pointers.
2503 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2504 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2505 *ToMember = ToType->getAs<MemberPointerType>();
2506 if (FromMember->getClass() != ToMember->getClass()) {
2507 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2508 << QualType(FromMember->getClass(), 0);
2509 return;
2510 }
2511 FromType = FromMember->getPointeeType();
2512 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002513 }
2514
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002515 if (FromType->isPointerType())
2516 FromType = FromType->getPointeeType();
2517 if (ToType->isPointerType())
2518 ToType = ToType->getPointeeType();
2519
2520 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002521 FromType = FromType.getNonReferenceType();
2522 ToType = ToType.getNonReferenceType();
2523
Richard Trieu6efd4c52011-11-23 22:32:32 +00002524 // Don't print extra info for non-specialized template functions.
2525 if (FromType->isInstantiationDependentType() &&
2526 !FromType->getAs<TemplateSpecializationType>()) {
2527 PDiag << ft_default;
2528 return;
2529 }
2530
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002531 // No extra info for same types.
2532 if (Context.hasSameType(FromType, ToType)) {
2533 PDiag << ft_default;
2534 return;
2535 }
2536
Richard Trieu6efd4c52011-11-23 22:32:32 +00002537 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2538 *ToFunction = ToType->getAs<FunctionProtoType>();
2539
2540 // Both types need to be function types.
2541 if (!FromFunction || !ToFunction) {
2542 PDiag << ft_default;
2543 return;
2544 }
2545
2546 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2547 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2548 << FromFunction->getNumArgs();
2549 return;
2550 }
2551
2552 // Handle different parameter types.
2553 unsigned ArgPos;
2554 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2555 PDiag << ft_parameter_mismatch << ArgPos + 1
2556 << ToFunction->getArgType(ArgPos)
2557 << FromFunction->getArgType(ArgPos);
2558 return;
2559 }
2560
2561 // Handle different return type.
2562 if (!Context.hasSameType(FromFunction->getResultType(),
2563 ToFunction->getResultType())) {
2564 PDiag << ft_return_type << ToFunction->getResultType()
2565 << FromFunction->getResultType();
2566 return;
2567 }
2568
2569 unsigned FromQuals = FromFunction->getTypeQuals(),
2570 ToQuals = ToFunction->getTypeQuals();
2571 if (FromQuals != ToQuals) {
2572 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2573 return;
2574 }
2575
2576 // Unable to find a difference, so add no extra info.
2577 PDiag << ft_default;
2578}
2579
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002580/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002581/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002582/// they have same number of arguments. This routine assumes that Objective-C
2583/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002584/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002585/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002586bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002587 const FunctionProtoType *NewType,
2588 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002589 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002590 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2591 N = NewType->arg_type_begin(),
2592 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2593 if (!Context.hasSameType(*O, *N)) {
2594 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2595 return false;
2596 }
2597 }
2598 return true;
2599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002600
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002601 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2602 N = NewType->arg_type_begin(),
2603 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2604 QualType ToType = (*O);
2605 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002606 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002607 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2608 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002609 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2610 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2611 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2612 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002613 continue;
2614 }
John McCallc12c5bb2010-05-15 11:32:37 +00002615 else if (const ObjCObjectPointerType *PTTo =
2616 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002617 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002618 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002619 if (Context.hasSameUnqualifiedType(
2620 PTTo->getObjectType()->getBaseType(),
2621 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002622 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002623 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002624 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002626 }
2627 }
2628 return true;
2629}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002630
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002631/// CheckPointerConversion - Check the pointer conversion from the
2632/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002633/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002634/// conversions for which IsPointerConversion has already returned
2635/// true. It returns true and produces a diagnostic if there was an
2636/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002637bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002638 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002639 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002640 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002641 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002642 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002643
John McCalldaa8e4e2010-11-15 09:13:47 +00002644 Kind = CK_BitCast;
2645
David Blaikie50800fc2012-08-08 17:33:31 +00002646 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2647 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2648 Expr::NPCK_ZeroExpression) {
2649 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2650 DiagRuntimeBehavior(From->getExprLoc(), From,
2651 PDiag(diag::warn_impcast_bool_to_null_pointer)
2652 << ToType << From->getSourceRange());
2653 else if (!isUnevaluatedContext())
2654 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2655 << ToType << From->getSourceRange();
2656 }
John McCall1d9b3b22011-09-09 05:25:32 +00002657 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2658 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002659 QualType FromPointeeType = FromPtrType->getPointeeType(),
2660 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002661
Douglas Gregor5fccd362010-03-03 23:55:11 +00002662 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2663 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002664 // We must have a derived-to-base conversion. Check an
2665 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002666 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2667 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002668 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002669 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002670 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671
Anders Carlsson61faec12009-09-12 04:46:44 +00002672 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002673 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002674 }
2675 }
John McCall1d9b3b22011-09-09 05:25:32 +00002676 } else if (const ObjCObjectPointerType *ToPtrType =
2677 ToType->getAs<ObjCObjectPointerType>()) {
2678 if (const ObjCObjectPointerType *FromPtrType =
2679 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002680 // Objective-C++ conversions are always okay.
2681 // FIXME: We should have a different class of conversions for the
2682 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002683 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002684 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002685 } else if (FromType->isBlockPointerType()) {
2686 Kind = CK_BlockPointerToObjCPointerCast;
2687 } else {
2688 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002689 }
John McCall1d9b3b22011-09-09 05:25:32 +00002690 } else if (ToType->isBlockPointerType()) {
2691 if (!FromType->isBlockPointerType())
2692 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002693 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002694
2695 // We shouldn't fall into this case unless it's valid for other
2696 // reasons.
2697 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2698 Kind = CK_NullToPointer;
2699
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002700 return false;
2701}
2702
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002703/// IsMemberPointerConversion - Determines whether the conversion of the
2704/// expression From, which has the (possibly adjusted) type FromType, can be
2705/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2706/// If so, returns true and places the converted type (that might differ from
2707/// ToType in its cv-qualifiers at some level) into ConvertedType.
2708bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002709 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002710 bool InOverloadResolution,
2711 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002712 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002713 if (!ToTypePtr)
2714 return false;
2715
2716 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002717 if (From->isNullPointerConstant(Context,
2718 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2719 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720 ConvertedType = ToType;
2721 return true;
2722 }
2723
2724 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002725 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002726 if (!FromTypePtr)
2727 return false;
2728
2729 // A pointer to member of B can be converted to a pointer to member of D,
2730 // where D is derived from B (C++ 4.11p2).
2731 QualType FromClass(FromTypePtr->getClass(), 0);
2732 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002733
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002734 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002735 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002736 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2738 ToClass.getTypePtr());
2739 return true;
2740 }
2741
2742 return false;
2743}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002744
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002745/// CheckMemberPointerConversion - Check the member pointer conversion from the
2746/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002747/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748/// for which IsMemberPointerConversion has already returned true. It returns
2749/// true and produces a diagnostic if there was an error, or returns false
2750/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002751bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002752 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002753 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002754 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002755 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002756 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002757 if (!FromPtrType) {
2758 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002760 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002761 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002762 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002763 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002764 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002765
Ted Kremenek6217b802009-07-29 21:53:49 +00002766 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002767 assert(ToPtrType && "No member pointer cast has a target type "
2768 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002769
Sebastian Redl21593ac2009-01-28 18:33:18 +00002770 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2771 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002772
Sebastian Redl21593ac2009-01-28 18:33:18 +00002773 // FIXME: What about dependent types?
2774 assert(FromClass->isRecordType() && "Pointer into non-class.");
2775 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002776
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002778 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002779 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2780 assert(DerivationOkay &&
2781 "Should not have been called if derivation isn't OK.");
2782 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002783
Sebastian Redl21593ac2009-01-28 18:33:18 +00002784 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2785 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002786 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2787 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2788 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2789 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002790 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002791
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002792 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002793 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2794 << FromClass << ToClass << QualType(VBase, 0)
2795 << From->getSourceRange();
2796 return true;
2797 }
2798
John McCall6b2accb2010-02-10 09:31:12 +00002799 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002800 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2801 Paths.front(),
2802 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002803
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002804 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002805 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002806 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002807 return false;
2808}
2809
Douglas Gregor98cd5992008-10-21 23:43:52 +00002810/// IsQualificationConversion - Determines whether the conversion from
2811/// an rvalue of type FromType to ToType is a qualification conversion
2812/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002813///
2814/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2815/// when the qualification conversion involves a change in the Objective-C
2816/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002817bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002818Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002819 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002820 FromType = Context.getCanonicalType(FromType);
2821 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002822 ObjCLifetimeConversion = false;
2823
Douglas Gregor98cd5992008-10-21 23:43:52 +00002824 // If FromType and ToType are the same type, this is not a
2825 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002826 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002827 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002828
Douglas Gregor98cd5992008-10-21 23:43:52 +00002829 // (C++ 4.4p4):
2830 // A conversion can add cv-qualifiers at levels other than the first
2831 // in multi-level pointers, subject to the following rules: [...]
2832 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002833 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002834 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835 // Within each iteration of the loop, we check the qualifiers to
2836 // determine if this still looks like a qualification
2837 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002838 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002839 // until there are no more pointers or pointers-to-members left to
2840 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002841 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002842
Douglas Gregor621c92a2011-04-25 18:40:17 +00002843 Qualifiers FromQuals = FromType.getQualifiers();
2844 Qualifiers ToQuals = ToType.getQualifiers();
2845
John McCallf85e1932011-06-15 23:02:42 +00002846 // Objective-C ARC:
2847 // Check Objective-C lifetime conversions.
2848 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2849 UnwrappedAnyPointer) {
2850 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2851 ObjCLifetimeConversion = true;
2852 FromQuals.removeObjCLifetime();
2853 ToQuals.removeObjCLifetime();
2854 } else {
2855 // Qualification conversions cannot cast between different
2856 // Objective-C lifetime qualifiers.
2857 return false;
2858 }
2859 }
2860
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002861 // Allow addition/removal of GC attributes but not changing GC attributes.
2862 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2863 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2864 FromQuals.removeObjCGCAttr();
2865 ToQuals.removeObjCGCAttr();
2866 }
2867
Douglas Gregor98cd5992008-10-21 23:43:52 +00002868 // -- for every j > 0, if const is in cv 1,j then const is in cv
2869 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002870 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002871 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002872
Douglas Gregor98cd5992008-10-21 23:43:52 +00002873 // -- if the cv 1,j and cv 2,j are different, then const is in
2874 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002875 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002876 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002877 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Douglas Gregor98cd5992008-10-21 23:43:52 +00002879 // Keep track of whether all prior cv-qualifiers in the "to" type
2880 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002881 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002882 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002883 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002884
2885 // We are left with FromType and ToType being the pointee types
2886 // after unwrapping the original FromType and ToType the same number
2887 // of types. If we unwrapped any pointers, and if FromType and
2888 // ToType have the same unqualified type (since we checked
2889 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002890 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002891}
2892
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002893/// \brief - Determine whether this is a conversion from a scalar type to an
2894/// atomic type.
2895///
2896/// If successful, updates \c SCS's second and third steps in the conversion
2897/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002898static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2899 bool InOverloadResolution,
2900 StandardConversionSequence &SCS,
2901 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002902 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2903 if (!ToAtomic)
2904 return false;
2905
2906 StandardConversionSequence InnerSCS;
2907 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2908 InOverloadResolution, InnerSCS,
2909 CStyle, /*AllowObjCWritebackConversion=*/false))
2910 return false;
2911
2912 SCS.Second = InnerSCS.Second;
2913 SCS.setToType(1, InnerSCS.getToType(1));
2914 SCS.Third = InnerSCS.Third;
2915 SCS.QualificationIncludesObjCLifetime
2916 = InnerSCS.QualificationIncludesObjCLifetime;
2917 SCS.setToType(2, InnerSCS.getToType(2));
2918 return true;
2919}
2920
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002921static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2922 CXXConstructorDecl *Constructor,
2923 QualType Type) {
2924 const FunctionProtoType *CtorType =
2925 Constructor->getType()->getAs<FunctionProtoType>();
2926 if (CtorType->getNumArgs() > 0) {
2927 QualType FirstArg = CtorType->getArgType(0);
2928 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2929 return true;
2930 }
2931 return false;
2932}
2933
Sebastian Redl56a04282012-02-11 23:51:08 +00002934static OverloadingResult
2935IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2936 CXXRecordDecl *To,
2937 UserDefinedConversionSequence &User,
2938 OverloadCandidateSet &CandidateSet,
2939 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002940 DeclContext::lookup_result R = S.LookupConstructors(To);
2941 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002942 Con != ConEnd; ++Con) {
2943 NamedDecl *D = *Con;
2944 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2945
2946 // Find the constructor (which may be a template).
2947 CXXConstructorDecl *Constructor = 0;
2948 FunctionTemplateDecl *ConstructorTmpl
2949 = dyn_cast<FunctionTemplateDecl>(D);
2950 if (ConstructorTmpl)
2951 Constructor
2952 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2953 else
2954 Constructor = cast<CXXConstructorDecl>(D);
2955
2956 bool Usable = !Constructor->isInvalidDecl() &&
2957 S.isInitListConstructor(Constructor) &&
2958 (AllowExplicit || !Constructor->isExplicit());
2959 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002960 // If the first argument is (a reference to) the target type,
2961 // suppress conversions.
2962 bool SuppressUserConversions =
2963 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002964 if (ConstructorTmpl)
2965 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2966 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002967 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002968 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002969 else
2970 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002971 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002972 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002973 }
2974 }
2975
2976 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2977
2978 OverloadCandidateSet::iterator Best;
2979 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2980 case OR_Success: {
2981 // Record the standard conversion we used and the conversion function.
2982 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002983 QualType ThisType = Constructor->getThisType(S.Context);
2984 // Initializer lists don't have conversions as such.
2985 User.Before.setAsIdentityConversion();
2986 User.HadMultipleCandidates = HadMultipleCandidates;
2987 User.ConversionFunction = Constructor;
2988 User.FoundConversionFunction = Best->FoundDecl;
2989 User.After.setAsIdentityConversion();
2990 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2991 User.After.setAllToTypes(ToType);
2992 return OR_Success;
2993 }
2994
2995 case OR_No_Viable_Function:
2996 return OR_No_Viable_Function;
2997 case OR_Deleted:
2998 return OR_Deleted;
2999 case OR_Ambiguous:
3000 return OR_Ambiguous;
3001 }
3002
3003 llvm_unreachable("Invalid OverloadResult!");
3004}
3005
Douglas Gregor734d9862009-01-30 23:27:23 +00003006/// Determines whether there is a user-defined conversion sequence
3007/// (C++ [over.ics.user]) that converts expression From to the type
3008/// ToType. If such a conversion exists, User will contain the
3009/// user-defined conversion sequence that performs such a conversion
3010/// and this routine will return true. Otherwise, this routine returns
3011/// false and User is unspecified.
3012///
Douglas Gregor734d9862009-01-30 23:27:23 +00003013/// \param AllowExplicit true if the conversion should consider C++0x
3014/// "explicit" conversion functions as well as non-explicit conversion
3015/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003016static OverloadingResult
3017IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003018 UserDefinedConversionSequence &User,
3019 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003020 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003021 // Whether we will only visit constructors.
3022 bool ConstructorsOnly = false;
3023
3024 // If the type we are conversion to is a class type, enumerate its
3025 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003026 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003027 // C++ [over.match.ctor]p1:
3028 // When objects of class type are direct-initialized (8.5), or
3029 // copy-initialized from an expression of the same or a
3030 // derived class type (8.5), overload resolution selects the
3031 // constructor. [...] For copy-initialization, the candidate
3032 // functions are all the converting constructors (12.3.1) of
3033 // that class. The argument list is the expression-list within
3034 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003035 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003036 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003037 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003038 ConstructorsOnly = true;
3039
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003040 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003041 // RequireCompleteType may have returned true due to some invalid decl
3042 // during template instantiation, but ToType may be complete enough now
3043 // to try to recover.
3044 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003045 // We're not going to find any constructors.
3046 } else if (CXXRecordDecl *ToRecordDecl
3047 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003048
3049 Expr **Args = &From;
3050 unsigned NumArgs = 1;
3051 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003052 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003053 // But first, see if there is an init-list-contructor that will work.
3054 OverloadingResult Result = IsInitializerListConstructorConversion(
3055 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3056 if (Result != OR_No_Viable_Function)
3057 return Result;
3058 // Never mind.
3059 CandidateSet.clear();
3060
3061 // If we're list-initializing, we pass the individual elements as
3062 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003063 Args = InitList->getInits();
3064 NumArgs = InitList->getNumInits();
3065 ListInitializing = true;
3066 }
3067
David Blaikie3bc93e32012-12-19 00:45:41 +00003068 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3069 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003070 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003071 NamedDecl *D = *Con;
3072 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3073
Douglas Gregordec06662009-08-21 18:42:58 +00003074 // Find the constructor (which may be a template).
3075 CXXConstructorDecl *Constructor = 0;
3076 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003077 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003078 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003079 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003080 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3081 else
John McCall9aa472c2010-03-19 07:35:19 +00003082 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003083
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003084 bool Usable = !Constructor->isInvalidDecl();
3085 if (ListInitializing)
3086 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3087 else
3088 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3089 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003090 bool SuppressUserConversions = !ConstructorsOnly;
3091 if (SuppressUserConversions && ListInitializing) {
3092 SuppressUserConversions = false;
3093 if (NumArgs == 1) {
3094 // If the first argument is (a reference to) the target type,
3095 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003096 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3097 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003098 }
3099 }
Douglas Gregordec06662009-08-21 18:42:58 +00003100 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003101 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3102 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003103 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003104 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003105 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003106 // Allow one user-defined conversion when user specifies a
3107 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003108 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003109 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003110 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003111 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003112 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003113 }
3114 }
3115
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003116 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003117 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003118 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003119 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003120 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003121 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003122 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003123 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3124 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003125 std::pair<CXXRecordDecl::conversion_iterator,
3126 CXXRecordDecl::conversion_iterator>
3127 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3128 for (CXXRecordDecl::conversion_iterator
3129 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003130 DeclAccessPair FoundDecl = I.getPair();
3131 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003132 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3133 if (isa<UsingShadowDecl>(D))
3134 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003136 CXXConversionDecl *Conv;
3137 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003138 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3139 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003140 else
John McCall32daa422010-03-31 01:36:47 +00003141 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003142
3143 if (AllowExplicit || !Conv->isExplicit()) {
3144 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003145 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3146 ActingContext, From, ToType,
3147 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003148 else
John McCall120d63c2010-08-24 20:38:10 +00003149 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3150 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003151 }
3152 }
3153 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003154 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003155
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003156 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3157
Douglas Gregor60d62c22008-10-31 16:23:19 +00003158 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003159 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003160 case OR_Success:
3161 // Record the standard conversion we used and the conversion function.
3162 if (CXXConstructorDecl *Constructor
3163 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3164 // C++ [over.ics.user]p1:
3165 // If the user-defined conversion is specified by a
3166 // constructor (12.3.1), the initial standard conversion
3167 // sequence converts the source type to the type required by
3168 // the argument of the constructor.
3169 //
3170 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003171 if (isa<InitListExpr>(From)) {
3172 // Initializer lists don't have conversions as such.
3173 User.Before.setAsIdentityConversion();
3174 } else {
3175 if (Best->Conversions[0].isEllipsis())
3176 User.EllipsisConversion = true;
3177 else {
3178 User.Before = Best->Conversions[0].Standard;
3179 User.EllipsisConversion = false;
3180 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003181 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003182 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003183 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003184 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003185 User.After.setAsIdentityConversion();
3186 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3187 User.After.setAllToTypes(ToType);
3188 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003189 }
3190 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003191 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3192 // C++ [over.ics.user]p1:
3193 //
3194 // [...] If the user-defined conversion is specified by a
3195 // conversion function (12.3.2), the initial standard
3196 // conversion sequence converts the source type to the
3197 // implicit object parameter of the conversion function.
3198 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003199 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003200 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003201 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003202 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003203
John McCall120d63c2010-08-24 20:38:10 +00003204 // C++ [over.ics.user]p2:
3205 // The second standard conversion sequence converts the
3206 // result of the user-defined conversion to the target type
3207 // for the sequence. Since an implicit conversion sequence
3208 // is an initialization, the special rules for
3209 // initialization by user-defined conversion apply when
3210 // selecting the best user-defined conversion for a
3211 // user-defined conversion sequence (see 13.3.3 and
3212 // 13.3.3.1).
3213 User.After = Best->FinalConversion;
3214 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003215 }
David Blaikie7530c032012-01-17 06:56:22 +00003216 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003217
John McCall120d63c2010-08-24 20:38:10 +00003218 case OR_No_Viable_Function:
3219 return OR_No_Viable_Function;
3220 case OR_Deleted:
3221 // No conversion here! We're done.
3222 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223
John McCall120d63c2010-08-24 20:38:10 +00003224 case OR_Ambiguous:
3225 return OR_Ambiguous;
3226 }
3227
David Blaikie7530c032012-01-17 06:56:22 +00003228 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003229}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003230
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003231bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003232Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003233 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003234 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003236 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003237 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003238 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003239 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003240 diag::err_typecheck_ambiguous_condition)
3241 << From->getType() << ToType << From->getSourceRange();
3242 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003243 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003244 diag::err_typecheck_nonviable_condition)
3245 << From->getType() << ToType << From->getSourceRange();
3246 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003247 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003248 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003249 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003250}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003251
Douglas Gregorb734e242012-02-22 17:32:19 +00003252/// \brief Compare the user-defined conversion functions or constructors
3253/// of two user-defined conversion sequences to determine whether any ordering
3254/// is possible.
3255static ImplicitConversionSequence::CompareKind
3256compareConversionFunctions(Sema &S,
3257 FunctionDecl *Function1,
3258 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003259 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003260 return ImplicitConversionSequence::Indistinguishable;
3261
3262 // Objective-C++:
3263 // If both conversion functions are implicitly-declared conversions from
3264 // a lambda closure type to a function pointer and a block pointer,
3265 // respectively, always prefer the conversion to a function pointer,
3266 // because the function pointer is more lightweight and is more likely
3267 // to keep code working.
3268 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3269 if (!Conv1)
3270 return ImplicitConversionSequence::Indistinguishable;
3271
3272 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3273 if (!Conv2)
3274 return ImplicitConversionSequence::Indistinguishable;
3275
3276 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3277 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3278 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3279 if (Block1 != Block2)
3280 return Block1? ImplicitConversionSequence::Worse
3281 : ImplicitConversionSequence::Better;
3282 }
3283
3284 return ImplicitConversionSequence::Indistinguishable;
3285}
3286
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003287/// CompareImplicitConversionSequences - Compare two implicit
3288/// conversion sequences to determine whether one is better than the
3289/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003290static ImplicitConversionSequence::CompareKind
3291CompareImplicitConversionSequences(Sema &S,
3292 const ImplicitConversionSequence& ICS1,
3293 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003294{
3295 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3296 // conversion sequences (as defined in 13.3.3.1)
3297 // -- a standard conversion sequence (13.3.3.1.1) is a better
3298 // conversion sequence than a user-defined conversion sequence or
3299 // an ellipsis conversion sequence, and
3300 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3301 // conversion sequence than an ellipsis conversion sequence
3302 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003303 //
John McCall1d318332010-01-12 00:44:57 +00003304 // C++0x [over.best.ics]p10:
3305 // For the purpose of ranking implicit conversion sequences as
3306 // described in 13.3.3.2, the ambiguous conversion sequence is
3307 // treated as a user-defined sequence that is indistinguishable
3308 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003309 if (ICS1.getKindRank() < ICS2.getKindRank())
3310 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003311 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003312 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003313
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003314 // The following checks require both conversion sequences to be of
3315 // the same kind.
3316 if (ICS1.getKind() != ICS2.getKind())
3317 return ImplicitConversionSequence::Indistinguishable;
3318
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003319 ImplicitConversionSequence::CompareKind Result =
3320 ImplicitConversionSequence::Indistinguishable;
3321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003322 // Two implicit conversion sequences of the same form are
3323 // indistinguishable conversion sequences unless one of the
3324 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003325 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003326 Result = CompareStandardConversionSequences(S,
3327 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003328 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003329 // User-defined conversion sequence U1 is a better conversion
3330 // sequence than another user-defined conversion sequence U2 if
3331 // they contain the same user-defined conversion function or
3332 // constructor and if the second standard conversion sequence of
3333 // U1 is better than the second standard conversion sequence of
3334 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003335 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003336 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003337 Result = CompareStandardConversionSequences(S,
3338 ICS1.UserDefined.After,
3339 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003340 else
3341 Result = compareConversionFunctions(S,
3342 ICS1.UserDefined.ConversionFunction,
3343 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003344 }
3345
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003346 // List-initialization sequence L1 is a better conversion sequence than
3347 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3348 // for some X and L2 does not.
3349 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003350 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003351 ICS1.isListInitializationSequence() &&
3352 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003353 if (ICS1.isStdInitializerListElement() &&
3354 !ICS2.isStdInitializerListElement())
3355 return ImplicitConversionSequence::Better;
3356 if (!ICS1.isStdInitializerListElement() &&
3357 ICS2.isStdInitializerListElement())
3358 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003359 }
3360
3361 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003362}
3363
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003364static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3365 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3366 Qualifiers Quals;
3367 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003368 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003371 return Context.hasSameUnqualifiedType(T1, T2);
3372}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
Douglas Gregorad323a82010-01-27 03:51:04 +00003374// Per 13.3.3.2p3, compare the given standard conversion sequences to
3375// determine if one is a proper subset of the other.
3376static ImplicitConversionSequence::CompareKind
3377compareStandardConversionSubsets(ASTContext &Context,
3378 const StandardConversionSequence& SCS1,
3379 const StandardConversionSequence& SCS2) {
3380 ImplicitConversionSequence::CompareKind Result
3381 = ImplicitConversionSequence::Indistinguishable;
3382
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003383 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003384 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003385 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3386 return ImplicitConversionSequence::Better;
3387 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3388 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389
Douglas Gregorad323a82010-01-27 03:51:04 +00003390 if (SCS1.Second != SCS2.Second) {
3391 if (SCS1.Second == ICK_Identity)
3392 Result = ImplicitConversionSequence::Better;
3393 else if (SCS2.Second == ICK_Identity)
3394 Result = ImplicitConversionSequence::Worse;
3395 else
3396 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003397 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003398 return ImplicitConversionSequence::Indistinguishable;
3399
3400 if (SCS1.Third == SCS2.Third) {
3401 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3402 : ImplicitConversionSequence::Indistinguishable;
3403 }
3404
3405 if (SCS1.Third == ICK_Identity)
3406 return Result == ImplicitConversionSequence::Worse
3407 ? ImplicitConversionSequence::Indistinguishable
3408 : ImplicitConversionSequence::Better;
3409
3410 if (SCS2.Third == ICK_Identity)
3411 return Result == ImplicitConversionSequence::Better
3412 ? ImplicitConversionSequence::Indistinguishable
3413 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003414
Douglas Gregorad323a82010-01-27 03:51:04 +00003415 return ImplicitConversionSequence::Indistinguishable;
3416}
3417
Douglas Gregor440a4832011-01-26 14:52:12 +00003418/// \brief Determine whether one of the given reference bindings is better
3419/// than the other based on what kind of bindings they are.
3420static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3421 const StandardConversionSequence &SCS2) {
3422 // C++0x [over.ics.rank]p3b4:
3423 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3424 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003425 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003426 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003428 // reference*.
3429 //
3430 // FIXME: Rvalue references. We're going rogue with the above edits,
3431 // because the semantics in the current C++0x working paper (N3225 at the
3432 // time of this writing) break the standard definition of std::forward
3433 // and std::reference_wrapper when dealing with references to functions.
3434 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003435 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3436 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3437 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438
Douglas Gregor440a4832011-01-26 14:52:12 +00003439 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3440 SCS2.IsLvalueReference) ||
3441 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3442 !SCS2.IsLvalueReference);
3443}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003445/// CompareStandardConversionSequences - Compare two standard
3446/// conversion sequences to determine whether one is better than the
3447/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003448static ImplicitConversionSequence::CompareKind
3449CompareStandardConversionSequences(Sema &S,
3450 const StandardConversionSequence& SCS1,
3451 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003452{
3453 // Standard conversion sequence S1 is a better conversion sequence
3454 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3455
3456 // -- S1 is a proper subsequence of S2 (comparing the conversion
3457 // sequences in the canonical form defined by 13.3.3.1.1,
3458 // excluding any Lvalue Transformation; the identity conversion
3459 // sequence is considered to be a subsequence of any
3460 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003461 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003462 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003463 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003464
3465 // -- the rank of S1 is better than the rank of S2 (by the rules
3466 // defined below), or, if not that,
3467 ImplicitConversionRank Rank1 = SCS1.getRank();
3468 ImplicitConversionRank Rank2 = SCS2.getRank();
3469 if (Rank1 < Rank2)
3470 return ImplicitConversionSequence::Better;
3471 else if (Rank2 < Rank1)
3472 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003473
Douglas Gregor57373262008-10-22 14:17:15 +00003474 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3475 // are indistinguishable unless one of the following rules
3476 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Douglas Gregor57373262008-10-22 14:17:15 +00003478 // A conversion that is not a conversion of a pointer, or
3479 // pointer to member, to bool is better than another conversion
3480 // that is such a conversion.
3481 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3482 return SCS2.isPointerConversionToBool()
3483 ? ImplicitConversionSequence::Better
3484 : ImplicitConversionSequence::Worse;
3485
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003486 // C++ [over.ics.rank]p4b2:
3487 //
3488 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003489 // conversion of B* to A* is better than conversion of B* to
3490 // void*, and conversion of A* to void* is better than conversion
3491 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003492 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003493 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003494 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003495 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003496 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3497 // Exactly one of the conversion sequences is a conversion to
3498 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003499 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3500 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003501 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3502 // Neither conversion sequence converts to a void pointer; compare
3503 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003504 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003505 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003506 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003507 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3508 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003509 // Both conversion sequences are conversions to void
3510 // pointers. Compare the source types to determine if there's an
3511 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003512 QualType FromType1 = SCS1.getFromType();
3513 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003514
3515 // Adjust the types we're converting from via the array-to-pointer
3516 // conversion, if we need to.
3517 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003518 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003519 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003520 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003521
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003522 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3523 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003524
John McCall120d63c2010-08-24 20:38:10 +00003525 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003526 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003527 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003528 return ImplicitConversionSequence::Worse;
3529
3530 // Objective-C++: If one interface is more specific than the
3531 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003532 const ObjCObjectPointerType* FromObjCPtr1
3533 = FromType1->getAs<ObjCObjectPointerType>();
3534 const ObjCObjectPointerType* FromObjCPtr2
3535 = FromType2->getAs<ObjCObjectPointerType>();
3536 if (FromObjCPtr1 && FromObjCPtr2) {
3537 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3538 FromObjCPtr2);
3539 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3540 FromObjCPtr1);
3541 if (AssignLeft != AssignRight) {
3542 return AssignLeft? ImplicitConversionSequence::Better
3543 : ImplicitConversionSequence::Worse;
3544 }
Douglas Gregor01919692009-12-13 21:37:05 +00003545 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003546 }
Douglas Gregor57373262008-10-22 14:17:15 +00003547
3548 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3549 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003550 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003551 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003552 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003553
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003554 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003555 // Check for a better reference binding based on the kind of bindings.
3556 if (isBetterReferenceBindingKind(SCS1, SCS2))
3557 return ImplicitConversionSequence::Better;
3558 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3559 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003561 // C++ [over.ics.rank]p3b4:
3562 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3563 // which the references refer are the same type except for
3564 // top-level cv-qualifiers, and the type to which the reference
3565 // initialized by S2 refers is more cv-qualified than the type
3566 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003567 QualType T1 = SCS1.getToType(2);
3568 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003569 T1 = S.Context.getCanonicalType(T1);
3570 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003571 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003572 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3573 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003574 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003575 // Objective-C++ ARC: If the references refer to objects with different
3576 // lifetimes, prefer bindings that don't change lifetime.
3577 if (SCS1.ObjCLifetimeConversionBinding !=
3578 SCS2.ObjCLifetimeConversionBinding) {
3579 return SCS1.ObjCLifetimeConversionBinding
3580 ? ImplicitConversionSequence::Worse
3581 : ImplicitConversionSequence::Better;
3582 }
3583
Chandler Carruth6df868e2010-12-12 08:17:55 +00003584 // If the type is an array type, promote the element qualifiers to the
3585 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003586 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003587 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003588 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003589 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003590 if (T2.isMoreQualifiedThan(T1))
3591 return ImplicitConversionSequence::Better;
3592 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003593 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003594 }
3595 }
Douglas Gregor57373262008-10-22 14:17:15 +00003596
Francois Pichet1c98d622011-09-18 21:37:37 +00003597 // In Microsoft mode, prefer an integral conversion to a
3598 // floating-to-integral conversion if the integral conversion
3599 // is between types of the same size.
3600 // For example:
3601 // void f(float);
3602 // void f(int);
3603 // int main {
3604 // long a;
3605 // f(a);
3606 // }
3607 // Here, MSVC will call f(int) instead of generating a compile error
3608 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003609 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003610 SCS1.Second == ICK_Integral_Conversion &&
3611 SCS2.Second == ICK_Floating_Integral &&
3612 S.Context.getTypeSize(SCS1.getFromType()) ==
3613 S.Context.getTypeSize(SCS1.getToType(2)))
3614 return ImplicitConversionSequence::Better;
3615
Douglas Gregor57373262008-10-22 14:17:15 +00003616 return ImplicitConversionSequence::Indistinguishable;
3617}
3618
3619/// CompareQualificationConversions - Compares two standard conversion
3620/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003621/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3622ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003623CompareQualificationConversions(Sema &S,
3624 const StandardConversionSequence& SCS1,
3625 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003626 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003627 // -- S1 and S2 differ only in their qualification conversion and
3628 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3629 // cv-qualification signature of type T1 is a proper subset of
3630 // the cv-qualification signature of type T2, and S1 is not the
3631 // deprecated string literal array-to-pointer conversion (4.2).
3632 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3633 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3634 return ImplicitConversionSequence::Indistinguishable;
3635
3636 // FIXME: the example in the standard doesn't use a qualification
3637 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003638 QualType T1 = SCS1.getToType(2);
3639 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003640 T1 = S.Context.getCanonicalType(T1);
3641 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003642 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003643 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3644 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003645
3646 // If the types are the same, we won't learn anything by unwrapped
3647 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003648 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003649 return ImplicitConversionSequence::Indistinguishable;
3650
Chandler Carruth28e318c2009-12-29 07:16:59 +00003651 // If the type is an array type, promote the element qualifiers to the type
3652 // for comparison.
3653 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003654 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003655 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003656 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003657
Mike Stump1eb44332009-09-09 15:08:12 +00003658 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003659 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003660
3661 // Objective-C++ ARC:
3662 // Prefer qualification conversions not involving a change in lifetime
3663 // to qualification conversions that do not change lifetime.
3664 if (SCS1.QualificationIncludesObjCLifetime !=
3665 SCS2.QualificationIncludesObjCLifetime) {
3666 Result = SCS1.QualificationIncludesObjCLifetime
3667 ? ImplicitConversionSequence::Worse
3668 : ImplicitConversionSequence::Better;
3669 }
3670
John McCall120d63c2010-08-24 20:38:10 +00003671 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003672 // Within each iteration of the loop, we check the qualifiers to
3673 // determine if this still looks like a qualification
3674 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003675 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003676 // until there are no more pointers or pointers-to-members left
3677 // to unwrap. This essentially mimics what
3678 // IsQualificationConversion does, but here we're checking for a
3679 // strict subset of qualifiers.
3680 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3681 // The qualifiers are the same, so this doesn't tell us anything
3682 // about how the sequences rank.
3683 ;
3684 else if (T2.isMoreQualifiedThan(T1)) {
3685 // T1 has fewer qualifiers, so it could be the better sequence.
3686 if (Result == ImplicitConversionSequence::Worse)
3687 // Neither has qualifiers that are a subset of the other's
3688 // qualifiers.
3689 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Douglas Gregor57373262008-10-22 14:17:15 +00003691 Result = ImplicitConversionSequence::Better;
3692 } else if (T1.isMoreQualifiedThan(T2)) {
3693 // T2 has fewer qualifiers, so it could be the better sequence.
3694 if (Result == ImplicitConversionSequence::Better)
3695 // Neither has qualifiers that are a subset of the other's
3696 // qualifiers.
3697 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Douglas Gregor57373262008-10-22 14:17:15 +00003699 Result = ImplicitConversionSequence::Worse;
3700 } else {
3701 // Qualifiers are disjoint.
3702 return ImplicitConversionSequence::Indistinguishable;
3703 }
3704
3705 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003706 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003707 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003708 }
3709
Douglas Gregor57373262008-10-22 14:17:15 +00003710 // Check that the winning standard conversion sequence isn't using
3711 // the deprecated string literal array to pointer conversion.
3712 switch (Result) {
3713 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003714 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003715 Result = ImplicitConversionSequence::Indistinguishable;
3716 break;
3717
3718 case ImplicitConversionSequence::Indistinguishable:
3719 break;
3720
3721 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003722 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003723 Result = ImplicitConversionSequence::Indistinguishable;
3724 break;
3725 }
3726
3727 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003728}
3729
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003730/// CompareDerivedToBaseConversions - Compares two standard conversion
3731/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003732/// various kinds of derived-to-base conversions (C++
3733/// [over.ics.rank]p4b3). As part of these checks, we also look at
3734/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003735ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003736CompareDerivedToBaseConversions(Sema &S,
3737 const StandardConversionSequence& SCS1,
3738 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003739 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003740 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003741 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003742 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003743
3744 // Adjust the types we're converting from via the array-to-pointer
3745 // conversion, if we need to.
3746 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003747 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003749 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003750
3751 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003752 FromType1 = S.Context.getCanonicalType(FromType1);
3753 ToType1 = S.Context.getCanonicalType(ToType1);
3754 FromType2 = S.Context.getCanonicalType(FromType2);
3755 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003756
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003757 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003758 //
3759 // If class B is derived directly or indirectly from class A and
3760 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003761 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003762 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003763 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003764 SCS2.Second == ICK_Pointer_Conversion &&
3765 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3766 FromType1->isPointerType() && FromType2->isPointerType() &&
3767 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003768 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003769 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003770 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003771 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003772 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003773 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003774 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003775 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003776
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003777 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003778 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003779 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003780 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003781 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003782 return ImplicitConversionSequence::Worse;
3783 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003784
3785 // -- conversion of B* to A* is better than conversion of C* to A*,
3786 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003787 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003788 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003789 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003790 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003791 }
3792 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3793 SCS2.Second == ICK_Pointer_Conversion) {
3794 const ObjCObjectPointerType *FromPtr1
3795 = FromType1->getAs<ObjCObjectPointerType>();
3796 const ObjCObjectPointerType *FromPtr2
3797 = FromType2->getAs<ObjCObjectPointerType>();
3798 const ObjCObjectPointerType *ToPtr1
3799 = ToType1->getAs<ObjCObjectPointerType>();
3800 const ObjCObjectPointerType *ToPtr2
3801 = ToType2->getAs<ObjCObjectPointerType>();
3802
3803 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3804 // Apply the same conversion ranking rules for Objective-C pointer types
3805 // that we do for C++ pointers to class types. However, we employ the
3806 // Objective-C pseudo-subtyping relationship used for assignment of
3807 // Objective-C pointer types.
3808 bool FromAssignLeft
3809 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3810 bool FromAssignRight
3811 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3812 bool ToAssignLeft
3813 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3814 bool ToAssignRight
3815 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3816
3817 // A conversion to an a non-id object pointer type or qualified 'id'
3818 // type is better than a conversion to 'id'.
3819 if (ToPtr1->isObjCIdType() &&
3820 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3821 return ImplicitConversionSequence::Worse;
3822 if (ToPtr2->isObjCIdType() &&
3823 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3824 return ImplicitConversionSequence::Better;
3825
3826 // A conversion to a non-id object pointer type is better than a
3827 // conversion to a qualified 'id' type
3828 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3829 return ImplicitConversionSequence::Worse;
3830 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3831 return ImplicitConversionSequence::Better;
3832
3833 // A conversion to an a non-Class object pointer type or qualified 'Class'
3834 // type is better than a conversion to 'Class'.
3835 if (ToPtr1->isObjCClassType() &&
3836 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3837 return ImplicitConversionSequence::Worse;
3838 if (ToPtr2->isObjCClassType() &&
3839 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3840 return ImplicitConversionSequence::Better;
3841
3842 // A conversion to a non-Class object pointer type is better than a
3843 // conversion to a qualified 'Class' type.
3844 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3845 return ImplicitConversionSequence::Worse;
3846 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3847 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Douglas Gregor395cc372011-01-31 18:51:41 +00003849 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3850 if (S.Context.hasSameType(FromType1, FromType2) &&
3851 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3852 (ToAssignLeft != ToAssignRight))
3853 return ToAssignLeft? ImplicitConversionSequence::Worse
3854 : ImplicitConversionSequence::Better;
3855
3856 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3857 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3858 (FromAssignLeft != FromAssignRight))
3859 return FromAssignLeft? ImplicitConversionSequence::Better
3860 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003861 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003862 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003863
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003864 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3866 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3867 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003869 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003871 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003872 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003873 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003875 ToType2->getAs<MemberPointerType>();
3876 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3877 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3878 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3879 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3880 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3881 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3882 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3883 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003884 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003885 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003886 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003887 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003888 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003889 return ImplicitConversionSequence::Better;
3890 }
3891 // conversion of B::* to C::* is better than conversion of A::* to C::*
3892 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003893 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003894 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003895 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003896 return ImplicitConversionSequence::Worse;
3897 }
3898 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003899
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003900 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003901 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003902 // -- binding of an expression of type C to a reference of type
3903 // B& is better than binding an expression of type C to a
3904 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003905 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3906 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3907 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003908 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003909 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003910 return ImplicitConversionSequence::Worse;
3911 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003912
Douglas Gregor225c41e2008-11-03 19:09:14 +00003913 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003914 // -- binding of an expression of type B to a reference of type
3915 // A& is better than binding an expression of type C to a
3916 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003917 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3918 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3919 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003920 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003921 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003922 return ImplicitConversionSequence::Worse;
3923 }
3924 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003925
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003926 return ImplicitConversionSequence::Indistinguishable;
3927}
3928
Douglas Gregorabe183d2010-04-13 16:31:36 +00003929/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3930/// determine whether they are reference-related,
3931/// reference-compatible, reference-compatible with added
3932/// qualification, or incompatible, for use in C++ initialization by
3933/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3934/// type, and the first type (T1) is the pointee type of the reference
3935/// type being initialized.
3936Sema::ReferenceCompareResult
3937Sema::CompareReferenceRelationship(SourceLocation Loc,
3938 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003939 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003940 bool &ObjCConversion,
3941 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003942 assert(!OrigT1->isReferenceType() &&
3943 "T1 must be the pointee type of the reference type");
3944 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3945
3946 QualType T1 = Context.getCanonicalType(OrigT1);
3947 QualType T2 = Context.getCanonicalType(OrigT2);
3948 Qualifiers T1Quals, T2Quals;
3949 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3950 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3951
3952 // C++ [dcl.init.ref]p4:
3953 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3954 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3955 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003956 DerivedToBase = false;
3957 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003958 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003959 if (UnqualT1 == UnqualT2) {
3960 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003961 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003962 IsDerivedFrom(UnqualT2, UnqualT1))
3963 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003964 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3965 UnqualT2->isObjCObjectOrInterfaceType() &&
3966 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3967 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003968 else
3969 return Ref_Incompatible;
3970
3971 // At this point, we know that T1 and T2 are reference-related (at
3972 // least).
3973
3974 // If the type is an array type, promote the element qualifiers to the type
3975 // for comparison.
3976 if (isa<ArrayType>(T1) && T1Quals)
3977 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3978 if (isa<ArrayType>(T2) && T2Quals)
3979 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3980
3981 // C++ [dcl.init.ref]p4:
3982 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3983 // reference-related to T2 and cv1 is the same cv-qualification
3984 // as, or greater cv-qualification than, cv2. For purposes of
3985 // overload resolution, cases for which cv1 is greater
3986 // cv-qualification than cv2 are identified as
3987 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003988 //
3989 // Note that we also require equivalence of Objective-C GC and address-space
3990 // qualifiers when performing these computations, so that e.g., an int in
3991 // address space 1 is not reference-compatible with an int in address
3992 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003993 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3994 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3995 T1Quals.removeObjCLifetime();
3996 T2Quals.removeObjCLifetime();
3997 ObjCLifetimeConversion = true;
3998 }
3999
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004000 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004001 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004002 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004003 return Ref_Compatible_With_Added_Qualification;
4004 else
4005 return Ref_Related;
4006}
4007
Douglas Gregor604eb652010-08-11 02:15:33 +00004008/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004009/// with DeclType. Return true if something definite is found.
4010static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004011FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4012 QualType DeclType, SourceLocation DeclLoc,
4013 Expr *Init, QualType T2, bool AllowRvalues,
4014 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004015 assert(T2->isRecordType() && "Can only find conversions of record types.");
4016 CXXRecordDecl *T2RecordDecl
4017 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4018
4019 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004020 std::pair<CXXRecordDecl::conversion_iterator,
4021 CXXRecordDecl::conversion_iterator>
4022 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4023 for (CXXRecordDecl::conversion_iterator
4024 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004025 NamedDecl *D = *I;
4026 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4027 if (isa<UsingShadowDecl>(D))
4028 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4029
4030 FunctionTemplateDecl *ConvTemplate
4031 = dyn_cast<FunctionTemplateDecl>(D);
4032 CXXConversionDecl *Conv;
4033 if (ConvTemplate)
4034 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4035 else
4036 Conv = cast<CXXConversionDecl>(D);
4037
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004039 // explicit conversions, skip it.
4040 if (!AllowExplicit && Conv->isExplicit())
4041 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004042
Douglas Gregor604eb652010-08-11 02:15:33 +00004043 if (AllowRvalues) {
4044 bool DerivedToBase = false;
4045 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004046 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004047
4048 // If we are initializing an rvalue reference, don't permit conversion
4049 // functions that return lvalues.
4050 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4051 const ReferenceType *RefType
4052 = Conv->getConversionType()->getAs<LValueReferenceType>();
4053 if (RefType && !RefType->getPointeeType()->isFunctionType())
4054 continue;
4055 }
4056
Douglas Gregor604eb652010-08-11 02:15:33 +00004057 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004058 S.CompareReferenceRelationship(
4059 DeclLoc,
4060 Conv->getConversionType().getNonReferenceType()
4061 .getUnqualifiedType(),
4062 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004063 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004064 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004065 continue;
4066 } else {
4067 // If the conversion function doesn't return a reference type,
4068 // it can't be considered for this conversion. An rvalue reference
4069 // is only acceptable if its referencee is a function type.
4070
4071 const ReferenceType *RefType =
4072 Conv->getConversionType()->getAs<ReferenceType>();
4073 if (!RefType ||
4074 (!RefType->isLValueReferenceType() &&
4075 !RefType->getPointeeType()->isFunctionType()))
4076 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004078
Douglas Gregor604eb652010-08-11 02:15:33 +00004079 if (ConvTemplate)
4080 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004081 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004082 else
4083 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004084 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004085 }
4086
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004087 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4088
Sebastian Redl4680bf22010-06-30 18:13:39 +00004089 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004090 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004091 case OR_Success:
4092 // C++ [over.ics.ref]p1:
4093 //
4094 // [...] If the parameter binds directly to the result of
4095 // applying a conversion function to the argument
4096 // expression, the implicit conversion sequence is a
4097 // user-defined conversion sequence (13.3.3.1.2), with the
4098 // second standard conversion sequence either an identity
4099 // conversion or, if the conversion function returns an
4100 // entity of a type that is a derived class of the parameter
4101 // type, a derived-to-base Conversion.
4102 if (!Best->FinalConversion.DirectBinding)
4103 return false;
4104
4105 ICS.setUserDefined();
4106 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4107 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004108 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004109 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004110 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004111 ICS.UserDefined.EllipsisConversion = false;
4112 assert(ICS.UserDefined.After.ReferenceBinding &&
4113 ICS.UserDefined.After.DirectBinding &&
4114 "Expected a direct reference binding!");
4115 return true;
4116
4117 case OR_Ambiguous:
4118 ICS.setAmbiguous();
4119 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4120 Cand != CandidateSet.end(); ++Cand)
4121 if (Cand->Viable)
4122 ICS.Ambiguous.addConversion(Cand->Function);
4123 return true;
4124
4125 case OR_No_Viable_Function:
4126 case OR_Deleted:
4127 // There was no suitable conversion, or we found a deleted
4128 // conversion; continue with other checks.
4129 return false;
4130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004131
David Blaikie7530c032012-01-17 06:56:22 +00004132 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004133}
4134
Douglas Gregorabe183d2010-04-13 16:31:36 +00004135/// \brief Compute an implicit conversion sequence for reference
4136/// initialization.
4137static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004138TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004139 SourceLocation DeclLoc,
4140 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004141 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004142 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4143
4144 // Most paths end in a failed conversion.
4145 ImplicitConversionSequence ICS;
4146 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4147
4148 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4149 QualType T2 = Init->getType();
4150
4151 // If the initializer is the address of an overloaded function, try
4152 // to resolve the overloaded function. If all goes well, T2 is the
4153 // type of the resulting function.
4154 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4155 DeclAccessPair Found;
4156 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4157 false, Found))
4158 T2 = Fn->getType();
4159 }
4160
4161 // Compute some basic properties of the types and the initializer.
4162 bool isRValRef = DeclType->isRValueReferenceType();
4163 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004164 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004165 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004166 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004167 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004168 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004169 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004170
Douglas Gregorabe183d2010-04-13 16:31:36 +00004171
Sebastian Redl4680bf22010-06-30 18:13:39 +00004172 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004173 // A reference to type "cv1 T1" is initialized by an expression
4174 // of type "cv2 T2" as follows:
4175
Sebastian Redl4680bf22010-06-30 18:13:39 +00004176 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004177 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004178 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4179 // reference-compatible with "cv2 T2," or
4180 //
4181 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4182 if (InitCategory.isLValue() &&
4183 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004184 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004185 // When a parameter of reference type binds directly (8.5.3)
4186 // to an argument expression, the implicit conversion sequence
4187 // is the identity conversion, unless the argument expression
4188 // has a type that is a derived class of the parameter type,
4189 // in which case the implicit conversion sequence is a
4190 // derived-to-base Conversion (13.3.3.1).
4191 ICS.setStandard();
4192 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004193 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4194 : ObjCConversion? ICK_Compatible_Conversion
4195 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 ICS.Standard.Third = ICK_Identity;
4197 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4198 ICS.Standard.setToType(0, T2);
4199 ICS.Standard.setToType(1, T1);
4200 ICS.Standard.setToType(2, T1);
4201 ICS.Standard.ReferenceBinding = true;
4202 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004203 ICS.Standard.IsLvalueReference = !isRValRef;
4204 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4205 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004206 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004207 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004208 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004209
Sebastian Redl4680bf22010-06-30 18:13:39 +00004210 // Nothing more to do: the inaccessibility/ambiguity check for
4211 // derived-to-base conversions is suppressed when we're
4212 // computing the implicit conversion sequence (C++
4213 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004214 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004215 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004216
Sebastian Redl4680bf22010-06-30 18:13:39 +00004217 // -- has a class type (i.e., T2 is a class type), where T1 is
4218 // not reference-related to T2, and can be implicitly
4219 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4220 // is reference-compatible with "cv3 T3" 92) (this
4221 // conversion is selected by enumerating the applicable
4222 // conversion functions (13.3.1.6) and choosing the best
4223 // one through overload resolution (13.3)),
4224 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004225 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004226 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004227 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4228 Init, T2, /*AllowRvalues=*/false,
4229 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004230 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004231 }
4232 }
4233
Sebastian Redl4680bf22010-06-30 18:13:39 +00004234 // -- Otherwise, the reference shall be an lvalue reference to a
4235 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004236 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004238 // We actually handle one oddity of C++ [over.ics.ref] at this
4239 // point, which is that, due to p2 (which short-circuits reference
4240 // binding by only attempting a simple conversion for non-direct
4241 // bindings) and p3's strange wording, we allow a const volatile
4242 // reference to bind to an rvalue. Hence the check for the presence
4243 // of "const" rather than checking for "const" being the only
4244 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004245 // This is also the point where rvalue references and lvalue inits no longer
4246 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004247 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004248 return ICS;
4249
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004250 // -- If the initializer expression
4251 //
4252 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004253 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004254 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4255 (InitCategory.isXValue() ||
4256 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4257 (InitCategory.isLValue() && T2->isFunctionType()))) {
4258 ICS.setStandard();
4259 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004261 : ObjCConversion? ICK_Compatible_Conversion
4262 : ICK_Identity;
4263 ICS.Standard.Third = ICK_Identity;
4264 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4265 ICS.Standard.setToType(0, T2);
4266 ICS.Standard.setToType(1, T1);
4267 ICS.Standard.setToType(2, T1);
4268 ICS.Standard.ReferenceBinding = true;
4269 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4270 // binding unless we're binding to a class prvalue.
4271 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4272 // allow the use of rvalue references in C++98/03 for the benefit of
4273 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004275 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004276 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004277 ICS.Standard.IsLvalueReference = !isRValRef;
4278 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004279 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004280 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004281 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004284 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004286 // -- has a class type (i.e., T2 is a class type), where T1 is not
4287 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288 // an xvalue, class prvalue, or function lvalue of type
4289 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004290 // "cv3 T3",
4291 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004293 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004295 // class subobject).
4296 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004297 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004298 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4299 Init, T2, /*AllowRvalues=*/true,
4300 AllowExplicit)) {
4301 // In the second case, if the reference is an rvalue reference
4302 // and the second standard conversion sequence of the
4303 // user-defined conversion sequence includes an lvalue-to-rvalue
4304 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004306 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4307 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4308
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004309 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004311
Douglas Gregorabe183d2010-04-13 16:31:36 +00004312 // -- Otherwise, a temporary of type "cv1 T1" is created and
4313 // initialized from the initializer expression using the
4314 // rules for a non-reference copy initialization (8.5). The
4315 // reference is then bound to the temporary. If T1 is
4316 // reference-related to T2, cv1 must be the same
4317 // cv-qualification as, or greater cv-qualification than,
4318 // cv2; otherwise, the program is ill-formed.
4319 if (RefRelationship == Sema::Ref_Related) {
4320 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4321 // we would be reference-compatible or reference-compatible with
4322 // added qualification. But that wasn't the case, so the reference
4323 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004324 //
4325 // Note that we only want to check address spaces and cvr-qualifiers here.
4326 // ObjC GC and lifetime qualifiers aren't important.
4327 Qualifiers T1Quals = T1.getQualifiers();
4328 Qualifiers T2Quals = T2.getQualifiers();
4329 T1Quals.removeObjCGCAttr();
4330 T1Quals.removeObjCLifetime();
4331 T2Quals.removeObjCGCAttr();
4332 T2Quals.removeObjCLifetime();
4333 if (!T1Quals.compatiblyIncludes(T2Quals))
4334 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004335 }
4336
4337 // If at least one of the types is a class type, the types are not
4338 // related, and we aren't allowed any user conversions, the
4339 // reference binding fails. This case is important for breaking
4340 // recursion, since TryImplicitConversion below will attempt to
4341 // create a temporary through the use of a copy constructor.
4342 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4343 (T1->isRecordType() || T2->isRecordType()))
4344 return ICS;
4345
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004346 // If T1 is reference-related to T2 and the reference is an rvalue
4347 // reference, the initializer expression shall not be an lvalue.
4348 if (RefRelationship >= Sema::Ref_Related &&
4349 isRValRef && Init->Classify(S.Context).isLValue())
4350 return ICS;
4351
Douglas Gregorabe183d2010-04-13 16:31:36 +00004352 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004353 // When a parameter of reference type is not bound directly to
4354 // an argument expression, the conversion sequence is the one
4355 // required to convert the argument expression to the
4356 // underlying type of the reference according to
4357 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4358 // to copy-initializing a temporary of the underlying type with
4359 // the argument expression. Any difference in top-level
4360 // cv-qualification is subsumed by the initialization itself
4361 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004362 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4363 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004364 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004365 /*CStyle=*/false,
4366 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004367
4368 // Of course, that's still a reference binding.
4369 if (ICS.isStandard()) {
4370 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004371 ICS.Standard.IsLvalueReference = !isRValRef;
4372 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4373 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004374 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004375 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004376 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004377 // Don't allow rvalue references to bind to lvalues.
4378 if (DeclType->isRValueReferenceType()) {
4379 if (const ReferenceType *RefType
4380 = ICS.UserDefined.ConversionFunction->getResultType()
4381 ->getAs<LValueReferenceType>()) {
4382 if (!RefType->getPointeeType()->isFunctionType()) {
4383 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4384 DeclType);
4385 return ICS;
4386 }
4387 }
4388 }
4389
Douglas Gregorabe183d2010-04-13 16:31:36 +00004390 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004391 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4392 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4393 ICS.UserDefined.After.BindsToRvalue = true;
4394 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4395 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004396 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004397
Douglas Gregorabe183d2010-04-13 16:31:36 +00004398 return ICS;
4399}
4400
Sebastian Redl5405b812011-10-16 18:19:34 +00004401static ImplicitConversionSequence
4402TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4403 bool SuppressUserConversions,
4404 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004405 bool AllowObjCWritebackConversion,
4406 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004407
4408/// TryListConversion - Try to copy-initialize a value of type ToType from the
4409/// initializer list From.
4410static ImplicitConversionSequence
4411TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4412 bool SuppressUserConversions,
4413 bool InOverloadResolution,
4414 bool AllowObjCWritebackConversion) {
4415 // C++11 [over.ics.list]p1:
4416 // When an argument is an initializer list, it is not an expression and
4417 // special rules apply for converting it to a parameter type.
4418
4419 ImplicitConversionSequence Result;
4420 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004421 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004422
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004423 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004424 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004425 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004426 return Result;
4427
Sebastian Redl5405b812011-10-16 18:19:34 +00004428 // C++11 [over.ics.list]p2:
4429 // If the parameter type is std::initializer_list<X> or "array of X" and
4430 // all the elements can be implicitly converted to X, the implicit
4431 // conversion sequence is the worst conversion necessary to convert an
4432 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004433 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004434 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004435 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004436 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004437 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004438 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004439 if (!X.isNull()) {
4440 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4441 Expr *Init = From->getInit(i);
4442 ImplicitConversionSequence ICS =
4443 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4444 InOverloadResolution,
4445 AllowObjCWritebackConversion);
4446 // If a single element isn't convertible, fail.
4447 if (ICS.isBad()) {
4448 Result = ICS;
4449 break;
4450 }
4451 // Otherwise, look for the worst conversion.
4452 if (Result.isBad() ||
4453 CompareImplicitConversionSequences(S, ICS, Result) ==
4454 ImplicitConversionSequence::Worse)
4455 Result = ICS;
4456 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004457
4458 // For an empty list, we won't have computed any conversion sequence.
4459 // Introduce the identity conversion sequence.
4460 if (From->getNumInits() == 0) {
4461 Result.setStandard();
4462 Result.Standard.setAsIdentityConversion();
4463 Result.Standard.setFromType(ToType);
4464 Result.Standard.setAllToTypes(ToType);
4465 }
4466
Sebastian Redlfe592282012-01-17 22:49:48 +00004467 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004468 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004469 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004470 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004471
4472 // C++11 [over.ics.list]p3:
4473 // Otherwise, if the parameter is a non-aggregate class X and overload
4474 // resolution chooses a single best constructor [...] the implicit
4475 // conversion sequence is a user-defined conversion sequence. If multiple
4476 // constructors are viable but none is better than the others, the
4477 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004478 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4479 // This function can deal with initializer lists.
4480 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4481 /*AllowExplicit=*/false,
4482 InOverloadResolution, /*CStyle=*/false,
4483 AllowObjCWritebackConversion);
4484 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004485 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004486 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004487
4488 // C++11 [over.ics.list]p4:
4489 // Otherwise, if the parameter has an aggregate type which can be
4490 // initialized from the initializer list [...] the implicit conversion
4491 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004492 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004493 // Type is an aggregate, argument is an init list. At this point it comes
4494 // down to checking whether the initialization works.
4495 // FIXME: Find out whether this parameter is consumed or not.
4496 InitializedEntity Entity =
4497 InitializedEntity::InitializeParameter(S.Context, ToType,
4498 /*Consumed=*/false);
4499 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4500 Result.setUserDefined();
4501 Result.UserDefined.Before.setAsIdentityConversion();
4502 // Initializer lists don't have a type.
4503 Result.UserDefined.Before.setFromType(QualType());
4504 Result.UserDefined.Before.setAllToTypes(QualType());
4505
4506 Result.UserDefined.After.setAsIdentityConversion();
4507 Result.UserDefined.After.setFromType(ToType);
4508 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004509 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004510 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004511 return Result;
4512 }
4513
4514 // C++11 [over.ics.list]p5:
4515 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004516 if (ToType->isReferenceType()) {
4517 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4518 // mention initializer lists in any way. So we go by what list-
4519 // initialization would do and try to extrapolate from that.
4520
4521 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4522
4523 // If the initializer list has a single element that is reference-related
4524 // to the parameter type, we initialize the reference from that.
4525 if (From->getNumInits() == 1) {
4526 Expr *Init = From->getInit(0);
4527
4528 QualType T2 = Init->getType();
4529
4530 // If the initializer is the address of an overloaded function, try
4531 // to resolve the overloaded function. If all goes well, T2 is the
4532 // type of the resulting function.
4533 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4534 DeclAccessPair Found;
4535 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4536 Init, ToType, false, Found))
4537 T2 = Fn->getType();
4538 }
4539
4540 // Compute some basic properties of the types and the initializer.
4541 bool dummy1 = false;
4542 bool dummy2 = false;
4543 bool dummy3 = false;
4544 Sema::ReferenceCompareResult RefRelationship
4545 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4546 dummy2, dummy3);
4547
4548 if (RefRelationship >= Sema::Ref_Related)
4549 return TryReferenceInit(S, Init, ToType,
4550 /*FIXME:*/From->getLocStart(),
4551 SuppressUserConversions,
4552 /*AllowExplicit=*/false);
4553 }
4554
4555 // Otherwise, we bind the reference to a temporary created from the
4556 // initializer list.
4557 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4558 InOverloadResolution,
4559 AllowObjCWritebackConversion);
4560 if (Result.isFailure())
4561 return Result;
4562 assert(!Result.isEllipsis() &&
4563 "Sub-initialization cannot result in ellipsis conversion.");
4564
4565 // Can we even bind to a temporary?
4566 if (ToType->isRValueReferenceType() ||
4567 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4568 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4569 Result.UserDefined.After;
4570 SCS.ReferenceBinding = true;
4571 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4572 SCS.BindsToRvalue = true;
4573 SCS.BindsToFunctionLvalue = false;
4574 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4575 SCS.ObjCLifetimeConversionBinding = false;
4576 } else
4577 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4578 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004579 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004580 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004581
4582 // C++11 [over.ics.list]p6:
4583 // Otherwise, if the parameter type is not a class:
4584 if (!ToType->isRecordType()) {
4585 // - if the initializer list has one element, the implicit conversion
4586 // sequence is the one required to convert the element to the
4587 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004588 unsigned NumInits = From->getNumInits();
4589 if (NumInits == 1)
4590 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4591 SuppressUserConversions,
4592 InOverloadResolution,
4593 AllowObjCWritebackConversion);
4594 // - if the initializer list has no elements, the implicit conversion
4595 // sequence is the identity conversion.
4596 else if (NumInits == 0) {
4597 Result.setStandard();
4598 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004599 Result.Standard.setFromType(ToType);
4600 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004601 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004602 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004603 return Result;
4604 }
4605
4606 // C++11 [over.ics.list]p7:
4607 // In all cases other than those enumerated above, no conversion is possible
4608 return Result;
4609}
4610
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004611/// TryCopyInitialization - Try to copy-initialize a value of type
4612/// ToType from the expression From. Return the implicit conversion
4613/// sequence required to pass this argument, which may be a bad
4614/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004615/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004616/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004617static ImplicitConversionSequence
4618TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004620 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004621 bool AllowObjCWritebackConversion,
4622 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004623 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4624 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4625 InOverloadResolution,AllowObjCWritebackConversion);
4626
Douglas Gregorabe183d2010-04-13 16:31:36 +00004627 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004628 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004629 /*FIXME:*/From->getLocStart(),
4630 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004631 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004632
John McCall120d63c2010-08-24 20:38:10 +00004633 return TryImplicitConversion(S, From, ToType,
4634 SuppressUserConversions,
4635 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004636 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004637 /*CStyle=*/false,
4638 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004639}
4640
Anna Zaksf3546ee2011-07-28 19:46:48 +00004641static bool TryCopyInitialization(const CanQualType FromQTy,
4642 const CanQualType ToQTy,
4643 Sema &S,
4644 SourceLocation Loc,
4645 ExprValueKind FromVK) {
4646 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4647 ImplicitConversionSequence ICS =
4648 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4649
4650 return !ICS.isBad();
4651}
4652
Douglas Gregor96176b32008-11-18 23:14:02 +00004653/// TryObjectArgumentInitialization - Try to initialize the object
4654/// parameter of the given member function (@c Method) from the
4655/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004656static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004657TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004658 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004659 CXXMethodDecl *Method,
4660 CXXRecordDecl *ActingContext) {
4661 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004662 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4663 // const volatile object.
4664 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4665 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004666 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004667
4668 // Set up the conversion sequence as a "bad" conversion, to allow us
4669 // to exit early.
4670 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004671
4672 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004673 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004674 FromType = PT->getPointeeType();
4675
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004676 // When we had a pointer, it's implicitly dereferenced, so we
4677 // better have an lvalue.
4678 assert(FromClassification.isLValue());
4679 }
4680
Anders Carlssona552f7c2009-05-01 18:34:30 +00004681 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004682
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004683 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004685 // parameter is
4686 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004687 // - "lvalue reference to cv X" for functions declared without a
4688 // ref-qualifier or with the & ref-qualifier
4689 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004690 // ref-qualifier
4691 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004692 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004693 // cv-qualification on the member function declaration.
4694 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004696 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004697 // (C++ [over.match.funcs]p5). We perform a simplified version of
4698 // reference binding here, that allows class rvalues to bind to
4699 // non-constant references.
4700
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004701 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004702 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004704 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004705 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004706 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004707 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004708 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004709 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004710
4711 // Check that we have either the same type or a derived type. It
4712 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004713 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004714 ImplicitConversionKind SecondKind;
4715 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4716 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004717 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004718 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004719 else {
John McCallb1bdc622010-02-25 01:37:24 +00004720 ICS.setBad(BadConversionSequence::unrelated_class,
4721 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004722 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004723 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004724
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004725 // Check the ref-qualifier.
4726 switch (Method->getRefQualifier()) {
4727 case RQ_None:
4728 // Do nothing; we don't care about lvalueness or rvalueness.
4729 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004730
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004731 case RQ_LValue:
4732 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4733 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004734 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004735 ImplicitParamType);
4736 return ICS;
4737 }
4738 break;
4739
4740 case RQ_RValue:
4741 if (!FromClassification.isRValue()) {
4742 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004744 ImplicitParamType);
4745 return ICS;
4746 }
4747 break;
4748 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004749
Douglas Gregor96176b32008-11-18 23:14:02 +00004750 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004751 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004752 ICS.Standard.setAsIdentityConversion();
4753 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004754 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004755 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004756 ICS.Standard.ReferenceBinding = true;
4757 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004758 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004759 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004760 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4761 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4762 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004763 return ICS;
4764}
4765
4766/// PerformObjectArgumentInitialization - Perform initialization of
4767/// the implicit object parameter for the given Method with the given
4768/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004769ExprResult
4770Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004771 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004772 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004773 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004774 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004775 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004776 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004777
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004778 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004779 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004780 FromRecordType = PT->getPointeeType();
4781 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004782 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004783 } else {
4784 FromRecordType = From->getType();
4785 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004786 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004787 }
4788
John McCall701c89e2009-12-03 04:06:58 +00004789 // Note that we always use the true parent context when performing
4790 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004791 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004792 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4793 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004794 if (ICS.isBad()) {
4795 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4796 Qualifiers FromQs = FromRecordType.getQualifiers();
4797 Qualifiers ToQs = DestType.getQualifiers();
4798 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4799 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004800 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004801 diag::err_member_function_call_bad_cvr)
4802 << Method->getDeclName() << FromRecordType << (CVR - 1)
4803 << From->getSourceRange();
4804 Diag(Method->getLocation(), diag::note_previous_decl)
4805 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004806 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004807 }
4808 }
4809
Daniel Dunbar96a00142012-03-09 18:35:03 +00004810 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004811 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004812 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004813 }
Mike Stump1eb44332009-09-09 15:08:12 +00004814
John Wiegley429bb272011-04-08 18:41:53 +00004815 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4816 ExprResult FromRes =
4817 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4818 if (FromRes.isInvalid())
4819 return ExprError();
4820 From = FromRes.take();
4821 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004822
Douglas Gregor5fccd362010-03-03 23:55:11 +00004823 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004824 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004825 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004826 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004827}
4828
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004829/// TryContextuallyConvertToBool - Attempt to contextually convert the
4830/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004831static ImplicitConversionSequence
4832TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004833 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004834 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004835 // FIXME: Are these flags correct?
4836 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004837 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004838 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004839 /*CStyle=*/false,
4840 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004841}
4842
4843/// PerformContextuallyConvertToBool - Perform a contextual conversion
4844/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004845ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004846 if (checkPlaceholderForOverload(*this, From))
4847 return ExprError();
4848
John McCall120d63c2010-08-24 20:38:10 +00004849 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004850 if (!ICS.isBad())
4851 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004852
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004853 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004854 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004855 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004856 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004857 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004858}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859
Richard Smith8ef7b202012-01-18 23:55:52 +00004860/// Check that the specified conversion is permitted in a converted constant
4861/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4862/// is acceptable.
4863static bool CheckConvertedConstantConversions(Sema &S,
4864 StandardConversionSequence &SCS) {
4865 // Since we know that the target type is an integral or unscoped enumeration
4866 // type, most conversion kinds are impossible. All possible First and Third
4867 // conversions are fine.
4868 switch (SCS.Second) {
4869 case ICK_Identity:
4870 case ICK_Integral_Promotion:
4871 case ICK_Integral_Conversion:
4872 return true;
4873
4874 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004875 // Conversion from an integral or unscoped enumeration type to bool is
4876 // classified as ICK_Boolean_Conversion, but it's also an integral
4877 // conversion, so it's permitted in a converted constant expression.
4878 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4879 SCS.getToType(2)->isBooleanType();
4880
Richard Smith8ef7b202012-01-18 23:55:52 +00004881 case ICK_Floating_Integral:
4882 case ICK_Complex_Real:
4883 return false;
4884
4885 case ICK_Lvalue_To_Rvalue:
4886 case ICK_Array_To_Pointer:
4887 case ICK_Function_To_Pointer:
4888 case ICK_NoReturn_Adjustment:
4889 case ICK_Qualification:
4890 case ICK_Compatible_Conversion:
4891 case ICK_Vector_Conversion:
4892 case ICK_Vector_Splat:
4893 case ICK_Derived_To_Base:
4894 case ICK_Pointer_Conversion:
4895 case ICK_Pointer_Member:
4896 case ICK_Block_Pointer_Conversion:
4897 case ICK_Writeback_Conversion:
4898 case ICK_Floating_Promotion:
4899 case ICK_Complex_Promotion:
4900 case ICK_Complex_Conversion:
4901 case ICK_Floating_Conversion:
4902 case ICK_TransparentUnionConversion:
4903 llvm_unreachable("unexpected second conversion kind");
4904
4905 case ICK_Num_Conversion_Kinds:
4906 break;
4907 }
4908
4909 llvm_unreachable("unknown conversion kind");
4910}
4911
4912/// CheckConvertedConstantExpression - Check that the expression From is a
4913/// converted constant expression of type T, perform the conversion and produce
4914/// the converted expression, per C++11 [expr.const]p3.
4915ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4916 llvm::APSInt &Value,
4917 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004918 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004919 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4920
4921 if (checkPlaceholderForOverload(*this, From))
4922 return ExprError();
4923
4924 // C++11 [expr.const]p3 with proposed wording fixes:
4925 // A converted constant expression of type T is a core constant expression,
4926 // implicitly converted to a prvalue of type T, where the converted
4927 // expression is a literal constant expression and the implicit conversion
4928 // sequence contains only user-defined conversions, lvalue-to-rvalue
4929 // conversions, integral promotions, and integral conversions other than
4930 // narrowing conversions.
4931 ImplicitConversionSequence ICS =
4932 TryImplicitConversion(From, T,
4933 /*SuppressUserConversions=*/false,
4934 /*AllowExplicit=*/false,
4935 /*InOverloadResolution=*/false,
4936 /*CStyle=*/false,
4937 /*AllowObjcWritebackConversion=*/false);
4938 StandardConversionSequence *SCS = 0;
4939 switch (ICS.getKind()) {
4940 case ImplicitConversionSequence::StandardConversion:
4941 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004942 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004943 diag::err_typecheck_converted_constant_expression_disallowed)
4944 << From->getType() << From->getSourceRange() << T;
4945 SCS = &ICS.Standard;
4946 break;
4947 case ImplicitConversionSequence::UserDefinedConversion:
4948 // We are converting from class type to an integral or enumeration type, so
4949 // the Before sequence must be trivial.
4950 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004951 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004952 diag::err_typecheck_converted_constant_expression_disallowed)
4953 << From->getType() << From->getSourceRange() << T;
4954 SCS = &ICS.UserDefined.After;
4955 break;
4956 case ImplicitConversionSequence::AmbiguousConversion:
4957 case ImplicitConversionSequence::BadConversion:
4958 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004959 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004960 diag::err_typecheck_converted_constant_expression)
4961 << From->getType() << From->getSourceRange() << T;
4962 return ExprError();
4963
4964 case ImplicitConversionSequence::EllipsisConversion:
4965 llvm_unreachable("ellipsis conversion in converted constant expression");
4966 }
4967
4968 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4969 if (Result.isInvalid())
4970 return Result;
4971
4972 // Check for a narrowing implicit conversion.
4973 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004974 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004975 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4976 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004977 case NK_Variable_Narrowing:
4978 // Implicit conversion to a narrower type, and the value is not a constant
4979 // expression. We'll diagnose this in a moment.
4980 case NK_Not_Narrowing:
4981 break;
4982
4983 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004984 Diag(From->getLocStart(),
4985 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4986 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004987 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004988 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004989 break;
4990
4991 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004992 Diag(From->getLocStart(),
4993 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4994 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004995 << CCE << /*Constant*/0 << From->getType() << T;
4996 break;
4997 }
4998
4999 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005000 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005001 Expr::EvalResult Eval;
5002 Eval.Diag = &Notes;
5003
5004 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5005 // The expression can't be folded, so we can't keep it at this position in
5006 // the AST.
5007 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005008 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005009 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005010
5011 if (Notes.empty()) {
5012 // It's a constant expression.
5013 return Result;
5014 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005015 }
5016
5017 // It's not a constant expression. Produce an appropriate diagnostic.
5018 if (Notes.size() == 1 &&
5019 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5020 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5021 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005022 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005023 << CCE << From->getSourceRange();
5024 for (unsigned I = 0; I < Notes.size(); ++I)
5025 Diag(Notes[I].first, Notes[I].second);
5026 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005027 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005028}
5029
John McCall0bcc9bc2011-09-09 06:11:02 +00005030/// dropPointerConversions - If the given standard conversion sequence
5031/// involves any pointer conversions, remove them. This may change
5032/// the result type of the conversion sequence.
5033static void dropPointerConversion(StandardConversionSequence &SCS) {
5034 if (SCS.Second == ICK_Pointer_Conversion) {
5035 SCS.Second = ICK_Identity;
5036 SCS.Third = ICK_Identity;
5037 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5038 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005039}
John McCall120d63c2010-08-24 20:38:10 +00005040
John McCall0bcc9bc2011-09-09 06:11:02 +00005041/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5042/// convert the expression From to an Objective-C pointer type.
5043static ImplicitConversionSequence
5044TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5045 // Do an implicit conversion to 'id'.
5046 QualType Ty = S.Context.getObjCIdType();
5047 ImplicitConversionSequence ICS
5048 = TryImplicitConversion(S, From, Ty,
5049 // FIXME: Are these flags correct?
5050 /*SuppressUserConversions=*/false,
5051 /*AllowExplicit=*/true,
5052 /*InOverloadResolution=*/false,
5053 /*CStyle=*/false,
5054 /*AllowObjCWritebackConversion=*/false);
5055
5056 // Strip off any final conversions to 'id'.
5057 switch (ICS.getKind()) {
5058 case ImplicitConversionSequence::BadConversion:
5059 case ImplicitConversionSequence::AmbiguousConversion:
5060 case ImplicitConversionSequence::EllipsisConversion:
5061 break;
5062
5063 case ImplicitConversionSequence::UserDefinedConversion:
5064 dropPointerConversion(ICS.UserDefined.After);
5065 break;
5066
5067 case ImplicitConversionSequence::StandardConversion:
5068 dropPointerConversion(ICS.Standard);
5069 break;
5070 }
5071
5072 return ICS;
5073}
5074
5075/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5076/// conversion of the expression From to an Objective-C pointer type.
5077ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005078 if (checkPlaceholderForOverload(*this, From))
5079 return ExprError();
5080
John McCallc12c5bb2010-05-15 11:32:37 +00005081 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005082 ImplicitConversionSequence ICS =
5083 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005084 if (!ICS.isBad())
5085 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005086 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005087}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005088
Richard Smithf39aec12012-02-04 07:07:42 +00005089/// Determine whether the provided type is an integral type, or an enumeration
5090/// type of a permitted flavor.
5091static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5092 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5093 : T->isIntegralOrUnscopedEnumerationType();
5094}
5095
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005096/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005097/// enumeration type.
5098///
5099/// This routine will attempt to convert an expression of class type to an
5100/// integral or enumeration type, if that class type only has a single
5101/// conversion to an integral or enumeration type.
5102///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005103/// \param Loc The source location of the construct that requires the
5104/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005105///
James Dennett40ae6662012-06-22 08:52:37 +00005106/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005107///
James Dennett40ae6662012-06-22 08:52:37 +00005108/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005109///
Richard Smithf39aec12012-02-04 07:07:42 +00005110/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5111/// enumerations should be considered.
5112///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005113/// \returns The expression, converted to an integral or enumeration type if
5114/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005115ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005116Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005117 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005118 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005119 // We can't perform any more checking for type-dependent expressions.
5120 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005121 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Eli Friedmanceccab92012-01-26 00:26:18 +00005123 // Process placeholders immediately.
5124 if (From->hasPlaceholderType()) {
5125 ExprResult result = CheckPlaceholderExpr(From);
5126 if (result.isInvalid()) return result;
5127 From = result.take();
5128 }
5129
Douglas Gregorc30614b2010-06-29 23:17:37 +00005130 // If the expression already has integral or enumeration type, we're golden.
5131 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005132 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005133 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005134
5135 // FIXME: Check for missing '()' if T is a function type?
5136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137 // 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 +00005138 // expression of integral or enumeration type.
5139 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005140 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005141 if (!Diagnoser.Suppress)
5142 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005143 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Douglas Gregorc30614b2010-06-29 23:17:37 +00005146 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005147 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005148 ICEConvertDiagnoser &Diagnoser;
5149 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005150
Douglas Gregorab41fe92012-05-04 22:38:52 +00005151 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5152 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005153
5154 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005155 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005156 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005157 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005158
5159 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005160 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005161
Douglas Gregorc30614b2010-06-29 23:17:37 +00005162 // Look for a conversion to an integral or enumeration type.
5163 UnresolvedSet<4> ViableConversions;
5164 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005165 std::pair<CXXRecordDecl::conversion_iterator,
5166 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005167 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005168
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005169 bool HadMultipleCandidates
5170 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005171
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005172 for (CXXRecordDecl::conversion_iterator
5173 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005174 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005175 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5176 if (isIntegralOrEnumerationType(
5177 Conversion->getConversionType().getNonReferenceType(),
5178 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005179 if (Conversion->isExplicit())
5180 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5181 else
5182 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5183 }
Richard Smithf39aec12012-02-04 07:07:42 +00005184 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186
Douglas Gregorc30614b2010-06-29 23:17:37 +00005187 switch (ViableConversions.size()) {
5188 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005189 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005190 DeclAccessPair Found = ExplicitConversions[0];
5191 CXXConversionDecl *Conversion
5192 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
Douglas Gregorc30614b2010-06-29 23:17:37 +00005194 // The user probably meant to invoke the given explicit
5195 // conversion; use it.
5196 QualType ConvTy
5197 = Conversion->getConversionType().getNonReferenceType();
5198 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005199 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005200
Douglas Gregorab41fe92012-05-04 22:38:52 +00005201 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202 << FixItHint::CreateInsertion(From->getLocStart(),
5203 "static_cast<" + TypeStr + ">(")
5204 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5205 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005206 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005207
5208 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005209 // explicit conversion function.
5210 if (isSFINAEContext())
5211 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212
Douglas Gregorc30614b2010-06-29 23:17:37 +00005213 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005214 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5215 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005216 if (Result.isInvalid())
5217 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005218 // Record usage of conversion in an implicit cast.
5219 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5220 CK_UserDefinedConversion,
5221 Result.get(), 0,
5222 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005223 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005224
Douglas Gregorc30614b2010-06-29 23:17:37 +00005225 // We'll complain below about a non-integral condition type.
5226 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005227
Douglas Gregorc30614b2010-06-29 23:17:37 +00005228 case 1: {
5229 // Apply this conversion.
5230 DeclAccessPair Found = ViableConversions[0];
5231 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005232
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005233 CXXConversionDecl *Conversion
5234 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5235 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005236 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005237 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005238 if (isSFINAEContext())
5239 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Douglas Gregorab41fe92012-05-04 22:38:52 +00005241 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5242 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005245 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5246 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005247 if (Result.isInvalid())
5248 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005249 // Record usage of conversion in an implicit cast.
5250 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5251 CK_UserDefinedConversion,
5252 Result.get(), 0,
5253 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005254 break;
5255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005256
Douglas Gregorc30614b2010-06-29 23:17:37 +00005257 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005258 if (Diagnoser.Suppress)
5259 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005260
Douglas Gregorab41fe92012-05-04 22:38:52 +00005261 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005262 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5263 CXXConversionDecl *Conv
5264 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5265 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005266 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005267 }
John McCall9ae2f072010-08-23 23:25:46 +00005268 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Richard Smith282e7e62012-02-04 09:53:13 +00005271 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005272 !Diagnoser.Suppress) {
5273 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5274 << From->getSourceRange();
5275 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005276
Eli Friedmanceccab92012-01-26 00:26:18 +00005277 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005278}
5279
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005280/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005281/// candidate functions, using the given function call arguments. If
5282/// @p SuppressUserConversions, then don't allow user-defined
5283/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005284///
James Dennett699c9042012-06-15 07:13:21 +00005285/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005286/// based on an incomplete set of function arguments. This feature is used by
5287/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005288void
5289Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005290 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005291 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005292 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005293 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005294 bool PartialOverloading,
5295 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005296 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005297 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005298 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005299 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005300 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005301
Douglas Gregor88a35142008-12-22 05:46:06 +00005302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005303 if (!isa<CXXConstructorDecl>(Method)) {
5304 // If we get here, it's because we're calling a member function
5305 // that is named without a member access expression (e.g.,
5306 // "this->f") that was either written explicitly or created
5307 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005308 // function, e.g., X::f(). We use an empty type for the implied
5309 // object argument (C++ [over.call.func]p3), and the acting context
5310 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005311 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005312 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005313 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005314 return;
5315 }
5316 // We treat a constructor like a non-member function, since its object
5317 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005318 }
5319
Douglas Gregorfd476482009-11-13 23:59:09 +00005320 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005321 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005322
Douglas Gregor7edfb692009-11-23 12:27:39 +00005323 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005324 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005325
Douglas Gregor66724ea2009-11-14 01:20:54 +00005326 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5327 // C++ [class.copy]p3:
5328 // A member function template is never instantiated to perform the copy
5329 // of a class object to an object of its class type.
5330 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005331 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005332 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005333 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5334 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005335 return;
5336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005338 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005339 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005340 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005341 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005342 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005343 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005344 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005345 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005346
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005347 unsigned NumArgsInProto = Proto->getNumArgs();
5348
5349 // (C++ 13.3.2p2): A candidate function having fewer than m
5350 // parameters is viable only if it has an ellipsis in its parameter
5351 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005352 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005353 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005354 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005355 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005356 return;
5357 }
5358
5359 // (C++ 13.3.2p2): A candidate function having more than m parameters
5360 // is viable only if the (m+1)st parameter has a default argument
5361 // (8.3.6). For the purposes of overload resolution, the
5362 // parameter list is truncated on the right, so that there are
5363 // exactly m parameters.
5364 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005365 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005366 // Not enough arguments.
5367 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005368 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005369 return;
5370 }
5371
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005372 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005373 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005374 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5375 if (CheckCUDATarget(Caller, Function)) {
5376 Candidate.Viable = false;
5377 Candidate.FailureKind = ovl_fail_bad_target;
5378 return;
5379 }
5380
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005381 // Determine the implicit conversion sequences for each of the
5382 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005383 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005384 if (ArgIdx < NumArgsInProto) {
5385 // (C++ 13.3.2p3): for F to be a viable function, there shall
5386 // exist for each argument an implicit conversion sequence
5387 // (13.3.3.1) that converts that argument to the corresponding
5388 // parameter of F.
5389 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005390 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005391 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005392 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005393 /*InOverloadResolution=*/true,
5394 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005395 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005396 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005397 if (Candidate.Conversions[ArgIdx].isBad()) {
5398 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005399 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005400 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005401 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005402 } else {
5403 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5404 // argument for which there is no corresponding parameter is
5405 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005406 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005407 }
5408 }
5409}
5410
Douglas Gregor063daf62009-03-13 18:40:31 +00005411/// \brief Add all of the function declarations in the given function set to
5412/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005413void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005414 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005415 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005416 bool SuppressUserConversions,
5417 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005418 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005419 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5420 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005421 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005422 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005423 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005424 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005425 Args.slice(1), CandidateSet,
5426 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005427 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005428 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005429 SuppressUserConversions);
5430 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005431 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005432 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5433 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005434 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005435 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005436 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005437 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005438 Args[0]->Classify(Context), Args.slice(1),
5439 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005440 else
John McCall9aa472c2010-03-19 07:35:19 +00005441 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005442 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005443 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005445 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005446}
5447
John McCall314be4e2009-11-17 07:50:12 +00005448/// AddMethodCandidate - Adds a named decl (which is some kind of
5449/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005450void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005451 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005452 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005453 Expr **Args, unsigned NumArgs,
5454 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005455 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005456 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005457 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005458
5459 if (isa<UsingShadowDecl>(Decl))
5460 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005461
John McCall314be4e2009-11-17 07:50:12 +00005462 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5463 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5464 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005465 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5466 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005467 ObjectType, ObjectClassification,
5468 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005469 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005470 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005471 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005472 ObjectType, ObjectClassification,
5473 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005474 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005475 }
5476}
5477
Douglas Gregor96176b32008-11-18 23:14:02 +00005478/// AddMethodCandidate - Adds the given C++ member function to the set
5479/// of candidate functions, using the given function call arguments
5480/// and the object argument (@c Object). For example, in a call
5481/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5482/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5483/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005484/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005485void
John McCall9aa472c2010-03-19 07:35:19 +00005486Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005487 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005488 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005489 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005490 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005491 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005492 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005493 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005494 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005495 assert(!isa<CXXConstructorDecl>(Method) &&
5496 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005497
Douglas Gregor3f396022009-09-28 04:47:19 +00005498 if (!CandidateSet.isNewCandidate(Method))
5499 return;
5500
Douglas Gregor7edfb692009-11-23 12:27:39 +00005501 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005502 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005503
Douglas Gregor96176b32008-11-18 23:14:02 +00005504 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005505 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005506 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005507 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005508 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005509 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005510 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005511
5512 unsigned NumArgsInProto = Proto->getNumArgs();
5513
5514 // (C++ 13.3.2p2): A candidate function having fewer than m
5515 // parameters is viable only if it has an ellipsis in its parameter
5516 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005517 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005518 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005519 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005520 return;
5521 }
5522
5523 // (C++ 13.3.2p2): A candidate function having more than m parameters
5524 // is viable only if the (m+1)st parameter has a default argument
5525 // (8.3.6). For the purposes of overload resolution, the
5526 // parameter list is truncated on the right, so that there are
5527 // exactly m parameters.
5528 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005529 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005530 // Not enough arguments.
5531 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005532 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005533 return;
5534 }
5535
5536 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005537
John McCall701c89e2009-12-03 04:06:58 +00005538 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005539 // The implicit object argument is ignored.
5540 Candidate.IgnoreObjectArgument = true;
5541 else {
5542 // Determine the implicit conversion sequence for the object
5543 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005544 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005545 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5546 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005547 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005548 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005549 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005550 return;
5551 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005552 }
5553
5554 // Determine the implicit conversion sequences for each of the
5555 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005556 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005557 if (ArgIdx < NumArgsInProto) {
5558 // (C++ 13.3.2p3): for F to be a viable function, there shall
5559 // exist for each argument an implicit conversion sequence
5560 // (13.3.3.1) that converts that argument to the corresponding
5561 // parameter of F.
5562 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005563 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005564 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005566 /*InOverloadResolution=*/true,
5567 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005568 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005569 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005570 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005571 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005572 break;
5573 }
5574 } else {
5575 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5576 // argument for which there is no corresponding parameter is
5577 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005578 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005579 }
5580 }
5581}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582
Douglas Gregor6b906862009-08-21 00:16:32 +00005583/// \brief Add a C++ member function template as a candidate to the candidate
5584/// set, using template argument deduction to produce an appropriate member
5585/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005586void
Douglas Gregor6b906862009-08-21 00:16:32 +00005587Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005588 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005589 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005590 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005591 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005592 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005593 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005594 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005595 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005596 if (!CandidateSet.isNewCandidate(MethodTmpl))
5597 return;
5598
Douglas Gregor6b906862009-08-21 00:16:32 +00005599 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005600 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005601 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005602 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005603 // candidate functions in the usual way.113) A given name can refer to one
5604 // or more function templates and also to a set of overloaded non-template
5605 // functions. In such a case, the candidate functions generated from each
5606 // function template are combined with the set of non-template candidate
5607 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005608 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005609 FunctionDecl *Specialization = 0;
5610 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005611 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5612 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005613 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005614 Candidate.FoundDecl = FoundDecl;
5615 Candidate.Function = MethodTmpl->getTemplatedDecl();
5616 Candidate.Viable = false;
5617 Candidate.FailureKind = ovl_fail_bad_deduction;
5618 Candidate.IsSurrogate = false;
5619 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005620 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005621 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005622 Info);
5623 return;
5624 }
Mike Stump1eb44332009-09-09 15:08:12 +00005625
Douglas Gregor6b906862009-08-21 00:16:32 +00005626 // Add the function template specialization produced by template argument
5627 // deduction as a candidate.
5628 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005629 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005630 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005631 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005632 ActingContext, ObjectType, ObjectClassification, Args,
5633 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005634}
5635
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005636/// \brief Add a C++ function template specialization as a candidate
5637/// in the candidate set, using template argument deduction to produce
5638/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005639void
Douglas Gregore53060f2009-06-25 22:08:12 +00005640Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005641 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005642 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005643 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005644 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005645 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005646 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5647 return;
5648
Douglas Gregore53060f2009-06-25 22:08:12 +00005649 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005650 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005651 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005652 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005653 // candidate functions in the usual way.113) A given name can refer to one
5654 // or more function templates and also to a set of overloaded non-template
5655 // functions. In such a case, the candidate functions generated from each
5656 // function template are combined with the set of non-template candidate
5657 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005658 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005659 FunctionDecl *Specialization = 0;
5660 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005661 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5662 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005663 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005664 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005665 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5666 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005667 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005668 Candidate.IsSurrogate = false;
5669 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005670 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005671 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005672 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005673 return;
5674 }
Mike Stump1eb44332009-09-09 15:08:12 +00005675
Douglas Gregore53060f2009-06-25 22:08:12 +00005676 // Add the function template specialization produced by template argument
5677 // deduction as a candidate.
5678 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005679 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005680 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005681}
Mike Stump1eb44332009-09-09 15:08:12 +00005682
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005683/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005684/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005685/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005686/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005687/// (which may or may not be the same type as the type that the
5688/// conversion function produces).
5689void
5690Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005691 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005692 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005693 Expr *From, QualType ToType,
5694 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005695 assert(!Conversion->getDescribedFunctionTemplate() &&
5696 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005697 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005698 if (!CandidateSet.isNewCandidate(Conversion))
5699 return;
5700
Douglas Gregor7edfb692009-11-23 12:27:39 +00005701 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005702 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005703
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005704 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005705 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005706 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005707 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005708 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005709 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005710 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005711 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005712 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005713 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005714 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005715
Douglas Gregorbca39322010-08-19 15:37:02 +00005716 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005717 // For conversion functions, the function is considered to be a member of
5718 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005719 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005720 //
5721 // Determine the implicit conversion sequence for the implicit
5722 // object parameter.
5723 QualType ImplicitParamType = From->getType();
5724 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5725 ImplicitParamType = FromPtrType->getPointeeType();
5726 CXXRecordDecl *ConversionContext
5727 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005728
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005729 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005730 = TryObjectArgumentInitialization(*this, From->getType(),
5731 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005732 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733
John McCall1d318332010-01-12 00:44:57 +00005734 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005735 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005736 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005737 return;
5738 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005739
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005741 // derived to base as such conversions are given Conversion Rank. They only
5742 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5743 QualType FromCanon
5744 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5745 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5746 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5747 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005748 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005749 return;
5750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005752 // To determine what the conversion from the result of calling the
5753 // conversion function to the type we're eventually trying to
5754 // convert to (ToType), we need to synthesize a call to the
5755 // conversion function and attempt copy initialization from it. This
5756 // makes sure that we get the right semantics with respect to
5757 // lvalues/rvalues and the type. Fortunately, we can allocate this
5758 // call on the stack and we don't need its arguments to be
5759 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005760 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005761 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005762 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5763 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005764 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005765 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005766
Richard Smith87c1f1f2011-07-13 22:53:21 +00005767 QualType ConversionType = Conversion->getConversionType();
5768 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005769 Candidate.Viable = false;
5770 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5771 return;
5772 }
5773
Richard Smith87c1f1f2011-07-13 22:53:21 +00005774 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005775
Mike Stump1eb44332009-09-09 15:08:12 +00005776 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005777 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5778 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005779 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005780 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005781 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005782 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005783 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005784 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005785 /*InOverloadResolution=*/false,
5786 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005787
John McCall1d318332010-01-12 00:44:57 +00005788 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005789 case ImplicitConversionSequence::StandardConversion:
5790 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005791
Douglas Gregorc520c842010-04-12 23:42:09 +00005792 // C++ [over.ics.user]p3:
5793 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005794 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005795 // shall have exact match rank.
5796 if (Conversion->getPrimaryTemplate() &&
5797 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5798 Candidate.Viable = false;
5799 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005801
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005802 // C++0x [dcl.init.ref]p5:
5803 // In the second case, if the reference is an rvalue reference and
5804 // the second standard conversion sequence of the user-defined
5805 // conversion sequence includes an lvalue-to-rvalue conversion, the
5806 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005807 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005808 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5809 Candidate.Viable = false;
5810 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5811 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005812 break;
5813
5814 case ImplicitConversionSequence::BadConversion:
5815 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005816 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005817 break;
5818
5819 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005820 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005821 "Can only end up with a standard conversion sequence or failure");
5822 }
5823}
5824
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005825/// \brief Adds a conversion function template specialization
5826/// candidate to the overload set, using template argument deduction
5827/// to deduce the template arguments of the conversion function
5828/// template from the type that we are converting to (C++
5829/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005830void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005831Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005832 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005833 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005834 Expr *From, QualType ToType,
5835 OverloadCandidateSet &CandidateSet) {
5836 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5837 "Only conversion function templates permitted here");
5838
Douglas Gregor3f396022009-09-28 04:47:19 +00005839 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5840 return;
5841
Craig Topper93e45992012-09-19 02:26:47 +00005842 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005843 CXXConversionDecl *Specialization = 0;
5844 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005845 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005846 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005847 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005848 Candidate.FoundDecl = FoundDecl;
5849 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5850 Candidate.Viable = false;
5851 Candidate.FailureKind = ovl_fail_bad_deduction;
5852 Candidate.IsSurrogate = false;
5853 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005854 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005855 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005856 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005857 return;
5858 }
Mike Stump1eb44332009-09-09 15:08:12 +00005859
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005860 // Add the conversion function template specialization produced by
5861 // template argument deduction as a candidate.
5862 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005863 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005864 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005865}
5866
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005867/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5868/// converts the given @c Object to a function pointer via the
5869/// conversion function @c Conversion, and then attempts to call it
5870/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5871/// the type of function that we'll eventually be calling.
5872void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005873 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005874 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005875 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005876 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005877 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005878 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005879 if (!CandidateSet.isNewCandidate(Conversion))
5880 return;
5881
Douglas Gregor7edfb692009-11-23 12:27:39 +00005882 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005883 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005884
Ahmed Charles13a140c2012-02-25 11:00:22 +00005885 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005886 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005887 Candidate.Function = 0;
5888 Candidate.Surrogate = Conversion;
5889 Candidate.Viable = true;
5890 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005891 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005892 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005893
5894 // Determine the implicit conversion sequence for the implicit
5895 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005896 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005897 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005898 Object->Classify(Context),
5899 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005900 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005901 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005902 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005903 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005904 return;
5905 }
5906
5907 // The first conversion is actually a user-defined conversion whose
5908 // first conversion is ObjectInit's standard conversion (which is
5909 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005910 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005911 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005912 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005913 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005914 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005915 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005916 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005917 = Candidate.Conversions[0].UserDefined.Before;
5918 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5919
Mike Stump1eb44332009-09-09 15:08:12 +00005920 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005921 unsigned NumArgsInProto = Proto->getNumArgs();
5922
5923 // (C++ 13.3.2p2): A candidate function having fewer than m
5924 // parameters is viable only if it has an ellipsis in its parameter
5925 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005926 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005927 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005928 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005929 return;
5930 }
5931
5932 // Function types don't have any default arguments, so just check if
5933 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005934 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005935 // Not enough arguments.
5936 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005937 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005938 return;
5939 }
5940
5941 // Determine the implicit conversion sequences for each of the
5942 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005943 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005944 if (ArgIdx < NumArgsInProto) {
5945 // (C++ 13.3.2p3): for F to be a viable function, there shall
5946 // exist for each argument an implicit conversion sequence
5947 // (13.3.3.1) that converts that argument to the corresponding
5948 // parameter of F.
5949 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005950 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005951 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005952 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005953 /*InOverloadResolution=*/false,
5954 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005955 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005956 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005957 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005958 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005959 break;
5960 }
5961 } else {
5962 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5963 // argument for which there is no corresponding parameter is
5964 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005965 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005966 }
5967 }
5968}
5969
Douglas Gregor063daf62009-03-13 18:40:31 +00005970/// \brief Add overload candidates for overloaded operators that are
5971/// member functions.
5972///
5973/// Add the overloaded operator candidates that are member functions
5974/// for the operator Op that was used in an operator expression such
5975/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5976/// CandidateSet will store the added overload candidates. (C++
5977/// [over.match.oper]).
5978void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5979 SourceLocation OpLoc,
5980 Expr **Args, unsigned NumArgs,
5981 OverloadCandidateSet& CandidateSet,
5982 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005983 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5984
5985 // C++ [over.match.oper]p3:
5986 // For a unary operator @ with an operand of a type whose
5987 // cv-unqualified version is T1, and for a binary operator @ with
5988 // a left operand of a type whose cv-unqualified version is T1 and
5989 // a right operand of a type whose cv-unqualified version is T2,
5990 // three sets of candidate functions, designated member
5991 // candidates, non-member candidates and built-in candidates, are
5992 // constructed as follows:
5993 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005994
5995 // -- If T1 is a class type, the set of member candidates is the
5996 // result of the qualified lookup of T1::operator@
5997 // (13.3.1.1.1); otherwise, the set of member candidates is
5998 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005999 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006000 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00006001 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006003
John McCalla24dc2e2009-11-17 02:14:36 +00006004 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6005 LookupQualifiedName(Operators, T1Rec->getDecl());
6006 Operators.suppressDiagnostics();
6007
Mike Stump1eb44332009-09-09 15:08:12 +00006008 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006009 OperEnd = Operators.end();
6010 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006011 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006012 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006013 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006014 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006015 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006016 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006017}
6018
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006019/// AddBuiltinCandidate - Add a candidate for a built-in
6020/// operator. ResultTy and ParamTys are the result and parameter types
6021/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006022/// arguments being passed to the candidate. IsAssignmentOperator
6023/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006024/// operator. NumContextualBoolArguments is the number of arguments
6025/// (at the beginning of the argument list) that will be contextually
6026/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006027void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006028 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006029 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006030 bool IsAssignmentOperator,
6031 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006032 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006033 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006034
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006035 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006036 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006037 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006038 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006039 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006040 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006041 Candidate.BuiltinTypes.ResultTy = ResultTy;
6042 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6043 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6044
6045 // Determine the implicit conversion sequences for each of the
6046 // arguments.
6047 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006048 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006049 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006050 // C++ [over.match.oper]p4:
6051 // For the built-in assignment operators, conversions of the
6052 // left operand are restricted as follows:
6053 // -- no temporaries are introduced to hold the left operand, and
6054 // -- no user-defined conversions are applied to the left
6055 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006056 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006057 //
6058 // We block these conversions by turning off user-defined
6059 // conversions, since that is the only way that initialization of
6060 // a reference to a non-class type can occur from something that
6061 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006062 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006063 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006064 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006065 Candidate.Conversions[ArgIdx]
6066 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006067 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006068 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006069 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006070 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006071 /*InOverloadResolution=*/false,
6072 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006073 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006074 }
John McCall1d318332010-01-12 00:44:57 +00006075 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006076 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006077 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006078 break;
6079 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006080 }
6081}
6082
6083/// BuiltinCandidateTypeSet - A set of types that will be used for the
6084/// candidate operator functions for built-in operators (C++
6085/// [over.built]). The types are separated into pointer types and
6086/// enumeration types.
6087class BuiltinCandidateTypeSet {
6088 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006089 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006090
6091 /// PointerTypes - The set of pointer types that will be used in the
6092 /// built-in candidates.
6093 TypeSet PointerTypes;
6094
Sebastian Redl78eb8742009-04-19 21:53:20 +00006095 /// MemberPointerTypes - The set of member pointer types that will be
6096 /// used in the built-in candidates.
6097 TypeSet MemberPointerTypes;
6098
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006099 /// EnumerationTypes - The set of enumeration types that will be
6100 /// used in the built-in candidates.
6101 TypeSet EnumerationTypes;
6102
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006103 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006104 /// candidates.
6105 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006106
6107 /// \brief A flag indicating non-record types are viable candidates
6108 bool HasNonRecordTypes;
6109
6110 /// \brief A flag indicating whether either arithmetic or enumeration types
6111 /// were present in the candidate set.
6112 bool HasArithmeticOrEnumeralTypes;
6113
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006114 /// \brief A flag indicating whether the nullptr type was present in the
6115 /// candidate set.
6116 bool HasNullPtrType;
6117
Douglas Gregor5842ba92009-08-24 15:23:48 +00006118 /// Sema - The semantic analysis instance where we are building the
6119 /// candidate type set.
6120 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006121
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006122 /// Context - The AST context in which we will build the type sets.
6123 ASTContext &Context;
6124
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006125 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6126 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006127 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006128
6129public:
6130 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006131 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006132
Mike Stump1eb44332009-09-09 15:08:12 +00006133 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006134 : HasNonRecordTypes(false),
6135 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006136 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006137 SemaRef(SemaRef),
6138 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006139
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006140 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006141 SourceLocation Loc,
6142 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006143 bool AllowExplicitConversions,
6144 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006145
6146 /// pointer_begin - First pointer type found;
6147 iterator pointer_begin() { return PointerTypes.begin(); }
6148
Sebastian Redl78eb8742009-04-19 21:53:20 +00006149 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006150 iterator pointer_end() { return PointerTypes.end(); }
6151
Sebastian Redl78eb8742009-04-19 21:53:20 +00006152 /// member_pointer_begin - First member pointer type found;
6153 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6154
6155 /// member_pointer_end - Past the last member pointer type found;
6156 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6157
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158 /// enumeration_begin - First enumeration type found;
6159 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6160
Sebastian Redl78eb8742009-04-19 21:53:20 +00006161 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006162 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006163
Douglas Gregor26bcf672010-05-19 03:21:00 +00006164 iterator vector_begin() { return VectorTypes.begin(); }
6165 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006166
6167 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6168 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006169 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006170};
6171
Sebastian Redl78eb8742009-04-19 21:53:20 +00006172/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006173/// the set of pointer types along with any more-qualified variants of
6174/// that type. For example, if @p Ty is "int const *", this routine
6175/// will add "int const *", "int const volatile *", "int const
6176/// restrict *", and "int const volatile restrict *" to the set of
6177/// pointer types. Returns true if the add of @p Ty itself succeeded,
6178/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006179///
6180/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006181bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006182BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6183 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006184
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006185 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006186 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006187 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006188
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006189 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006190 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006191 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006192 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006193 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6194 PointeeTy = PTy->getPointeeType();
6195 buildObjCPtr = true;
6196 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006197 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006198 }
6199
Sebastian Redla9efada2009-11-18 20:39:26 +00006200 // Don't add qualified variants of arrays. For one, they're not allowed
6201 // (the qualifier would sink to the element type), and for another, the
6202 // only overload situation where it matters is subscript or pointer +- int,
6203 // and those shouldn't have qualifier variants anyway.
6204 if (PointeeTy->isArrayType())
6205 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006206
John McCall0953e762009-09-24 19:53:00 +00006207 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006208 bool hasVolatile = VisibleQuals.hasVolatile();
6209 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006210
John McCall0953e762009-09-24 19:53:00 +00006211 // Iterate through all strict supersets of BaseCVR.
6212 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6213 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006214 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006215 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006216
6217 // Skip over restrict if no restrict found anywhere in the types, or if
6218 // the type cannot be restrict-qualified.
6219 if ((CVR & Qualifiers::Restrict) &&
6220 (!hasRestrict ||
6221 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6222 continue;
6223
6224 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006225 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006226
6227 // Build qualified pointer type.
6228 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006229 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006230 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006231 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006232 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6233
6234 // Insert qualified pointer type.
6235 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006236 }
6237
6238 return true;
6239}
6240
Sebastian Redl78eb8742009-04-19 21:53:20 +00006241/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6242/// to the set of pointer types along with any more-qualified variants of
6243/// that type. For example, if @p Ty is "int const *", this routine
6244/// will add "int const *", "int const volatile *", "int const
6245/// restrict *", and "int const volatile restrict *" to the set of
6246/// pointer types. Returns true if the add of @p Ty itself succeeded,
6247/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006248///
6249/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006250bool
6251BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6252 QualType Ty) {
6253 // Insert this type.
6254 if (!MemberPointerTypes.insert(Ty))
6255 return false;
6256
John McCall0953e762009-09-24 19:53:00 +00006257 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6258 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006259
John McCall0953e762009-09-24 19:53:00 +00006260 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006261 // Don't add qualified variants of arrays. For one, they're not allowed
6262 // (the qualifier would sink to the element type), and for another, the
6263 // only overload situation where it matters is subscript or pointer +- int,
6264 // and those shouldn't have qualifier variants anyway.
6265 if (PointeeTy->isArrayType())
6266 return true;
John McCall0953e762009-09-24 19:53:00 +00006267 const Type *ClassTy = PointerTy->getClass();
6268
6269 // Iterate through all strict supersets of the pointee type's CVR
6270 // qualifiers.
6271 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6272 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6273 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006274
John McCall0953e762009-09-24 19:53:00 +00006275 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006276 MemberPointerTypes.insert(
6277 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006278 }
6279
6280 return true;
6281}
6282
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006283/// AddTypesConvertedFrom - Add each of the types to which the type @p
6284/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006285/// primarily interested in pointer types and enumeration types. We also
6286/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006287/// AllowUserConversions is true if we should look at the conversion
6288/// functions of a class type, and AllowExplicitConversions if we
6289/// should also include the explicit conversion functions of a class
6290/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006291void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006292BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006293 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006294 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006295 bool AllowExplicitConversions,
6296 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006297 // Only deal with canonical types.
6298 Ty = Context.getCanonicalType(Ty);
6299
6300 // Look through reference types; they aren't part of the type of an
6301 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006302 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006303 Ty = RefTy->getPointeeType();
6304
John McCall3b657512011-01-19 10:06:00 +00006305 // If we're dealing with an array type, decay to the pointer.
6306 if (Ty->isArrayType())
6307 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6308
6309 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006310 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006311
Chandler Carruth6a577462010-12-13 01:44:01 +00006312 // Flag if we ever add a non-record type.
6313 const RecordType *TyRec = Ty->getAs<RecordType>();
6314 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6315
Chandler Carruth6a577462010-12-13 01:44:01 +00006316 // Flag if we encounter an arithmetic type.
6317 HasArithmeticOrEnumeralTypes =
6318 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6319
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006320 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6321 PointerTypes.insert(Ty);
6322 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006323 // Insert our type, and its more-qualified variants, into the set
6324 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006325 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006326 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006327 } else if (Ty->isMemberPointerType()) {
6328 // Member pointers are far easier, since the pointee can't be converted.
6329 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6330 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006331 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006332 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006333 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006334 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006335 // We treat vector types as arithmetic types in many contexts as an
6336 // extension.
6337 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006338 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006339 } else if (Ty->isNullPtrType()) {
6340 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006341 } else if (AllowUserConversions && TyRec) {
6342 // No conversion functions in incomplete types.
6343 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6344 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006345
Chandler Carruth6a577462010-12-13 01:44:01 +00006346 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006347 std::pair<CXXRecordDecl::conversion_iterator,
6348 CXXRecordDecl::conversion_iterator>
6349 Conversions = ClassDecl->getVisibleConversionFunctions();
6350 for (CXXRecordDecl::conversion_iterator
6351 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006352 NamedDecl *D = I.getDecl();
6353 if (isa<UsingShadowDecl>(D))
6354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006355
Chandler Carruth6a577462010-12-13 01:44:01 +00006356 // Skip conversion function templates; they don't tell us anything
6357 // about which builtin types we can convert to.
6358 if (isa<FunctionTemplateDecl>(D))
6359 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006360
Chandler Carruth6a577462010-12-13 01:44:01 +00006361 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6362 if (AllowExplicitConversions || !Conv->isExplicit()) {
6363 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6364 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006365 }
6366 }
6367 }
6368}
6369
Douglas Gregor19b7b152009-08-24 13:43:27 +00006370/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6371/// the volatile- and non-volatile-qualified assignment operators for the
6372/// given type to the candidate set.
6373static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6374 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006375 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006376 unsigned NumArgs,
6377 OverloadCandidateSet &CandidateSet) {
6378 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006379
Douglas Gregor19b7b152009-08-24 13:43:27 +00006380 // T& operator=(T&, T)
6381 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6382 ParamTypes[1] = T;
6383 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6384 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Douglas Gregor19b7b152009-08-24 13:43:27 +00006386 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6387 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006388 ParamTypes[0]
6389 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006390 ParamTypes[1] = T;
6391 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006392 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006393 }
6394}
Mike Stump1eb44332009-09-09 15:08:12 +00006395
Sebastian Redl9994a342009-10-25 17:03:50 +00006396/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6397/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006398static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6399 Qualifiers VRQuals;
6400 const RecordType *TyRec;
6401 if (const MemberPointerType *RHSMPType =
6402 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006403 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006404 else
6405 TyRec = ArgExpr->getType()->getAs<RecordType>();
6406 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006407 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006408 VRQuals.addVolatile();
6409 VRQuals.addRestrict();
6410 return VRQuals;
6411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006412
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006413 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006414 if (!ClassDecl->hasDefinition())
6415 return VRQuals;
6416
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006417 std::pair<CXXRecordDecl::conversion_iterator,
6418 CXXRecordDecl::conversion_iterator>
6419 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006420
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006421 for (CXXRecordDecl::conversion_iterator
6422 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006423 NamedDecl *D = I.getDecl();
6424 if (isa<UsingShadowDecl>(D))
6425 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6426 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006427 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6428 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6429 CanTy = ResTypeRef->getPointeeType();
6430 // Need to go down the pointer/mempointer chain and add qualifiers
6431 // as see them.
6432 bool done = false;
6433 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006434 if (CanTy.isRestrictQualified())
6435 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006436 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6437 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006438 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006439 CanTy->getAs<MemberPointerType>())
6440 CanTy = ResTypeMPtr->getPointeeType();
6441 else
6442 done = true;
6443 if (CanTy.isVolatileQualified())
6444 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006445 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6446 return VRQuals;
6447 }
6448 }
6449 }
6450 return VRQuals;
6451}
John McCall00071ec2010-11-13 05:51:15 +00006452
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006453namespace {
John McCall00071ec2010-11-13 05:51:15 +00006454
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006455/// \brief Helper class to manage the addition of builtin operator overload
6456/// candidates. It provides shared state and utility methods used throughout
6457/// the process, as well as a helper method to add each group of builtin
6458/// operator overloads from the standard to a candidate set.
6459class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006460 // Common instance state available to all overload candidate addition methods.
6461 Sema &S;
6462 Expr **Args;
6463 unsigned NumArgs;
6464 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006465 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006466 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006467 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006468
Chandler Carruth6d695582010-12-12 10:35:00 +00006469 // Define some constants used to index and iterate over the arithemetic types
6470 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006471 // The "promoted arithmetic types" are the arithmetic
6472 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006473 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006474 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006475 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006476 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006477 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006478 LastPromotedArithmeticType = 11;
6479 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006480
Chandler Carruth6d695582010-12-12 10:35:00 +00006481 /// \brief Get the canonical type for a given arithmetic type index.
6482 CanQualType getArithmeticType(unsigned index) {
6483 assert(index < NumArithmeticTypes);
6484 static CanQualType ASTContext::* const
6485 ArithmeticTypes[NumArithmeticTypes] = {
6486 // Start of promoted types.
6487 &ASTContext::FloatTy,
6488 &ASTContext::DoubleTy,
6489 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006490
Chandler Carruth6d695582010-12-12 10:35:00 +00006491 // Start of integral types.
6492 &ASTContext::IntTy,
6493 &ASTContext::LongTy,
6494 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006495 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006496 &ASTContext::UnsignedIntTy,
6497 &ASTContext::UnsignedLongTy,
6498 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006499 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006500 // End of promoted types.
6501
6502 &ASTContext::BoolTy,
6503 &ASTContext::CharTy,
6504 &ASTContext::WCharTy,
6505 &ASTContext::Char16Ty,
6506 &ASTContext::Char32Ty,
6507 &ASTContext::SignedCharTy,
6508 &ASTContext::ShortTy,
6509 &ASTContext::UnsignedCharTy,
6510 &ASTContext::UnsignedShortTy,
6511 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006512 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 };
6514 return S.Context.*ArithmeticTypes[index];
6515 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006516
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006517 /// \brief Gets the canonical type resulting from the usual arithemetic
6518 /// converions for the given arithmetic types.
6519 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6520 // Accelerator table for performing the usual arithmetic conversions.
6521 // The rules are basically:
6522 // - if either is floating-point, use the wider floating-point
6523 // - if same signedness, use the higher rank
6524 // - if same size, use unsigned of the higher rank
6525 // - use the larger type
6526 // These rules, together with the axiom that higher ranks are
6527 // never smaller, are sufficient to precompute all of these results
6528 // *except* when dealing with signed types of higher rank.
6529 // (we could precompute SLL x UI for all known platforms, but it's
6530 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006531 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006532 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006533 Dep=-1,
6534 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006535 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006536 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006537 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006538/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6539/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6540/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6541/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6542/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6543/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6544/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6545/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6546/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6547/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6548/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006549 };
6550
6551 assert(L < LastPromotedArithmeticType);
6552 assert(R < LastPromotedArithmeticType);
6553 int Idx = ConversionsTable[L][R];
6554
6555 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006556 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006557
6558 // Slow path: we need to compare widths.
6559 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006560 CanQualType LT = getArithmeticType(L),
6561 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006562 unsigned LW = S.Context.getIntWidth(LT),
6563 RW = S.Context.getIntWidth(RT);
6564
6565 // If they're different widths, use the signed type.
6566 if (LW > RW) return LT;
6567 else if (LW < RW) return RT;
6568
6569 // Otherwise, use the unsigned type of the signed type's rank.
6570 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6571 assert(L == SLL || R == SLL);
6572 return S.Context.UnsignedLongLongTy;
6573 }
6574
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006575 /// \brief Helper method to factor out the common pattern of adding overloads
6576 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006577 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006578 bool HasVolatile,
6579 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006580 QualType ParamTypes[2] = {
6581 S.Context.getLValueReferenceType(CandidateTy),
6582 S.Context.IntTy
6583 };
6584
6585 // Non-volatile version.
6586 if (NumArgs == 1)
6587 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6588 else
6589 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6590
6591 // Use a heuristic to reduce number of builtin candidates in the set:
6592 // add volatile version only if there are conversions to a volatile type.
6593 if (HasVolatile) {
6594 ParamTypes[0] =
6595 S.Context.getLValueReferenceType(
6596 S.Context.getVolatileType(CandidateTy));
6597 if (NumArgs == 1)
6598 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6599 else
6600 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6601 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006602
6603 // Add restrict version only if there are conversions to a restrict type
6604 // and our candidate type is a non-restrict-qualified pointer.
6605 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6606 !CandidateTy.isRestrictQualified()) {
6607 ParamTypes[0]
6608 = S.Context.getLValueReferenceType(
6609 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6610 if (NumArgs == 1)
6611 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6612 else
6613 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6614
6615 if (HasVolatile) {
6616 ParamTypes[0]
6617 = S.Context.getLValueReferenceType(
6618 S.Context.getCVRQualifiedType(CandidateTy,
6619 (Qualifiers::Volatile |
6620 Qualifiers::Restrict)));
6621 if (NumArgs == 1)
6622 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6623 CandidateSet);
6624 else
6625 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6626 }
6627 }
6628
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006629 }
6630
6631public:
6632 BuiltinOperatorOverloadBuilder(
6633 Sema &S, Expr **Args, unsigned NumArgs,
6634 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006635 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006636 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006637 OverloadCandidateSet &CandidateSet)
6638 : S(S), Args(Args), NumArgs(NumArgs),
6639 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006640 HasArithmeticOrEnumeralCandidateType(
6641 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006642 CandidateTypes(CandidateTypes),
6643 CandidateSet(CandidateSet) {
6644 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006645 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006646 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006647 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006648 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006649 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006650 assert(getArithmeticType(FirstPromotedArithmeticType)
6651 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006652 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006653 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006654 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006655 "Invalid last promoted arithmetic type");
6656 }
6657
6658 // C++ [over.built]p3:
6659 //
6660 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6661 // is either volatile or empty, there exist candidate operator
6662 // functions of the form
6663 //
6664 // VQ T& operator++(VQ T&);
6665 // T operator++(VQ T&, int);
6666 //
6667 // C++ [over.built]p4:
6668 //
6669 // For every pair (T, VQ), where T is an arithmetic type other
6670 // than bool, and VQ is either volatile or empty, there exist
6671 // candidate operator functions of the form
6672 //
6673 // VQ T& operator--(VQ T&);
6674 // T operator--(VQ T&, int);
6675 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006676 if (!HasArithmeticOrEnumeralCandidateType)
6677 return;
6678
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006679 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6680 Arith < NumArithmeticTypes; ++Arith) {
6681 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006682 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006683 VisibleTypeConversionsQuals.hasVolatile(),
6684 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006685 }
6686 }
6687
6688 // C++ [over.built]p5:
6689 //
6690 // For every pair (T, VQ), where T is a cv-qualified or
6691 // cv-unqualified object type, and VQ is either volatile or
6692 // empty, there exist candidate operator functions of the form
6693 //
6694 // T*VQ& operator++(T*VQ&);
6695 // T*VQ& operator--(T*VQ&);
6696 // T* operator++(T*VQ&, int);
6697 // T* operator--(T*VQ&, int);
6698 void addPlusPlusMinusMinusPointerOverloads() {
6699 for (BuiltinCandidateTypeSet::iterator
6700 Ptr = CandidateTypes[0].pointer_begin(),
6701 PtrEnd = CandidateTypes[0].pointer_end();
6702 Ptr != PtrEnd; ++Ptr) {
6703 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006704 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006705 continue;
6706
6707 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006708 (!(*Ptr).isVolatileQualified() &&
6709 VisibleTypeConversionsQuals.hasVolatile()),
6710 (!(*Ptr).isRestrictQualified() &&
6711 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006712 }
6713 }
6714
6715 // C++ [over.built]p6:
6716 // For every cv-qualified or cv-unqualified object type T, there
6717 // exist candidate operator functions of the form
6718 //
6719 // T& operator*(T*);
6720 //
6721 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006722 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006723 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006724 // T& operator*(T*);
6725 void addUnaryStarPointerOverloads() {
6726 for (BuiltinCandidateTypeSet::iterator
6727 Ptr = CandidateTypes[0].pointer_begin(),
6728 PtrEnd = CandidateTypes[0].pointer_end();
6729 Ptr != PtrEnd; ++Ptr) {
6730 QualType ParamTy = *Ptr;
6731 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006732 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6733 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006734
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006735 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6736 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6737 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006738
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006739 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6740 &ParamTy, Args, 1, CandidateSet);
6741 }
6742 }
6743
6744 // C++ [over.built]p9:
6745 // For every promoted arithmetic type T, there exist candidate
6746 // operator functions of the form
6747 //
6748 // T operator+(T);
6749 // T operator-(T);
6750 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006751 if (!HasArithmeticOrEnumeralCandidateType)
6752 return;
6753
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006754 for (unsigned Arith = FirstPromotedArithmeticType;
6755 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006756 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006757 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6758 }
6759
6760 // Extension: We also add these operators for vector types.
6761 for (BuiltinCandidateTypeSet::iterator
6762 Vec = CandidateTypes[0].vector_begin(),
6763 VecEnd = CandidateTypes[0].vector_end();
6764 Vec != VecEnd; ++Vec) {
6765 QualType VecTy = *Vec;
6766 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6767 }
6768 }
6769
6770 // C++ [over.built]p8:
6771 // For every type T, there exist candidate operator functions of
6772 // the form
6773 //
6774 // T* operator+(T*);
6775 void addUnaryPlusPointerOverloads() {
6776 for (BuiltinCandidateTypeSet::iterator
6777 Ptr = CandidateTypes[0].pointer_begin(),
6778 PtrEnd = CandidateTypes[0].pointer_end();
6779 Ptr != PtrEnd; ++Ptr) {
6780 QualType ParamTy = *Ptr;
6781 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6782 }
6783 }
6784
6785 // C++ [over.built]p10:
6786 // For every promoted integral type T, there exist candidate
6787 // operator functions of the form
6788 //
6789 // T operator~(T);
6790 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006791 if (!HasArithmeticOrEnumeralCandidateType)
6792 return;
6793
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006794 for (unsigned Int = FirstPromotedIntegralType;
6795 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006796 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006797 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6798 }
6799
6800 // Extension: We also add this operator for vector types.
6801 for (BuiltinCandidateTypeSet::iterator
6802 Vec = CandidateTypes[0].vector_begin(),
6803 VecEnd = CandidateTypes[0].vector_end();
6804 Vec != VecEnd; ++Vec) {
6805 QualType VecTy = *Vec;
6806 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6807 }
6808 }
6809
6810 // C++ [over.match.oper]p16:
6811 // For every pointer to member type T, there exist candidate operator
6812 // functions of the form
6813 //
6814 // bool operator==(T,T);
6815 // bool operator!=(T,T);
6816 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6817 /// Set of (canonical) types that we've already handled.
6818 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6819
6820 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6821 for (BuiltinCandidateTypeSet::iterator
6822 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6823 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6824 MemPtr != MemPtrEnd;
6825 ++MemPtr) {
6826 // Don't add the same builtin candidate twice.
6827 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6828 continue;
6829
6830 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6831 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6832 CandidateSet);
6833 }
6834 }
6835 }
6836
6837 // C++ [over.built]p15:
6838 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006839 // For every T, where T is an enumeration type, a pointer type, or
6840 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006841 //
6842 // bool operator<(T, T);
6843 // bool operator>(T, T);
6844 // bool operator<=(T, T);
6845 // bool operator>=(T, T);
6846 // bool operator==(T, T);
6847 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006848 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006849 // C++ [over.match.oper]p3:
6850 // [...]the built-in candidates include all of the candidate operator
6851 // functions defined in 13.6 that, compared to the given operator, [...]
6852 // do not have the same parameter-type-list as any non-template non-member
6853 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006854 //
Eli Friedman97c67392012-09-18 21:52:24 +00006855 // Note that in practice, this only affects enumeration types because there
6856 // aren't any built-in candidates of record type, and a user-defined operator
6857 // must have an operand of record or enumeration type. Also, the only other
6858 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006859 // cannot be overloaded for enumeration types, so this is the only place
6860 // where we must suppress candidates like this.
6861 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6862 UserDefinedBinaryOperators;
6863
6864 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6865 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6866 CandidateTypes[ArgIdx].enumeration_end()) {
6867 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6868 CEnd = CandidateSet.end();
6869 C != CEnd; ++C) {
6870 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6871 continue;
6872
Eli Friedman97c67392012-09-18 21:52:24 +00006873 if (C->Function->isFunctionTemplateSpecialization())
6874 continue;
6875
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006876 QualType FirstParamType =
6877 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6878 QualType SecondParamType =
6879 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6880
6881 // Skip if either parameter isn't of enumeral type.
6882 if (!FirstParamType->isEnumeralType() ||
6883 !SecondParamType->isEnumeralType())
6884 continue;
6885
6886 // Add this operator to the set of known user-defined operators.
6887 UserDefinedBinaryOperators.insert(
6888 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6889 S.Context.getCanonicalType(SecondParamType)));
6890 }
6891 }
6892 }
6893
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006894 /// Set of (canonical) types that we've already handled.
6895 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6896
6897 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6898 for (BuiltinCandidateTypeSet::iterator
6899 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6900 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6901 Ptr != PtrEnd; ++Ptr) {
6902 // Don't add the same builtin candidate twice.
6903 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6904 continue;
6905
6906 QualType ParamTypes[2] = { *Ptr, *Ptr };
6907 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6908 CandidateSet);
6909 }
6910 for (BuiltinCandidateTypeSet::iterator
6911 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6912 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6913 Enum != EnumEnd; ++Enum) {
6914 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6915
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006916 // Don't add the same builtin candidate twice, or if a user defined
6917 // candidate exists.
6918 if (!AddedTypes.insert(CanonType) ||
6919 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6920 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006921 continue;
6922
6923 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006924 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6925 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006926 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006927
6928 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6929 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6930 if (AddedTypes.insert(NullPtrTy) &&
6931 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6932 NullPtrTy))) {
6933 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6934 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6935 CandidateSet);
6936 }
6937 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006938 }
6939 }
6940
6941 // C++ [over.built]p13:
6942 //
6943 // For every cv-qualified or cv-unqualified object type T
6944 // there exist candidate operator functions of the form
6945 //
6946 // T* operator+(T*, ptrdiff_t);
6947 // T& operator[](T*, ptrdiff_t); [BELOW]
6948 // T* operator-(T*, ptrdiff_t);
6949 // T* operator+(ptrdiff_t, T*);
6950 // T& operator[](ptrdiff_t, T*); [BELOW]
6951 //
6952 // C++ [over.built]p14:
6953 //
6954 // For every T, where T is a pointer to object type, there
6955 // exist candidate operator functions of the form
6956 //
6957 // ptrdiff_t operator-(T, T);
6958 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6959 /// Set of (canonical) types that we've already handled.
6960 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6961
6962 for (int Arg = 0; Arg < 2; ++Arg) {
6963 QualType AsymetricParamTypes[2] = {
6964 S.Context.getPointerDiffType(),
6965 S.Context.getPointerDiffType(),
6966 };
6967 for (BuiltinCandidateTypeSet::iterator
6968 Ptr = CandidateTypes[Arg].pointer_begin(),
6969 PtrEnd = CandidateTypes[Arg].pointer_end();
6970 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006971 QualType PointeeTy = (*Ptr)->getPointeeType();
6972 if (!PointeeTy->isObjectType())
6973 continue;
6974
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006975 AsymetricParamTypes[Arg] = *Ptr;
6976 if (Arg == 0 || Op == OO_Plus) {
6977 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6978 // T* operator+(ptrdiff_t, T*);
6979 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6980 CandidateSet);
6981 }
6982 if (Op == OO_Minus) {
6983 // ptrdiff_t operator-(T, T);
6984 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6985 continue;
6986
6987 QualType ParamTypes[2] = { *Ptr, *Ptr };
6988 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6989 Args, 2, CandidateSet);
6990 }
6991 }
6992 }
6993 }
6994
6995 // C++ [over.built]p12:
6996 //
6997 // For every pair of promoted arithmetic types L and R, there
6998 // exist candidate operator functions of the form
6999 //
7000 // LR operator*(L, R);
7001 // LR operator/(L, R);
7002 // LR operator+(L, R);
7003 // LR operator-(L, R);
7004 // bool operator<(L, R);
7005 // bool operator>(L, R);
7006 // bool operator<=(L, R);
7007 // bool operator>=(L, R);
7008 // bool operator==(L, R);
7009 // bool operator!=(L, R);
7010 //
7011 // where LR is the result of the usual arithmetic conversions
7012 // between types L and R.
7013 //
7014 // C++ [over.built]p24:
7015 //
7016 // For every pair of promoted arithmetic types L and R, there exist
7017 // candidate operator functions of the form
7018 //
7019 // LR operator?(bool, L, R);
7020 //
7021 // where LR is the result of the usual arithmetic conversions
7022 // between types L and R.
7023 // Our candidates ignore the first parameter.
7024 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007025 if (!HasArithmeticOrEnumeralCandidateType)
7026 return;
7027
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007028 for (unsigned Left = FirstPromotedArithmeticType;
7029 Left < LastPromotedArithmeticType; ++Left) {
7030 for (unsigned Right = FirstPromotedArithmeticType;
7031 Right < LastPromotedArithmeticType; ++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 =
7035 isComparison ? S.Context.BoolTy
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 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7042 // conditional operator for vector types.
7043 for (BuiltinCandidateTypeSet::iterator
7044 Vec1 = CandidateTypes[0].vector_begin(),
7045 Vec1End = CandidateTypes[0].vector_end();
7046 Vec1 != Vec1End; ++Vec1) {
7047 for (BuiltinCandidateTypeSet::iterator
7048 Vec2 = CandidateTypes[1].vector_begin(),
7049 Vec2End = CandidateTypes[1].vector_end();
7050 Vec2 != Vec2End; ++Vec2) {
7051 QualType LandR[2] = { *Vec1, *Vec2 };
7052 QualType Result = S.Context.BoolTy;
7053 if (!isComparison) {
7054 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7055 Result = *Vec1;
7056 else
7057 Result = *Vec2;
7058 }
7059
7060 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7061 }
7062 }
7063 }
7064
7065 // C++ [over.built]p17:
7066 //
7067 // For every pair of promoted integral types L and R, there
7068 // exist candidate operator functions of the form
7069 //
7070 // LR operator%(L, R);
7071 // LR operator&(L, R);
7072 // LR operator^(L, R);
7073 // LR operator|(L, R);
7074 // L operator<<(L, R);
7075 // L operator>>(L, R);
7076 //
7077 // where LR is the result of the usual arithmetic conversions
7078 // between types L and R.
7079 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007080 if (!HasArithmeticOrEnumeralCandidateType)
7081 return;
7082
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007083 for (unsigned Left = FirstPromotedIntegralType;
7084 Left < LastPromotedIntegralType; ++Left) {
7085 for (unsigned Right = FirstPromotedIntegralType;
7086 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007087 QualType LandR[2] = { getArithmeticType(Left),
7088 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007089 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7090 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007091 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007092 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7093 }
7094 }
7095 }
7096
7097 // C++ [over.built]p20:
7098 //
7099 // For every pair (T, VQ), where T is an enumeration or
7100 // pointer to member type and VQ is either volatile or
7101 // empty, there exist candidate operator functions of the form
7102 //
7103 // VQ T& operator=(VQ T&, T);
7104 void addAssignmentMemberPointerOrEnumeralOverloads() {
7105 /// Set of (canonical) types that we've already handled.
7106 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7107
7108 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7109 for (BuiltinCandidateTypeSet::iterator
7110 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7111 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7112 Enum != EnumEnd; ++Enum) {
7113 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7114 continue;
7115
7116 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7117 CandidateSet);
7118 }
7119
7120 for (BuiltinCandidateTypeSet::iterator
7121 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7122 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7123 MemPtr != MemPtrEnd; ++MemPtr) {
7124 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7125 continue;
7126
7127 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7128 CandidateSet);
7129 }
7130 }
7131 }
7132
7133 // C++ [over.built]p19:
7134 //
7135 // For every pair (T, VQ), where T is any type and VQ is either
7136 // volatile or empty, there exist candidate operator functions
7137 // of the form
7138 //
7139 // T*VQ& operator=(T*VQ&, T*);
7140 //
7141 // C++ [over.built]p21:
7142 //
7143 // For every pair (T, VQ), where T is a cv-qualified or
7144 // cv-unqualified object type and VQ is either volatile or
7145 // empty, there exist candidate operator functions of the form
7146 //
7147 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7148 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7149 void addAssignmentPointerOverloads(bool isEqualOp) {
7150 /// Set of (canonical) types that we've already handled.
7151 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7152
7153 for (BuiltinCandidateTypeSet::iterator
7154 Ptr = CandidateTypes[0].pointer_begin(),
7155 PtrEnd = CandidateTypes[0].pointer_end();
7156 Ptr != PtrEnd; ++Ptr) {
7157 // If this is operator=, keep track of the builtin candidates we added.
7158 if (isEqualOp)
7159 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007160 else if (!(*Ptr)->getPointeeType()->isObjectType())
7161 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007162
7163 // non-volatile version
7164 QualType ParamTypes[2] = {
7165 S.Context.getLValueReferenceType(*Ptr),
7166 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7167 };
7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7169 /*IsAssigmentOperator=*/ isEqualOp);
7170
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007171 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7172 VisibleTypeConversionsQuals.hasVolatile();
7173 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007174 // volatile version
7175 ParamTypes[0] =
7176 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7177 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7178 /*IsAssigmentOperator=*/isEqualOp);
7179 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007180
7181 if (!(*Ptr).isRestrictQualified() &&
7182 VisibleTypeConversionsQuals.hasRestrict()) {
7183 // restrict version
7184 ParamTypes[0]
7185 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7186 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7187 /*IsAssigmentOperator=*/isEqualOp);
7188
7189 if (NeedVolatile) {
7190 // volatile restrict version
7191 ParamTypes[0]
7192 = S.Context.getLValueReferenceType(
7193 S.Context.getCVRQualifiedType(*Ptr,
7194 (Qualifiers::Volatile |
7195 Qualifiers::Restrict)));
7196 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7197 CandidateSet,
7198 /*IsAssigmentOperator=*/isEqualOp);
7199 }
7200 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007201 }
7202
7203 if (isEqualOp) {
7204 for (BuiltinCandidateTypeSet::iterator
7205 Ptr = CandidateTypes[1].pointer_begin(),
7206 PtrEnd = CandidateTypes[1].pointer_end();
7207 Ptr != PtrEnd; ++Ptr) {
7208 // Make sure we don't add the same candidate twice.
7209 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7210 continue;
7211
Chandler Carruth6df868e2010-12-12 08:17:55 +00007212 QualType ParamTypes[2] = {
7213 S.Context.getLValueReferenceType(*Ptr),
7214 *Ptr,
7215 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007216
7217 // non-volatile version
7218 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7219 /*IsAssigmentOperator=*/true);
7220
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007221 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7222 VisibleTypeConversionsQuals.hasVolatile();
7223 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224 // volatile version
7225 ParamTypes[0] =
7226 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007227 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7228 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007229 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007230
7231 if (!(*Ptr).isRestrictQualified() &&
7232 VisibleTypeConversionsQuals.hasRestrict()) {
7233 // restrict version
7234 ParamTypes[0]
7235 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7236 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7237 CandidateSet, /*IsAssigmentOperator=*/true);
7238
7239 if (NeedVolatile) {
7240 // volatile restrict version
7241 ParamTypes[0]
7242 = S.Context.getLValueReferenceType(
7243 S.Context.getCVRQualifiedType(*Ptr,
7244 (Qualifiers::Volatile |
7245 Qualifiers::Restrict)));
7246 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7247 CandidateSet, /*IsAssigmentOperator=*/true);
7248
7249 }
7250 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007251 }
7252 }
7253 }
7254
7255 // C++ [over.built]p18:
7256 //
7257 // For every triple (L, VQ, R), where L is an arithmetic type,
7258 // VQ is either volatile or empty, and R is a promoted
7259 // arithmetic type, there exist candidate operator functions of
7260 // the form
7261 //
7262 // VQ L& operator=(VQ L&, R);
7263 // VQ L& operator*=(VQ L&, R);
7264 // VQ L& operator/=(VQ L&, R);
7265 // VQ L& operator+=(VQ L&, R);
7266 // VQ L& operator-=(VQ L&, R);
7267 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007268 if (!HasArithmeticOrEnumeralCandidateType)
7269 return;
7270
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007271 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7272 for (unsigned Right = FirstPromotedArithmeticType;
7273 Right < LastPromotedArithmeticType; ++Right) {
7274 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007275 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007276
7277 // Add this built-in operator as a candidate (VQ is empty).
7278 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007279 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7281 /*IsAssigmentOperator=*/isEqualOp);
7282
7283 // Add this built-in operator as a candidate (VQ is 'volatile').
7284 if (VisibleTypeConversionsQuals.hasVolatile()) {
7285 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007286 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007287 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007288 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7289 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007290 /*IsAssigmentOperator=*/isEqualOp);
7291 }
7292 }
7293 }
7294
7295 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7296 for (BuiltinCandidateTypeSet::iterator
7297 Vec1 = CandidateTypes[0].vector_begin(),
7298 Vec1End = CandidateTypes[0].vector_end();
7299 Vec1 != Vec1End; ++Vec1) {
7300 for (BuiltinCandidateTypeSet::iterator
7301 Vec2 = CandidateTypes[1].vector_begin(),
7302 Vec2End = CandidateTypes[1].vector_end();
7303 Vec2 != Vec2End; ++Vec2) {
7304 QualType ParamTypes[2];
7305 ParamTypes[1] = *Vec2;
7306 // Add this built-in operator as a candidate (VQ is empty).
7307 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7309 /*IsAssigmentOperator=*/isEqualOp);
7310
7311 // Add this built-in operator as a candidate (VQ is 'volatile').
7312 if (VisibleTypeConversionsQuals.hasVolatile()) {
7313 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7314 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7316 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007317 /*IsAssigmentOperator=*/isEqualOp);
7318 }
7319 }
7320 }
7321 }
7322
7323 // C++ [over.built]p22:
7324 //
7325 // For every triple (L, VQ, R), where L is an integral type, VQ
7326 // is either volatile or empty, and R is a promoted integral
7327 // type, there exist candidate operator functions of the form
7328 //
7329 // VQ L& operator%=(VQ L&, R);
7330 // VQ L& operator<<=(VQ L&, R);
7331 // VQ L& operator>>=(VQ L&, R);
7332 // VQ L& operator&=(VQ L&, R);
7333 // VQ L& operator^=(VQ L&, R);
7334 // VQ L& operator|=(VQ L&, R);
7335 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007336 if (!HasArithmeticOrEnumeralCandidateType)
7337 return;
7338
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007339 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7340 for (unsigned Right = FirstPromotedIntegralType;
7341 Right < LastPromotedIntegralType; ++Right) {
7342 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007343 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007344
7345 // Add this built-in operator as a candidate (VQ is empty).
7346 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007347 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007348 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7349 if (VisibleTypeConversionsQuals.hasVolatile()) {
7350 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007351 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7353 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7354 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7355 CandidateSet);
7356 }
7357 }
7358 }
7359 }
7360
7361 // C++ [over.operator]p23:
7362 //
7363 // There also exist candidate operator functions of the form
7364 //
7365 // bool operator!(bool);
7366 // bool operator&&(bool, bool);
7367 // bool operator||(bool, bool);
7368 void addExclaimOverload() {
7369 QualType ParamTy = S.Context.BoolTy;
7370 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7371 /*IsAssignmentOperator=*/false,
7372 /*NumContextualBoolArguments=*/1);
7373 }
7374 void addAmpAmpOrPipePipeOverload() {
7375 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7376 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7377 /*IsAssignmentOperator=*/false,
7378 /*NumContextualBoolArguments=*/2);
7379 }
7380
7381 // C++ [over.built]p13:
7382 //
7383 // For every cv-qualified or cv-unqualified object type T there
7384 // exist candidate operator functions of the form
7385 //
7386 // T* operator+(T*, ptrdiff_t); [ABOVE]
7387 // T& operator[](T*, ptrdiff_t);
7388 // T* operator-(T*, ptrdiff_t); [ABOVE]
7389 // T* operator+(ptrdiff_t, T*); [ABOVE]
7390 // T& operator[](ptrdiff_t, T*);
7391 void addSubscriptOverloads() {
7392 for (BuiltinCandidateTypeSet::iterator
7393 Ptr = CandidateTypes[0].pointer_begin(),
7394 PtrEnd = CandidateTypes[0].pointer_end();
7395 Ptr != PtrEnd; ++Ptr) {
7396 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7397 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007398 if (!PointeeType->isObjectType())
7399 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007400
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007401 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7402
7403 // T& operator[](T*, ptrdiff_t)
7404 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7405 }
7406
7407 for (BuiltinCandidateTypeSet::iterator
7408 Ptr = CandidateTypes[1].pointer_begin(),
7409 PtrEnd = CandidateTypes[1].pointer_end();
7410 Ptr != PtrEnd; ++Ptr) {
7411 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7412 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007413 if (!PointeeType->isObjectType())
7414 continue;
7415
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007416 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7417
7418 // T& operator[](ptrdiff_t, T*)
7419 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7420 }
7421 }
7422
7423 // C++ [over.built]p11:
7424 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7425 // C1 is the same type as C2 or is a derived class of C2, T is an object
7426 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7427 // there exist candidate operator functions of the form
7428 //
7429 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7430 //
7431 // where CV12 is the union of CV1 and CV2.
7432 void addArrowStarOverloads() {
7433 for (BuiltinCandidateTypeSet::iterator
7434 Ptr = CandidateTypes[0].pointer_begin(),
7435 PtrEnd = CandidateTypes[0].pointer_end();
7436 Ptr != PtrEnd; ++Ptr) {
7437 QualType C1Ty = (*Ptr);
7438 QualType C1;
7439 QualifierCollector Q1;
7440 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7441 if (!isa<RecordType>(C1))
7442 continue;
7443 // heuristic to reduce number of builtin candidates in the set.
7444 // Add volatile/restrict version only if there are conversions to a
7445 // volatile/restrict type.
7446 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7447 continue;
7448 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7449 continue;
7450 for (BuiltinCandidateTypeSet::iterator
7451 MemPtr = CandidateTypes[1].member_pointer_begin(),
7452 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7453 MemPtr != MemPtrEnd; ++MemPtr) {
7454 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7455 QualType C2 = QualType(mptr->getClass(), 0);
7456 C2 = C2.getUnqualifiedType();
7457 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7458 break;
7459 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7460 // build CV12 T&
7461 QualType T = mptr->getPointeeType();
7462 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7463 T.isVolatileQualified())
7464 continue;
7465 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7466 T.isRestrictQualified())
7467 continue;
7468 T = Q1.apply(S.Context, T);
7469 QualType ResultTy = S.Context.getLValueReferenceType(T);
7470 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7471 }
7472 }
7473 }
7474
7475 // Note that we don't consider the first argument, since it has been
7476 // contextually converted to bool long ago. The candidates below are
7477 // therefore added as binary.
7478 //
7479 // C++ [over.built]p25:
7480 // For every type T, where T is a pointer, pointer-to-member, or scoped
7481 // enumeration type, there exist candidate operator functions of the form
7482 //
7483 // T operator?(bool, T, T);
7484 //
7485 void addConditionalOperatorOverloads() {
7486 /// Set of (canonical) types that we've already handled.
7487 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7488
7489 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7490 for (BuiltinCandidateTypeSet::iterator
7491 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7492 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7493 Ptr != PtrEnd; ++Ptr) {
7494 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7495 continue;
7496
7497 QualType ParamTypes[2] = { *Ptr, *Ptr };
7498 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7499 }
7500
7501 for (BuiltinCandidateTypeSet::iterator
7502 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7503 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7504 MemPtr != MemPtrEnd; ++MemPtr) {
7505 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7506 continue;
7507
7508 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7509 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7510 }
7511
Richard Smith80ad52f2013-01-02 11:42:31 +00007512 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007513 for (BuiltinCandidateTypeSet::iterator
7514 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7515 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7516 Enum != EnumEnd; ++Enum) {
7517 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7518 continue;
7519
7520 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7521 continue;
7522
7523 QualType ParamTypes[2] = { *Enum, *Enum };
7524 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7525 }
7526 }
7527 }
7528 }
7529};
7530
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007531} // end anonymous namespace
7532
7533/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7534/// operator overloads to the candidate set (C++ [over.built]), based
7535/// on the operator @p Op and the arguments given. For example, if the
7536/// operator is a binary '+', this routine might add "int
7537/// operator+(int, int)" to cover integer addition.
7538void
7539Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7540 SourceLocation OpLoc,
7541 Expr **Args, unsigned NumArgs,
7542 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007543 // Find all of the types that the arguments can convert to, but only
7544 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007545 // that make use of these types. Also record whether we encounter non-record
7546 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007547 Qualifiers VisibleTypeConversionsQuals;
7548 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007549 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7550 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007551
7552 bool HasNonRecordCandidateType = false;
7553 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007554 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007555 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7556 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7557 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7558 OpLoc,
7559 true,
7560 (Op == OO_Exclaim ||
7561 Op == OO_AmpAmp ||
7562 Op == OO_PipePipe),
7563 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007564 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7565 CandidateTypes[ArgIdx].hasNonRecordTypes();
7566 HasArithmeticOrEnumeralCandidateType =
7567 HasArithmeticOrEnumeralCandidateType ||
7568 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007569 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007570
Chandler Carruth6a577462010-12-13 01:44:01 +00007571 // Exit early when no non-record types have been added to the candidate set
7572 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007573 //
7574 // We can't exit early for !, ||, or &&, since there we have always have
7575 // 'bool' overloads.
7576 if (!HasNonRecordCandidateType &&
7577 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007578 return;
7579
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007580 // Setup an object to manage the common state for building overloads.
7581 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7582 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007583 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007584 CandidateTypes, CandidateSet);
7585
7586 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007587 switch (Op) {
7588 case OO_None:
7589 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007590 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007591
Chandler Carruthabb71842010-12-12 08:51:33 +00007592 case OO_New:
7593 case OO_Delete:
7594 case OO_Array_New:
7595 case OO_Array_Delete:
7596 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007597 llvm_unreachable(
7598 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007599
7600 case OO_Comma:
7601 case OO_Arrow:
7602 // C++ [over.match.oper]p3:
7603 // -- For the operator ',', the unary operator '&', or the
7604 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007605 break;
7606
7607 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007608 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007609 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007610 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007611
7612 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007613 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007614 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007615 } else {
7616 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7617 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7618 }
Douglas Gregor74253732008-11-19 15:42:04 +00007619 break;
7620
Chandler Carruthabb71842010-12-12 08:51:33 +00007621 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007622 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007623 OpBuilder.addUnaryStarPointerOverloads();
7624 else
7625 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7626 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007627
Chandler Carruthabb71842010-12-12 08:51:33 +00007628 case OO_Slash:
7629 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007630 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007631
7632 case OO_PlusPlus:
7633 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007634 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7635 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007636 break;
7637
Douglas Gregor19b7b152009-08-24 13:43:27 +00007638 case OO_EqualEqual:
7639 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007640 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007641 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007642
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007643 case OO_Less:
7644 case OO_Greater:
7645 case OO_LessEqual:
7646 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007647 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007648 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7649 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007650
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007651 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007652 case OO_Caret:
7653 case OO_Pipe:
7654 case OO_LessLess:
7655 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007656 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007657 break;
7658
Chandler Carruthabb71842010-12-12 08:51:33 +00007659 case OO_Amp: // '&' is either unary or binary
7660 if (NumArgs == 1)
7661 // C++ [over.match.oper]p3:
7662 // -- For the operator ',', the unary operator '&', or the
7663 // operator '->', the built-in candidates set is empty.
7664 break;
7665
7666 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7667 break;
7668
7669 case OO_Tilde:
7670 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7671 break;
7672
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007673 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007674 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007675 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007676
7677 case OO_PlusEqual:
7678 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007679 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007680 // Fall through.
7681
7682 case OO_StarEqual:
7683 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007684 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007685 break;
7686
7687 case OO_PercentEqual:
7688 case OO_LessLessEqual:
7689 case OO_GreaterGreaterEqual:
7690 case OO_AmpEqual:
7691 case OO_CaretEqual:
7692 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007693 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007694 break;
7695
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007696 case OO_Exclaim:
7697 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007698 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007699
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007700 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007701 case OO_PipePipe:
7702 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007703 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007704
7705 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007706 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007707 break;
7708
7709 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007710 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007711 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007712
7713 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007714 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007715 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7716 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007717 }
7718}
7719
Douglas Gregorfa047642009-02-04 00:32:51 +00007720/// \brief Add function candidates found via argument-dependent lookup
7721/// to the set of overloading candidates.
7722///
7723/// This routine performs argument-dependent name lookup based on the
7724/// given function name (which may also be an operator name) and adds
7725/// all of the overload candidates found by ADL to the overload
7726/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007727void
Douglas Gregorfa047642009-02-04 00:32:51 +00007728Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007729 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007730 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007731 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007732 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007733 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007734 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007735
John McCalla113e722010-01-26 06:04:06 +00007736 // FIXME: This approach for uniquing ADL results (and removing
7737 // redundant candidates from the set) relies on pointer-equality,
7738 // which means we need to key off the canonical decl. However,
7739 // always going back to the canonical decl might not get us the
7740 // right set of default arguments. What default arguments are
7741 // we supposed to consider on ADL candidates, anyway?
7742
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007743 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007744 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007745
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007746 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007747 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7748 CandEnd = CandidateSet.end();
7749 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007750 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007751 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007752 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007753 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007754 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007755
7756 // For each of the ADL candidates we found, add it to the overload
7757 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007758 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007759 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007761 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007762 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007763
Ahmed Charles13a140c2012-02-25 11:00:22 +00007764 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7765 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007766 } else
John McCall6e266892010-01-26 03:27:55 +00007767 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007768 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007769 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007770 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007771}
7772
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007773/// isBetterOverloadCandidate - Determines whether the first overload
7774/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007775bool
John McCall120d63c2010-08-24 20:38:10 +00007776isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007777 const OverloadCandidate &Cand1,
7778 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007779 SourceLocation Loc,
7780 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007781 // Define viable functions to be better candidates than non-viable
7782 // functions.
7783 if (!Cand2.Viable)
7784 return Cand1.Viable;
7785 else if (!Cand1.Viable)
7786 return false;
7787
Douglas Gregor88a35142008-12-22 05:46:06 +00007788 // C++ [over.match.best]p1:
7789 //
7790 // -- if F is a static member function, ICS1(F) is defined such
7791 // that ICS1(F) is neither better nor worse than ICS1(G) for
7792 // any function G, and, symmetrically, ICS1(G) is neither
7793 // better nor worse than ICS1(F).
7794 unsigned StartArg = 0;
7795 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7796 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007797
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007798 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007799 // A viable function F1 is defined to be a better function than another
7800 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007801 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007802 unsigned NumArgs = Cand1.NumConversions;
7803 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007804 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007805 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007806 switch (CompareImplicitConversionSequences(S,
7807 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007808 Cand2.Conversions[ArgIdx])) {
7809 case ImplicitConversionSequence::Better:
7810 // Cand1 has a better conversion sequence.
7811 HasBetterConversion = true;
7812 break;
7813
7814 case ImplicitConversionSequence::Worse:
7815 // Cand1 can't be better than Cand2.
7816 return false;
7817
7818 case ImplicitConversionSequence::Indistinguishable:
7819 // Do nothing.
7820 break;
7821 }
7822 }
7823
Mike Stump1eb44332009-09-09 15:08:12 +00007824 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007825 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007826 if (HasBetterConversion)
7827 return true;
7828
Mike Stump1eb44332009-09-09 15:08:12 +00007829 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007830 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007831 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007832 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7833 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007834
7835 // -- F1 and F2 are function template specializations, and the function
7836 // template for F1 is more specialized than the template for F2
7837 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007838 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007839 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007840 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007841 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007842 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7843 Cand2.Function->getPrimaryTemplate(),
7844 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007845 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007846 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007847 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007848 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007849 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007850
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007851 // -- the context is an initialization by user-defined conversion
7852 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7853 // from the return type of F1 to the destination type (i.e.,
7854 // the type of the entity being initialized) is a better
7855 // conversion sequence than the standard conversion sequence
7856 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007857 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007858 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007859 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007860 // First check whether we prefer one of the conversion functions over the
7861 // other. This only distinguishes the results in non-standard, extension
7862 // cases such as the conversion from a lambda closure type to a function
7863 // pointer or block.
7864 ImplicitConversionSequence::CompareKind FuncResult
7865 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7866 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7867 return FuncResult;
7868
John McCall120d63c2010-08-24 20:38:10 +00007869 switch (CompareStandardConversionSequences(S,
7870 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007871 Cand2.FinalConversion)) {
7872 case ImplicitConversionSequence::Better:
7873 // Cand1 has a better conversion sequence.
7874 return true;
7875
7876 case ImplicitConversionSequence::Worse:
7877 // Cand1 can't be better than Cand2.
7878 return false;
7879
7880 case ImplicitConversionSequence::Indistinguishable:
7881 // Do nothing
7882 break;
7883 }
7884 }
7885
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007886 return false;
7887}
7888
Mike Stump1eb44332009-09-09 15:08:12 +00007889/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007890/// within an overload candidate set.
7891///
James Dennettefce31f2012-06-22 08:10:18 +00007892/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007893/// which overload resolution occurs.
7894///
James Dennettefce31f2012-06-22 08:10:18 +00007895/// \param Best If overload resolution was successful or found a deleted
7896/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007897///
7898/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007899OverloadingResult
7900OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007901 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007902 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007903 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007904 Best = end();
7905 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7906 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007907 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007908 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007909 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007910 }
7911
7912 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007913 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007914 return OR_No_Viable_Function;
7915
7916 // Make sure that this function is better than every other viable
7917 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007918 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007919 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007920 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007921 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007922 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007923 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007924 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007925 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007926 }
Mike Stump1eb44332009-09-09 15:08:12 +00007927
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007928 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007929 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007930 (Best->Function->isDeleted() ||
7931 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007932 return OR_Deleted;
7933
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007934 return OR_Success;
7935}
7936
John McCall3c80f572010-01-12 02:15:36 +00007937namespace {
7938
7939enum OverloadCandidateKind {
7940 oc_function,
7941 oc_method,
7942 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007943 oc_function_template,
7944 oc_method_template,
7945 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007946 oc_implicit_default_constructor,
7947 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007948 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007949 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007950 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007951 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007952};
7953
John McCall220ccbf2010-01-13 00:25:19 +00007954OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7955 FunctionDecl *Fn,
7956 std::string &Description) {
7957 bool isTemplate = false;
7958
7959 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7960 isTemplate = true;
7961 Description = S.getTemplateArgumentBindingsText(
7962 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7963 }
John McCallb1622a12010-01-06 09:43:14 +00007964
7965 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007966 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007967 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007968
Sebastian Redlf677ea32011-02-05 19:23:19 +00007969 if (Ctor->getInheritedConstructor())
7970 return oc_implicit_inherited_constructor;
7971
Sean Hunt82713172011-05-25 23:16:36 +00007972 if (Ctor->isDefaultConstructor())
7973 return oc_implicit_default_constructor;
7974
7975 if (Ctor->isMoveConstructor())
7976 return oc_implicit_move_constructor;
7977
7978 assert(Ctor->isCopyConstructor() &&
7979 "unexpected sort of implicit constructor");
7980 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007981 }
7982
7983 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7984 // This actually gets spelled 'candidate function' for now, but
7985 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007986 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007987 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007988
Sean Hunt82713172011-05-25 23:16:36 +00007989 if (Meth->isMoveAssignmentOperator())
7990 return oc_implicit_move_assignment;
7991
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007992 if (Meth->isCopyAssignmentOperator())
7993 return oc_implicit_copy_assignment;
7994
7995 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7996 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007997 }
7998
John McCall220ccbf2010-01-13 00:25:19 +00007999 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008000}
8001
Sebastian Redlf677ea32011-02-05 19:23:19 +00008002void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8003 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8004 if (!Ctor) return;
8005
8006 Ctor = Ctor->getInheritedConstructor();
8007 if (!Ctor) return;
8008
8009 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8010}
8011
John McCall3c80f572010-01-12 02:15:36 +00008012} // end anonymous namespace
8013
8014// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008015void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008016 std::string FnDesc;
8017 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008018 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8019 << (unsigned) K << FnDesc;
8020 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8021 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008022 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008023}
8024
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008025//Notes the location of all overload candidates designated through
8026// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008027void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008028 assert(OverloadedExpr->getType() == Context.OverloadTy);
8029
8030 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8031 OverloadExpr *OvlExpr = Ovl.Expression;
8032
8033 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8034 IEnd = OvlExpr->decls_end();
8035 I != IEnd; ++I) {
8036 if (FunctionTemplateDecl *FunTmpl =
8037 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008038 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008039 } else if (FunctionDecl *Fun
8040 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008041 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008042 }
8043 }
8044}
8045
John McCall1d318332010-01-12 00:44:57 +00008046/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8047/// "lead" diagnostic; it will be given two arguments, the source and
8048/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008049void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8050 Sema &S,
8051 SourceLocation CaretLoc,
8052 const PartialDiagnostic &PDiag) const {
8053 S.Diag(CaretLoc, PDiag)
8054 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008055 // FIXME: The note limiting machinery is borrowed from
8056 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8057 // refactoring here.
8058 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8059 unsigned CandsShown = 0;
8060 AmbiguousConversionSequence::const_iterator I, E;
8061 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8062 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8063 break;
8064 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008065 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008066 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008067 if (I != E)
8068 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008069}
8070
John McCall1d318332010-01-12 00:44:57 +00008071namespace {
8072
John McCalladbb8f82010-01-13 09:16:55 +00008073void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8074 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8075 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008076 assert(Cand->Function && "for now, candidate must be a function");
8077 FunctionDecl *Fn = Cand->Function;
8078
8079 // There's a conversion slot for the object argument if this is a
8080 // non-constructor method. Note that 'I' corresponds the
8081 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008082 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008083 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008084 if (I == 0)
8085 isObjectArgument = true;
8086 else
8087 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008088 }
8089
John McCall220ccbf2010-01-13 00:25:19 +00008090 std::string FnDesc;
8091 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8092
John McCalladbb8f82010-01-13 09:16:55 +00008093 Expr *FromExpr = Conv.Bad.FromExpr;
8094 QualType FromTy = Conv.Bad.getFromType();
8095 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008096
John McCall5920dbb2010-02-02 02:42:52 +00008097 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008098 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008099 Expr *E = FromExpr->IgnoreParens();
8100 if (isa<UnaryOperator>(E))
8101 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008102 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008103
8104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8105 << (unsigned) FnKind << FnDesc
8106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8107 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008108 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008109 return;
8110 }
8111
John McCall258b2032010-01-23 08:10:49 +00008112 // Do some hand-waving analysis to see if the non-viability is due
8113 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008114 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8115 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8116 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8117 CToTy = RT->getPointeeType();
8118 else {
8119 // TODO: detect and diagnose the full richness of const mismatches.
8120 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8121 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8122 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8123 }
8124
8125 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8126 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008127 Qualifiers FromQs = CFromTy.getQualifiers();
8128 Qualifiers ToQs = CToTy.getQualifiers();
8129
8130 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8131 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8132 << (unsigned) FnKind << FnDesc
8133 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8134 << FromTy
8135 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8136 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008137 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008138 return;
8139 }
8140
John McCallf85e1932011-06-15 23:02:42 +00008141 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008143 << (unsigned) FnKind << FnDesc
8144 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8145 << FromTy
8146 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8147 << (unsigned) isObjectArgument << I+1;
8148 MaybeEmitInheritedConstructorNote(S, Fn);
8149 return;
8150 }
8151
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008152 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8153 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8154 << (unsigned) FnKind << FnDesc
8155 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8156 << FromTy
8157 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8158 << (unsigned) isObjectArgument << I+1;
8159 MaybeEmitInheritedConstructorNote(S, Fn);
8160 return;
8161 }
8162
John McCall651f3ee2010-01-14 03:28:57 +00008163 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8164 assert(CVR && "unexpected qualifiers mismatch");
8165
8166 if (isObjectArgument) {
8167 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8168 << (unsigned) FnKind << FnDesc
8169 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8170 << FromTy << (CVR - 1);
8171 } else {
8172 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8173 << (unsigned) FnKind << FnDesc
8174 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8175 << FromTy << (CVR - 1) << I+1;
8176 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008177 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008178 return;
8179 }
8180
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008181 // Special diagnostic for failure to convert an initializer list, since
8182 // telling the user that it has type void is not useful.
8183 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8184 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8185 << (unsigned) FnKind << FnDesc
8186 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8187 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8188 MaybeEmitInheritedConstructorNote(S, Fn);
8189 return;
8190 }
8191
John McCall258b2032010-01-23 08:10:49 +00008192 // Diagnose references or pointers to incomplete types differently,
8193 // since it's far from impossible that the incompleteness triggered
8194 // the failure.
8195 QualType TempFromTy = FromTy.getNonReferenceType();
8196 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8197 TempFromTy = PTy->getPointeeType();
8198 if (TempFromTy->isIncompleteType()) {
8199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8200 << (unsigned) FnKind << FnDesc
8201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8202 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008203 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008204 return;
8205 }
8206
Douglas Gregor85789812010-06-30 23:01:39 +00008207 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008208 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008209 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8210 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8211 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8212 FromPtrTy->getPointeeType()) &&
8213 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8214 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008215 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008216 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008217 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008218 }
8219 } else if (const ObjCObjectPointerType *FromPtrTy
8220 = FromTy->getAs<ObjCObjectPointerType>()) {
8221 if (const ObjCObjectPointerType *ToPtrTy
8222 = ToTy->getAs<ObjCObjectPointerType>())
8223 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8224 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8225 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8226 FromPtrTy->getPointeeType()) &&
8227 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008228 BaseToDerivedConversion = 2;
8229 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008230 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8231 !FromTy->isIncompleteType() &&
8232 !ToRefTy->getPointeeType()->isIncompleteType() &&
8233 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8234 BaseToDerivedConversion = 3;
8235 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8236 ToTy.getNonReferenceType().getCanonicalType() ==
8237 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008238 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8239 << (unsigned) FnKind << FnDesc
8240 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8241 << (unsigned) isObjectArgument << I + 1;
8242 MaybeEmitInheritedConstructorNote(S, Fn);
8243 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008244 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008246
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008247 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008248 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008249 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008250 << (unsigned) FnKind << FnDesc
8251 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008252 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008253 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008254 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008255 return;
8256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008257
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008258 if (isa<ObjCObjectPointerType>(CFromTy) &&
8259 isa<PointerType>(CToTy)) {
8260 Qualifiers FromQs = CFromTy.getQualifiers();
8261 Qualifiers ToQs = CToTy.getQualifiers();
8262 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8264 << (unsigned) FnKind << FnDesc
8265 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8266 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8267 MaybeEmitInheritedConstructorNote(S, Fn);
8268 return;
8269 }
8270 }
8271
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008272 // Emit the generic diagnostic and, optionally, add the hints to it.
8273 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8274 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008276 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8277 << (unsigned) (Cand->Fix.Kind);
8278
8279 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008280 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8281 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008282 FDiag << *HI;
8283 S.Diag(Fn->getLocation(), FDiag);
8284
Sebastian Redlf677ea32011-02-05 19:23:19 +00008285 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008286}
8287
8288void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8289 unsigned NumFormalArgs) {
8290 // TODO: treat calls to a missing default constructor as a special case
8291
8292 FunctionDecl *Fn = Cand->Function;
8293 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8294
8295 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008296
Douglas Gregor439d3c32011-05-05 00:13:13 +00008297 // With invalid overloaded operators, it's possible that we think we
8298 // have an arity mismatch when it fact it looks like we have the
8299 // right number of arguments, because only overloaded operators have
8300 // the weird behavior of overloading member and non-member functions.
8301 // Just don't report anything.
8302 if (Fn->isInvalidDecl() &&
8303 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8304 return;
8305
John McCalladbb8f82010-01-13 09:16:55 +00008306 // at least / at most / exactly
8307 unsigned mode, modeCount;
8308 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008309 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8310 (Cand->FailureKind == ovl_fail_bad_deduction &&
8311 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008312 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008313 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008314 mode = 0; // "at least"
8315 else
8316 mode = 2; // "exactly"
8317 modeCount = MinParams;
8318 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008319 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8320 (Cand->FailureKind == ovl_fail_bad_deduction &&
8321 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008322 if (MinParams != FnTy->getNumArgs())
8323 mode = 1; // "at most"
8324 else
8325 mode = 2; // "exactly"
8326 modeCount = FnTy->getNumArgs();
8327 }
8328
8329 std::string Description;
8330 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8331
Richard Smithf7b80562012-05-11 05:16:41 +00008332 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8333 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8334 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8335 << Fn->getParamDecl(0) << NumFormalArgs;
8336 else
8337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8338 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8339 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008340 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008341}
8342
John McCall342fec42010-02-01 18:53:26 +00008343/// Diagnose a failed template-argument deduction.
8344void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008345 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008346 FunctionDecl *Fn = Cand->Function; // pattern
8347
Douglas Gregora9333192010-05-08 17:41:32 +00008348 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008349 NamedDecl *ParamD;
8350 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8351 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8352 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008353 switch (Cand->DeductionFailure.Result) {
8354 case Sema::TDK_Success:
8355 llvm_unreachable("TDK_success while diagnosing bad deduction");
8356
8357 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008358 assert(ParamD && "no parameter found for incomplete deduction result");
8359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8360 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008361 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008362 return;
8363 }
8364
John McCall57e97782010-08-05 09:05:08 +00008365 case Sema::TDK_Underqualified: {
8366 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8367 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8368
8369 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8370
8371 // Param will have been canonicalized, but it should just be a
8372 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008373 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008374 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008375 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008376 assert(S.Context.hasSameType(Param, NonCanonParam));
8377
8378 // Arg has also been canonicalized, but there's nothing we can do
8379 // about that. It also doesn't matter as much, because it won't
8380 // have any template parameters in it (because deduction isn't
8381 // done on dependent types).
8382 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8383
8384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8385 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008386 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008387 return;
8388 }
8389
8390 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008391 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008392 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008393 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008394 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008395 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008396 which = 1;
8397 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008398 which = 2;
8399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008400
Douglas Gregora9333192010-05-08 17:41:32 +00008401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008402 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008403 << *Cand->DeductionFailure.getFirstArg()
8404 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008405 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008406 return;
8407 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008408
Douglas Gregorf1a84452010-05-08 19:15:54 +00008409 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008410 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008411 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008412 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008413 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8414 << ParamD->getDeclName();
8415 else {
8416 int index = 0;
8417 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8418 index = TTP->getIndex();
8419 else if (NonTypeTemplateParmDecl *NTTP
8420 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8421 index = NTTP->getIndex();
8422 else
8423 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008424 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008425 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8426 << (index + 1);
8427 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008428 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008429 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008430
Douglas Gregora18592e2010-05-08 18:13:28 +00008431 case Sema::TDK_TooManyArguments:
8432 case Sema::TDK_TooFewArguments:
8433 DiagnoseArityMismatch(S, Cand, NumArgs);
8434 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008435
8436 case Sema::TDK_InstantiationDepth:
8437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008438 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008439 return;
8440
8441 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008442 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008443 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008444 if (TemplateArgumentList *Args =
8445 Cand->DeductionFailure.getTemplateArgumentList()) {
8446 TemplateArgString = " ";
8447 TemplateArgString += S.getTemplateArgumentBindingsText(
8448 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8449 }
8450
Richard Smith4493c0a2012-05-09 05:17:00 +00008451 // If this candidate was disabled by enable_if, say so.
8452 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8453 if (PDiag && PDiag->second.getDiagID() ==
8454 diag::err_typename_nested_not_found_enable_if) {
8455 // FIXME: Use the source range of the condition, and the fully-qualified
8456 // name of the enable_if template. These are both present in PDiag.
8457 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8458 << "'enable_if'" << TemplateArgString;
8459 return;
8460 }
8461
Richard Smithb8590f32012-05-07 09:03:25 +00008462 // Format the SFINAE diagnostic into the argument string.
8463 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8464 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008465 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008466 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008467 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008468 SFINAEArgString = ": ";
8469 R = SourceRange(PDiag->first, PDiag->first);
8470 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8471 }
8472
Douglas Gregorec20f462010-05-08 20:07:26 +00008473 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008474 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008475 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008476 return;
8477 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008478
Richard Smith0efa62f2013-01-31 04:03:12 +00008479 case Sema::TDK_FailedOverloadResolution: {
8480 OverloadExpr::FindResult R =
8481 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8482 S.Diag(Fn->getLocation(),
8483 diag::note_ovl_candidate_failed_overload_resolution)
8484 << R.Expression->getName();
8485 return;
8486 }
8487
Richard Smith29805ca2013-01-31 05:19:49 +00008488 case Sema::TDK_NonDeducedMismatch:
8489 // FIXME: Provide a source location to indicate what we couldn't match.
8490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8491 << *Cand->DeductionFailure.getFirstArg()
8492 << *Cand->DeductionFailure.getSecondArg();
8493 return;
8494
John McCall342fec42010-02-01 18:53:26 +00008495 // TODO: diagnose these individually, then kill off
8496 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008497 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008499 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008500 return;
8501 }
8502}
8503
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008504/// CUDA: diagnose an invalid call across targets.
8505void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8506 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8507 FunctionDecl *Callee = Cand->Function;
8508
8509 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8510 CalleeTarget = S.IdentifyCUDATarget(Callee);
8511
8512 std::string FnDesc;
8513 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8514
8515 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8516 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8517}
8518
John McCall342fec42010-02-01 18:53:26 +00008519/// Generates a 'note' diagnostic for an overload candidate. We've
8520/// already generated a primary error at the call site.
8521///
8522/// It really does need to be a single diagnostic with its caret
8523/// pointed at the candidate declaration. Yes, this creates some
8524/// major challenges of technical writing. Yes, this makes pointing
8525/// out problems with specific arguments quite awkward. It's still
8526/// better than generating twenty screens of text for every failed
8527/// overload.
8528///
8529/// It would be great to be able to express per-candidate problems
8530/// more richly for those diagnostic clients that cared, but we'd
8531/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008532void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008533 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008534 FunctionDecl *Fn = Cand->Function;
8535
John McCall81201622010-01-08 04:41:39 +00008536 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008537 if (Cand->Viable && (Fn->isDeleted() ||
8538 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008539 std::string FnDesc;
8540 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008541
8542 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008543 << FnKind << FnDesc
8544 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008545 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008546 return;
John McCall81201622010-01-08 04:41:39 +00008547 }
8548
John McCall220ccbf2010-01-13 00:25:19 +00008549 // We don't really have anything else to say about viable candidates.
8550 if (Cand->Viable) {
8551 S.NoteOverloadCandidate(Fn);
8552 return;
8553 }
John McCall1d318332010-01-12 00:44:57 +00008554
John McCalladbb8f82010-01-13 09:16:55 +00008555 switch (Cand->FailureKind) {
8556 case ovl_fail_too_many_arguments:
8557 case ovl_fail_too_few_arguments:
8558 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008559
John McCalladbb8f82010-01-13 09:16:55 +00008560 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008561 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008562
John McCall717e8912010-01-23 05:17:32 +00008563 case ovl_fail_trivial_conversion:
8564 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008565 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008566 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008567
John McCallb1bdc622010-02-25 01:37:24 +00008568 case ovl_fail_bad_conversion: {
8569 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008570 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008571 if (Cand->Conversions[I].isBad())
8572 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008573
John McCalladbb8f82010-01-13 09:16:55 +00008574 // FIXME: this currently happens when we're called from SemaInit
8575 // when user-conversion overload fails. Figure out how to handle
8576 // those conditions and diagnose them well.
8577 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008578 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008579
8580 case ovl_fail_bad_target:
8581 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008582 }
John McCalla1d7d622010-01-08 00:58:21 +00008583}
8584
8585void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8586 // Desugar the type of the surrogate down to a function type,
8587 // retaining as many typedefs as possible while still showing
8588 // the function type (and, therefore, its parameter types).
8589 QualType FnType = Cand->Surrogate->getConversionType();
8590 bool isLValueReference = false;
8591 bool isRValueReference = false;
8592 bool isPointer = false;
8593 if (const LValueReferenceType *FnTypeRef =
8594 FnType->getAs<LValueReferenceType>()) {
8595 FnType = FnTypeRef->getPointeeType();
8596 isLValueReference = true;
8597 } else if (const RValueReferenceType *FnTypeRef =
8598 FnType->getAs<RValueReferenceType>()) {
8599 FnType = FnTypeRef->getPointeeType();
8600 isRValueReference = true;
8601 }
8602 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8603 FnType = FnTypePtr->getPointeeType();
8604 isPointer = true;
8605 }
8606 // Desugar down to a function type.
8607 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8608 // Reconstruct the pointer/reference as appropriate.
8609 if (isPointer) FnType = S.Context.getPointerType(FnType);
8610 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8611 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8612
8613 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8614 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008615 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008616}
8617
8618void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008619 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008620 SourceLocation OpLoc,
8621 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008622 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008623 std::string TypeStr("operator");
8624 TypeStr += Opc;
8625 TypeStr += "(";
8626 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008627 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008628 TypeStr += ")";
8629 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8630 } else {
8631 TypeStr += ", ";
8632 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8633 TypeStr += ")";
8634 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8635 }
8636}
8637
8638void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8639 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008640 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008641 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8642 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008643 if (ICS.isBad()) break; // all meaningless after first invalid
8644 if (!ICS.isAmbiguous()) continue;
8645
John McCall120d63c2010-08-24 20:38:10 +00008646 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008647 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008648 }
8649}
8650
John McCall1b77e732010-01-15 23:32:50 +00008651SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8652 if (Cand->Function)
8653 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008654 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008655 return Cand->Surrogate->getLocation();
8656 return SourceLocation();
8657}
8658
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008659static unsigned
8660RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008661 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008662 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008663 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008664
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008665 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008666 case Sema::TDK_Incomplete:
8667 return 1;
8668
8669 case Sema::TDK_Underqualified:
8670 case Sema::TDK_Inconsistent:
8671 return 2;
8672
8673 case Sema::TDK_SubstitutionFailure:
8674 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008675 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008676 return 3;
8677
8678 case Sema::TDK_InstantiationDepth:
8679 case Sema::TDK_FailedOverloadResolution:
8680 return 4;
8681
8682 case Sema::TDK_InvalidExplicitArguments:
8683 return 5;
8684
8685 case Sema::TDK_TooManyArguments:
8686 case Sema::TDK_TooFewArguments:
8687 return 6;
8688 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008689 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008690}
8691
John McCallbf65c0b2010-01-12 00:48:53 +00008692struct CompareOverloadCandidatesForDisplay {
8693 Sema &S;
8694 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008695
8696 bool operator()(const OverloadCandidate *L,
8697 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008698 // Fast-path this check.
8699 if (L == R) return false;
8700
John McCall81201622010-01-08 04:41:39 +00008701 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008702 if (L->Viable) {
8703 if (!R->Viable) return true;
8704
8705 // TODO: introduce a tri-valued comparison for overload
8706 // candidates. Would be more worthwhile if we had a sort
8707 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008708 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8709 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008710 } else if (R->Viable)
8711 return false;
John McCall81201622010-01-08 04:41:39 +00008712
John McCall1b77e732010-01-15 23:32:50 +00008713 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008714
John McCall1b77e732010-01-15 23:32:50 +00008715 // Criteria by which we can sort non-viable candidates:
8716 if (!L->Viable) {
8717 // 1. Arity mismatches come after other candidates.
8718 if (L->FailureKind == ovl_fail_too_many_arguments ||
8719 L->FailureKind == ovl_fail_too_few_arguments)
8720 return false;
8721 if (R->FailureKind == ovl_fail_too_many_arguments ||
8722 R->FailureKind == ovl_fail_too_few_arguments)
8723 return true;
John McCall81201622010-01-08 04:41:39 +00008724
John McCall717e8912010-01-23 05:17:32 +00008725 // 2. Bad conversions come first and are ordered by the number
8726 // of bad conversions and quality of good conversions.
8727 if (L->FailureKind == ovl_fail_bad_conversion) {
8728 if (R->FailureKind != ovl_fail_bad_conversion)
8729 return true;
8730
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008731 // The conversion that can be fixed with a smaller number of changes,
8732 // comes first.
8733 unsigned numLFixes = L->Fix.NumConversionsFixed;
8734 unsigned numRFixes = R->Fix.NumConversionsFixed;
8735 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8736 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008737 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008738 if (numLFixes < numRFixes)
8739 return true;
8740 else
8741 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008742 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008743
John McCall717e8912010-01-23 05:17:32 +00008744 // If there's any ordering between the defined conversions...
8745 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008746 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008747
8748 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008749 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008750 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008751 switch (CompareImplicitConversionSequences(S,
8752 L->Conversions[I],
8753 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008754 case ImplicitConversionSequence::Better:
8755 leftBetter++;
8756 break;
8757
8758 case ImplicitConversionSequence::Worse:
8759 leftBetter--;
8760 break;
8761
8762 case ImplicitConversionSequence::Indistinguishable:
8763 break;
8764 }
8765 }
8766 if (leftBetter > 0) return true;
8767 if (leftBetter < 0) return false;
8768
8769 } else if (R->FailureKind == ovl_fail_bad_conversion)
8770 return false;
8771
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008772 if (L->FailureKind == ovl_fail_bad_deduction) {
8773 if (R->FailureKind != ovl_fail_bad_deduction)
8774 return true;
8775
8776 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8777 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008778 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008779 } else if (R->FailureKind == ovl_fail_bad_deduction)
8780 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008781
John McCall1b77e732010-01-15 23:32:50 +00008782 // TODO: others?
8783 }
8784
8785 // Sort everything else by location.
8786 SourceLocation LLoc = GetLocationForCandidate(L);
8787 SourceLocation RLoc = GetLocationForCandidate(R);
8788
8789 // Put candidates without locations (e.g. builtins) at the end.
8790 if (LLoc.isInvalid()) return false;
8791 if (RLoc.isInvalid()) return true;
8792
8793 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008794 }
8795};
8796
John McCall717e8912010-01-23 05:17:32 +00008797/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008798/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008799void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008800 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008801 assert(!Cand->Viable);
8802
8803 // Don't do anything on failures other than bad conversion.
8804 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8805
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008806 // We only want the FixIts if all the arguments can be corrected.
8807 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008808 // Use a implicit copy initialization to check conversion fixes.
8809 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008810
John McCall717e8912010-01-23 05:17:32 +00008811 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008812 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008813 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008814 while (true) {
8815 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8816 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008817 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008818 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008819 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008820 }
John McCall717e8912010-01-23 05:17:32 +00008821 }
8822
8823 if (ConvIdx == ConvCount)
8824 return;
8825
John McCallb1bdc622010-02-25 01:37:24 +00008826 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8827 "remaining conversion is initialized?");
8828
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008829 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008830 // operation somehow.
8831 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008832
8833 const FunctionProtoType* Proto;
8834 unsigned ArgIdx = ConvIdx;
8835
8836 if (Cand->IsSurrogate) {
8837 QualType ConvType
8838 = Cand->Surrogate->getConversionType().getNonReferenceType();
8839 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8840 ConvType = ConvPtrType->getPointeeType();
8841 Proto = ConvType->getAs<FunctionProtoType>();
8842 ArgIdx--;
8843 } else if (Cand->Function) {
8844 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8845 if (isa<CXXMethodDecl>(Cand->Function) &&
8846 !isa<CXXConstructorDecl>(Cand->Function))
8847 ArgIdx--;
8848 } else {
8849 // Builtin binary operator with a bad first conversion.
8850 assert(ConvCount <= 3);
8851 for (; ConvIdx != ConvCount; ++ConvIdx)
8852 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008853 = TryCopyInitialization(S, Args[ConvIdx],
8854 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008855 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008856 /*InOverloadResolution*/ true,
8857 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008858 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008859 return;
8860 }
8861
8862 // Fill in the rest of the conversions.
8863 unsigned NumArgsInProto = Proto->getNumArgs();
8864 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008865 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008866 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008867 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008868 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008869 /*InOverloadResolution=*/true,
8870 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008871 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008872 // Store the FixIt in the candidate if it exists.
8873 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008874 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008875 }
John McCall717e8912010-01-23 05:17:32 +00008876 else
8877 Cand->Conversions[ConvIdx].setEllipsis();
8878 }
8879}
8880
John McCalla1d7d622010-01-08 00:58:21 +00008881} // end anonymous namespace
8882
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008883/// PrintOverloadCandidates - When overload resolution fails, prints
8884/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008885/// set.
John McCall120d63c2010-08-24 20:38:10 +00008886void OverloadCandidateSet::NoteCandidates(Sema &S,
8887 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008888 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008889 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008890 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008891 // Sort the candidates by viability and position. Sorting directly would
8892 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008893 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008894 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8895 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008896 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008897 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008898 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008899 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008900 if (Cand->Function || Cand->IsSurrogate)
8901 Cands.push_back(Cand);
8902 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8903 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008904 }
8905 }
8906
John McCallbf65c0b2010-01-12 00:48:53 +00008907 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008908 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008909
John McCall1d318332010-01-12 00:44:57 +00008910 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008911
Chris Lattner5f9e2722011-07-23 10:55:15 +00008912 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008913 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008914 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008915 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8916 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008917
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008918 // Set an arbitrary limit on the number of candidate functions we'll spam
8919 // the user with. FIXME: This limit should depend on details of the
8920 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008921 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008922 break;
8923 }
8924 ++CandsShown;
8925
John McCalla1d7d622010-01-08 00:58:21 +00008926 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008927 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008928 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008929 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008930 else {
8931 assert(Cand->Viable &&
8932 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008933 // Generally we only see ambiguities including viable builtin
8934 // operators if overload resolution got screwed up by an
8935 // ambiguous user-defined conversion.
8936 //
8937 // FIXME: It's quite possible for different conversions to see
8938 // different ambiguities, though.
8939 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008940 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008941 ReportedAmbiguousConversions = true;
8942 }
John McCalla1d7d622010-01-08 00:58:21 +00008943
John McCall1d318332010-01-12 00:44:57 +00008944 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008945 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008946 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008947 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008948
8949 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008950 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008951}
8952
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008953// [PossiblyAFunctionType] --> [Return]
8954// NonFunctionType --> NonFunctionType
8955// R (A) --> R(A)
8956// R (*)(A) --> R (A)
8957// R (&)(A) --> R (A)
8958// R (S::*)(A) --> R (A)
8959QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8960 QualType Ret = PossiblyAFunctionType;
8961 if (const PointerType *ToTypePtr =
8962 PossiblyAFunctionType->getAs<PointerType>())
8963 Ret = ToTypePtr->getPointeeType();
8964 else if (const ReferenceType *ToTypeRef =
8965 PossiblyAFunctionType->getAs<ReferenceType>())
8966 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008967 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008968 PossiblyAFunctionType->getAs<MemberPointerType>())
8969 Ret = MemTypePtr->getPointeeType();
8970 Ret =
8971 Context.getCanonicalType(Ret).getUnqualifiedType();
8972 return Ret;
8973}
Douglas Gregor904eed32008-11-10 20:40:00 +00008974
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008975// A helper class to help with address of function resolution
8976// - allows us to avoid passing around all those ugly parameters
8977class AddressOfFunctionResolver
8978{
8979 Sema& S;
8980 Expr* SourceExpr;
8981 const QualType& TargetType;
8982 QualType TargetFunctionType; // Extracted function type from target type
8983
8984 bool Complain;
8985 //DeclAccessPair& ResultFunctionAccessPair;
8986 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008987
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008988 bool TargetTypeIsNonStaticMemberFunction;
8989 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008990
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008991 OverloadExpr::FindResult OvlExprInfo;
8992 OverloadExpr *OvlExpr;
8993 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008994 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008995
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008996public:
8997 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8998 const QualType& TargetType, bool Complain)
8999 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9000 Complain(Complain), Context(S.getASTContext()),
9001 TargetTypeIsNonStaticMemberFunction(
9002 !!TargetType->getAs<MemberPointerType>()),
9003 FoundNonTemplateFunction(false),
9004 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9005 OvlExpr(OvlExprInfo.Expression)
9006 {
9007 ExtractUnqualifiedFunctionTypeFromTargetType();
9008
9009 if (!TargetFunctionType->isFunctionType()) {
9010 if (OvlExpr->hasExplicitTemplateArgs()) {
9011 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009012 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009013 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009014
9015 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9016 if (!Method->isStatic()) {
9017 // If the target type is a non-function type and the function
9018 // found is a non-static member function, pretend as if that was
9019 // the target, it's the only possible type to end up with.
9020 TargetTypeIsNonStaticMemberFunction = true;
9021
9022 // And skip adding the function if its not in the proper form.
9023 // We'll diagnose this due to an empty set of functions.
9024 if (!OvlExprInfo.HasFormOfMemberPointer)
9025 return;
9026 }
9027 }
9028
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009029 Matches.push_back(std::make_pair(dap,Fn));
9030 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009031 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009032 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009033 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009034
9035 if (OvlExpr->hasExplicitTemplateArgs())
9036 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009037
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009038 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9039 // C++ [over.over]p4:
9040 // If more than one function is selected, [...]
9041 if (Matches.size() > 1) {
9042 if (FoundNonTemplateFunction)
9043 EliminateAllTemplateMatches();
9044 else
9045 EliminateAllExceptMostSpecializedTemplate();
9046 }
9047 }
9048 }
9049
9050private:
9051 bool isTargetTypeAFunction() const {
9052 return TargetFunctionType->isFunctionType();
9053 }
9054
9055 // [ToType] [Return]
9056
9057 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9058 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9059 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9060 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9061 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9062 }
9063
9064 // return true if any matching specializations were found
9065 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9066 const DeclAccessPair& CurAccessFunPair) {
9067 if (CXXMethodDecl *Method
9068 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9069 // Skip non-static function templates when converting to pointer, and
9070 // static when converting to member pointer.
9071 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9072 return false;
9073 }
9074 else if (TargetTypeIsNonStaticMemberFunction)
9075 return false;
9076
9077 // C++ [over.over]p2:
9078 // If the name is a function template, template argument deduction is
9079 // done (14.8.2.2), and if the argument deduction succeeds, the
9080 // resulting template argument list is used to generate a single
9081 // function template specialization, which is added to the set of
9082 // overloaded functions considered.
9083 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009084 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009085 if (Sema::TemplateDeductionResult Result
9086 = S.DeduceTemplateArguments(FunctionTemplate,
9087 &OvlExplicitTemplateArgs,
9088 TargetFunctionType, Specialization,
9089 Info)) {
9090 // FIXME: make a note of the failed deduction for diagnostics.
9091 (void)Result;
9092 return false;
9093 }
9094
9095 // Template argument deduction ensures that we have an exact match.
9096 // This function template specicalization works.
9097 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9098 assert(TargetFunctionType
9099 == Context.getCanonicalType(Specialization->getType()));
9100 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9101 return true;
9102 }
9103
9104 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9105 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009106 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009107 // Skip non-static functions when converting to pointer, and static
9108 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009109 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9110 return false;
9111 }
9112 else if (TargetTypeIsNonStaticMemberFunction)
9113 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009114
Chandler Carruthbd647292009-12-29 06:17:27 +00009115 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009116 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009117 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9118 if (S.CheckCUDATarget(Caller, FunDecl))
9119 return false;
9120
Douglas Gregor43c79c22009-12-09 00:47:37 +00009121 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009122 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9123 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009124 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9125 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009126 Matches.push_back(std::make_pair(CurAccessFunPair,
9127 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009128 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009129 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009130 }
Mike Stump1eb44332009-09-09 15:08:12 +00009131 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009132
9133 return false;
9134 }
9135
9136 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9137 bool Ret = false;
9138
9139 // If the overload expression doesn't have the form of a pointer to
9140 // member, don't try to convert it to a pointer-to-member type.
9141 if (IsInvalidFormOfPointerToMemberFunction())
9142 return false;
9143
9144 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9145 E = OvlExpr->decls_end();
9146 I != E; ++I) {
9147 // Look through any using declarations to find the underlying function.
9148 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9149
9150 // C++ [over.over]p3:
9151 // Non-member functions and static member functions match
9152 // targets of type "pointer-to-function" or "reference-to-function."
9153 // Nonstatic member functions match targets of
9154 // type "pointer-to-member-function."
9155 // Note that according to DR 247, the containing class does not matter.
9156 if (FunctionTemplateDecl *FunctionTemplate
9157 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9158 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9159 Ret = true;
9160 }
9161 // If we have explicit template arguments supplied, skip non-templates.
9162 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9163 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9164 Ret = true;
9165 }
9166 assert(Ret || Matches.empty());
9167 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009168 }
9169
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009170 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009171 // [...] and any given function template specialization F1 is
9172 // eliminated if the set contains a second function template
9173 // specialization whose function template is more specialized
9174 // than the function template of F1 according to the partial
9175 // ordering rules of 14.5.5.2.
9176
9177 // The algorithm specified above is quadratic. We instead use a
9178 // two-pass algorithm (similar to the one used to identify the
9179 // best viable function in an overload set) that identifies the
9180 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009181
9182 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9183 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9184 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009185
John McCallc373d482010-01-27 01:50:18 +00009186 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009187 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9188 TPOC_Other, 0, SourceExpr->getLocStart(),
9189 S.PDiag(),
9190 S.PDiag(diag::err_addr_ovl_ambiguous)
9191 << Matches[0].second->getDeclName(),
9192 S.PDiag(diag::note_ovl_candidate)
9193 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009194 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009195
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009196 if (Result != MatchesCopy.end()) {
9197 // Make it the first and only element
9198 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9199 Matches[0].second = cast<FunctionDecl>(*Result);
9200 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009201 }
9202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009203
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009204 void EliminateAllTemplateMatches() {
9205 // [...] any function template specializations in the set are
9206 // eliminated if the set also contains a non-template function, [...]
9207 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9208 if (Matches[I].second->getPrimaryTemplate() == 0)
9209 ++I;
9210 else {
9211 Matches[I] = Matches[--N];
9212 Matches.set_size(N);
9213 }
9214 }
9215 }
9216
9217public:
9218 void ComplainNoMatchesFound() const {
9219 assert(Matches.empty());
9220 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9221 << OvlExpr->getName() << TargetFunctionType
9222 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009223 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009224 }
9225
9226 bool IsInvalidFormOfPointerToMemberFunction() const {
9227 return TargetTypeIsNonStaticMemberFunction &&
9228 !OvlExprInfo.HasFormOfMemberPointer;
9229 }
9230
9231 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9232 // TODO: Should we condition this on whether any functions might
9233 // have matched, or is it more appropriate to do that in callers?
9234 // TODO: a fixit wouldn't hurt.
9235 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9236 << TargetType << OvlExpr->getSourceRange();
9237 }
9238
9239 void ComplainOfInvalidConversion() const {
9240 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9241 << OvlExpr->getName() << TargetType;
9242 }
9243
9244 void ComplainMultipleMatchesFound() const {
9245 assert(Matches.size() > 1);
9246 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9247 << OvlExpr->getName()
9248 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009249 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009250 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009251
9252 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9253
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009254 int getNumMatches() const { return Matches.size(); }
9255
9256 FunctionDecl* getMatchingFunctionDecl() const {
9257 if (Matches.size() != 1) return 0;
9258 return Matches[0].second;
9259 }
9260
9261 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9262 if (Matches.size() != 1) return 0;
9263 return &Matches[0].first;
9264 }
9265};
9266
9267/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9268/// an overloaded function (C++ [over.over]), where @p From is an
9269/// expression with overloaded function type and @p ToType is the type
9270/// we're trying to resolve to. For example:
9271///
9272/// @code
9273/// int f(double);
9274/// int f(int);
9275///
9276/// int (*pfd)(double) = f; // selects f(double)
9277/// @endcode
9278///
9279/// This routine returns the resulting FunctionDecl if it could be
9280/// resolved, and NULL otherwise. When @p Complain is true, this
9281/// routine will emit diagnostics if there is an error.
9282FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009283Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9284 QualType TargetType,
9285 bool Complain,
9286 DeclAccessPair &FoundResult,
9287 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009288 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009289
9290 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9291 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009292 int NumMatches = Resolver.getNumMatches();
9293 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009294 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9296 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9297 else
9298 Resolver.ComplainNoMatchesFound();
9299 }
9300 else if (NumMatches > 1 && Complain)
9301 Resolver.ComplainMultipleMatchesFound();
9302 else if (NumMatches == 1) {
9303 Fn = Resolver.getMatchingFunctionDecl();
9304 assert(Fn);
9305 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009306 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009307 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009308 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009309
9310 if (pHadMultipleCandidates)
9311 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009312 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009313}
9314
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009315/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009316/// resolve that overloaded function expression down to a single function.
9317///
9318/// This routine can only resolve template-ids that refer to a single function
9319/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009320/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009321/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009322FunctionDecl *
9323Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9324 bool Complain,
9325 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009326 // C++ [over.over]p1:
9327 // [...] [Note: any redundant set of parentheses surrounding the
9328 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009329 // C++ [over.over]p1:
9330 // [...] The overloaded function name can be preceded by the &
9331 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009332
Douglas Gregor4b52e252009-12-21 23:17:24 +00009333 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009334 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009335 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009336
9337 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009338 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009339
Douglas Gregor4b52e252009-12-21 23:17:24 +00009340 // Look through all of the overloaded functions, searching for one
9341 // whose type matches exactly.
9342 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009343 for (UnresolvedSetIterator I = ovl->decls_begin(),
9344 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009345 // C++0x [temp.arg.explicit]p3:
9346 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009347 // where deduction is not done, if a template argument list is
9348 // specified and it, along with any default template arguments,
9349 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009350 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009351 FunctionTemplateDecl *FunctionTemplate
9352 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009353
Douglas Gregor4b52e252009-12-21 23:17:24 +00009354 // C++ [over.over]p2:
9355 // If the name is a function template, template argument deduction is
9356 // done (14.8.2.2), and if the argument deduction succeeds, the
9357 // resulting template argument list is used to generate a single
9358 // function template specialization, which is added to the set of
9359 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009360 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009361 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009362 if (TemplateDeductionResult Result
9363 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9364 Specialization, Info)) {
9365 // FIXME: make a note of the failed deduction for diagnostics.
9366 (void)Result;
9367 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009368 }
9369
John McCall864c0412011-04-26 20:42:42 +00009370 assert(Specialization && "no specialization and no error?");
9371
Douglas Gregor4b52e252009-12-21 23:17:24 +00009372 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009373 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009374 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009375 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9376 << ovl->getName();
9377 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009378 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009379 return 0;
John McCall864c0412011-04-26 20:42:42 +00009380 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009381
John McCall864c0412011-04-26 20:42:42 +00009382 Matched = Specialization;
9383 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009385
Douglas Gregor4b52e252009-12-21 23:17:24 +00009386 return Matched;
9387}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009388
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009389
9390
9391
John McCall6dbba4f2011-10-11 23:14:30 +00009392// Resolve and fix an overloaded expression that can be resolved
9393// because it identifies a single function template specialization.
9394//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009395// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009396//
9397// Return true if it was logically possible to so resolve the
9398// expression, regardless of whether or not it succeeded. Always
9399// returns true if 'complain' is set.
9400bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9401 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9402 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009403 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009404 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009405 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009406
John McCall6dbba4f2011-10-11 23:14:30 +00009407 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009408
John McCall864c0412011-04-26 20:42:42 +00009409 DeclAccessPair found;
9410 ExprResult SingleFunctionExpression;
9411 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9412 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009413 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009414 SrcExpr = ExprError();
9415 return true;
9416 }
John McCall864c0412011-04-26 20:42:42 +00009417
9418 // It is only correct to resolve to an instance method if we're
9419 // resolving a form that's permitted to be a pointer to member.
9420 // Otherwise we'll end up making a bound member expression, which
9421 // is illegal in all the contexts we resolve like this.
9422 if (!ovl.HasFormOfMemberPointer &&
9423 isa<CXXMethodDecl>(fn) &&
9424 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009425 if (!complain) return false;
9426
9427 Diag(ovl.Expression->getExprLoc(),
9428 diag::err_bound_member_function)
9429 << 0 << ovl.Expression->getSourceRange();
9430
9431 // TODO: I believe we only end up here if there's a mix of
9432 // static and non-static candidates (otherwise the expression
9433 // would have 'bound member' type, not 'overload' type).
9434 // Ideally we would note which candidate was chosen and why
9435 // the static candidates were rejected.
9436 SrcExpr = ExprError();
9437 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009438 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009439
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009440 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009441 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009442 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009443
9444 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009445 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009446 SingleFunctionExpression =
9447 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009448 if (SingleFunctionExpression.isInvalid()) {
9449 SrcExpr = ExprError();
9450 return true;
9451 }
9452 }
John McCall864c0412011-04-26 20:42:42 +00009453 }
9454
9455 if (!SingleFunctionExpression.isUsable()) {
9456 if (complain) {
9457 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9458 << ovl.Expression->getName()
9459 << DestTypeForComplaining
9460 << OpRangeForComplaining
9461 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009462 NoteAllOverloadCandidates(SrcExpr.get());
9463
9464 SrcExpr = ExprError();
9465 return true;
9466 }
9467
9468 return false;
John McCall864c0412011-04-26 20:42:42 +00009469 }
9470
John McCall6dbba4f2011-10-11 23:14:30 +00009471 SrcExpr = SingleFunctionExpression;
9472 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009473}
9474
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009475/// \brief Add a single candidate to the overload set.
9476static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009477 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009478 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009479 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009480 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009481 bool PartialOverloading,
9482 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009483 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009484 if (isa<UsingShadowDecl>(Callee))
9485 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9486
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009487 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009488 if (ExplicitTemplateArgs) {
9489 assert(!KnownValid && "Explicit template arguments?");
9490 return;
9491 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009492 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9493 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009494 return;
John McCallba135432009-11-21 08:51:07 +00009495 }
9496
9497 if (FunctionTemplateDecl *FuncTemplate
9498 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009499 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009500 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009501 return;
9502 }
9503
Richard Smith2ced0442011-06-26 22:19:54 +00009504 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009505}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009506
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009507/// \brief Add the overload candidates named by callee and/or found by argument
9508/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009509void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009510 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009511 OverloadCandidateSet &CandidateSet,
9512 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009513
9514#ifndef NDEBUG
9515 // Verify that ArgumentDependentLookup is consistent with the rules
9516 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009517 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009518 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9519 // and let Y be the lookup set produced by argument dependent
9520 // lookup (defined as follows). If X contains
9521 //
9522 // -- a declaration of a class member, or
9523 //
9524 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009525 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009526 //
9527 // -- a declaration that is neither a function or a function
9528 // template
9529 //
9530 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009531
John McCall3b4294e2009-12-16 12:17:52 +00009532 if (ULE->requiresADL()) {
9533 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9534 E = ULE->decls_end(); I != E; ++I) {
9535 assert(!(*I)->getDeclContext()->isRecord());
9536 assert(isa<UsingShadowDecl>(*I) ||
9537 !(*I)->getDeclContext()->isFunctionOrMethod());
9538 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009539 }
9540 }
9541#endif
9542
John McCall3b4294e2009-12-16 12:17:52 +00009543 // It would be nice to avoid this copy.
9544 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009545 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009546 if (ULE->hasExplicitTemplateArgs()) {
9547 ULE->copyTemplateArgumentsInto(TABuffer);
9548 ExplicitTemplateArgs = &TABuffer;
9549 }
9550
9551 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9552 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009553 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9554 CandidateSet, PartialOverloading,
9555 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009556
John McCall3b4294e2009-12-16 12:17:52 +00009557 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009558 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009559 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009560 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009561 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009562}
John McCall578b69b2009-12-16 08:11:27 +00009563
Richard Smithf50e88a2011-06-05 22:42:48 +00009564/// Attempt to recover from an ill-formed use of a non-dependent name in a
9565/// template, where the non-dependent name was declared after the template
9566/// was defined. This is common in code written for a compilers which do not
9567/// correctly implement two-stage name lookup.
9568///
9569/// Returns true if a viable candidate was found and a diagnostic was issued.
9570static bool
9571DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9572 const CXXScopeSpec &SS, LookupResult &R,
9573 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009574 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009575 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9576 return false;
9577
9578 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009579 if (DC->isTransparentContext())
9580 continue;
9581
Richard Smithf50e88a2011-06-05 22:42:48 +00009582 SemaRef.LookupQualifiedName(R, DC);
9583
9584 if (!R.empty()) {
9585 R.suppressDiagnostics();
9586
9587 if (isa<CXXRecordDecl>(DC)) {
9588 // Don't diagnose names we find in classes; we get much better
9589 // diagnostics for these from DiagnoseEmptyLookup.
9590 R.clear();
9591 return false;
9592 }
9593
9594 OverloadCandidateSet Candidates(FnLoc);
9595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9596 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009597 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009598 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009599
9600 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009601 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009602 // No viable functions. Don't bother the user with notes for functions
9603 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009604 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009605 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009606 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009607
9608 // Find the namespaces where ADL would have looked, and suggest
9609 // declaring the function there instead.
9610 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9611 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009612 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009613 AssociatedNamespaces,
9614 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009615 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009616 DeclContext *Std = SemaRef.getStdNamespace();
9617 for (Sema::AssociatedNamespaceSet::iterator
9618 it = AssociatedNamespaces.begin(),
9619 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009620 // Never suggest declaring a function within namespace 'std'.
9621 if (Std && Std->Encloses(*it))
9622 continue;
9623
9624 // Never suggest declaring a function within a namespace with a reserved
9625 // name, like __gnu_cxx.
9626 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9627 if (NS &&
9628 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9629 continue;
9630
9631 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009632 }
9633
9634 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9635 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009636 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009637 SemaRef.Diag(Best->Function->getLocation(),
9638 diag::note_not_found_by_two_phase_lookup)
9639 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009640 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009641 SemaRef.Diag(Best->Function->getLocation(),
9642 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009643 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009644 } else {
9645 // FIXME: It would be useful to list the associated namespaces here,
9646 // but the diagnostics infrastructure doesn't provide a way to produce
9647 // a localized representation of a list of items.
9648 SemaRef.Diag(Best->Function->getLocation(),
9649 diag::note_not_found_by_two_phase_lookup)
9650 << R.getLookupName() << 2;
9651 }
9652
9653 // Try to recover by calling this function.
9654 return true;
9655 }
9656
9657 R.clear();
9658 }
9659
9660 return false;
9661}
9662
9663/// Attempt to recover from ill-formed use of a non-dependent operator in a
9664/// template, where the non-dependent operator was declared after the template
9665/// was defined.
9666///
9667/// Returns true if a viable candidate was found and a diagnostic was issued.
9668static bool
9669DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9670 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009671 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009672 DeclarationName OpName =
9673 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9674 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9675 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009676 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009677}
9678
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009679namespace {
9680// Callback to limit the allowed keywords and to only accept typo corrections
9681// that are keywords or whose decls refer to functions (or template functions)
9682// that accept the given number of arguments.
9683class RecoveryCallCCC : public CorrectionCandidateCallback {
9684 public:
9685 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9686 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009687 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009688 WantRemainingKeywords = false;
9689 }
9690
9691 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9692 if (!candidate.getCorrectionDecl())
9693 return candidate.isKeyword();
9694
9695 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9696 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9697 FunctionDecl *FD = 0;
9698 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9699 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9700 FD = FTD->getTemplatedDecl();
9701 if (!HasExplicitTemplateArgs && !FD) {
9702 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9703 // If the Decl is neither a function nor a template function,
9704 // determine if it is a pointer or reference to a function. If so,
9705 // check against the number of arguments expected for the pointee.
9706 QualType ValType = cast<ValueDecl>(ND)->getType();
9707 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9708 ValType = ValType->getPointeeType();
9709 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9710 if (FPT->getNumArgs() == NumArgs)
9711 return true;
9712 }
9713 }
9714 if (FD && FD->getNumParams() >= NumArgs &&
9715 FD->getMinRequiredArguments() <= NumArgs)
9716 return true;
9717 }
9718 return false;
9719 }
9720
9721 private:
9722 unsigned NumArgs;
9723 bool HasExplicitTemplateArgs;
9724};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009725
9726// Callback that effectively disabled typo correction
9727class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9728 public:
9729 NoTypoCorrectionCCC() {
9730 WantTypeSpecifiers = false;
9731 WantExpressionKeywords = false;
9732 WantCXXNamedCasts = false;
9733 WantRemainingKeywords = false;
9734 }
9735
9736 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9737 return false;
9738 }
9739};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009740
9741class BuildRecoveryCallExprRAII {
9742 Sema &SemaRef;
9743public:
9744 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9745 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9746 SemaRef.IsBuildingRecoveryCallExpr = true;
9747 }
9748
9749 ~BuildRecoveryCallExprRAII() {
9750 SemaRef.IsBuildingRecoveryCallExpr = false;
9751 }
9752};
9753
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009754}
9755
John McCall578b69b2009-12-16 08:11:27 +00009756/// Attempts to recover from a call where no functions were found.
9757///
9758/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009759static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009760BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009761 UnresolvedLookupExpr *ULE,
9762 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009763 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009764 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009765 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009766 // Do not try to recover if it is already building a recovery call.
9767 // This stops infinite loops for template instantiations like
9768 //
9769 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9770 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9771 //
9772 if (SemaRef.IsBuildingRecoveryCallExpr)
9773 return ExprError();
9774 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009775
9776 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009777 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009778 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009779
John McCall3b4294e2009-12-16 12:17:52 +00009780 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009781 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009782 if (ULE->hasExplicitTemplateArgs()) {
9783 ULE->copyTemplateArgumentsInto(TABuffer);
9784 ExplicitTemplateArgs = &TABuffer;
9785 }
9786
John McCall578b69b2009-12-16 08:11:27 +00009787 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9788 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009789 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009790 NoTypoCorrectionCCC RejectAll;
9791 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9792 (CorrectionCandidateCallback*)&Validator :
9793 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009794 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009795 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009796 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009797 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009798 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009799 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009800
John McCall3b4294e2009-12-16 12:17:52 +00009801 assert(!R.empty() && "lookup results empty despite recovery");
9802
9803 // Build an implicit member call if appropriate. Just drop the
9804 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009805 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009806 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009807 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9808 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009809 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009810 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009811 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009812 else
9813 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9814
9815 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009816 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009817
9818 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009819 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009820 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009821 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009822 MultiExprArg(Args.data(), Args.size()),
9823 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009824}
Douglas Gregord7a95972010-06-08 17:35:15 +00009825
Sam Panzere1715b62012-08-21 00:52:01 +00009826/// \brief Constructs and populates an OverloadedCandidateSet from
9827/// the given function.
9828/// \returns true when an the ExprResult output parameter has been set.
9829bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9830 UnresolvedLookupExpr *ULE,
9831 Expr **Args, unsigned NumArgs,
9832 SourceLocation RParenLoc,
9833 OverloadCandidateSet *CandidateSet,
9834 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009835#ifndef NDEBUG
9836 if (ULE->requiresADL()) {
9837 // To do ADL, we must have found an unqualified name.
9838 assert(!ULE->getQualifier() && "qualified name with ADL");
9839
9840 // We don't perform ADL for implicit declarations of builtins.
9841 // Verify that this was correctly set up.
9842 FunctionDecl *F;
9843 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9844 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9845 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009846 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009847
John McCall3b4294e2009-12-16 12:17:52 +00009848 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009849 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009850 }
John McCall3b4294e2009-12-16 12:17:52 +00009851#endif
9852
John McCall5acb0c92011-10-17 18:40:02 +00009853 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009854 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9855 *Result = ExprError();
9856 return true;
9857 }
Douglas Gregor17330012009-02-04 15:01:18 +00009858
John McCall3b4294e2009-12-16 12:17:52 +00009859 // Add the functions denoted by the callee to the set of candidate
9860 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009861 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009862 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009863
9864 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009865 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9866 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009867 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009868 // In Microsoft mode, if we are inside a template class member function then
9869 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009870 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009871 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009872 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009873 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009874 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9875 llvm::makeArrayRef(Args, NumArgs),
9876 Context.DependentTy, VK_RValue,
9877 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009878 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009879 *Result = Owned(CE);
9880 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009881 }
Sam Panzere1715b62012-08-21 00:52:01 +00009882 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009883 }
John McCall578b69b2009-12-16 08:11:27 +00009884
John McCall5acb0c92011-10-17 18:40:02 +00009885 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009886 return false;
9887}
John McCall5acb0c92011-10-17 18:40:02 +00009888
Sam Panzere1715b62012-08-21 00:52:01 +00009889/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9890/// the completed call expression. If overload resolution fails, emits
9891/// diagnostics and returns ExprError()
9892static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9893 UnresolvedLookupExpr *ULE,
9894 SourceLocation LParenLoc,
9895 Expr **Args, unsigned NumArgs,
9896 SourceLocation RParenLoc,
9897 Expr *ExecConfig,
9898 OverloadCandidateSet *CandidateSet,
9899 OverloadCandidateSet::iterator *Best,
9900 OverloadingResult OverloadResult,
9901 bool AllowTypoCorrection) {
9902 if (CandidateSet->empty())
9903 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9904 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9905 RParenLoc, /*EmptyLookup=*/true,
9906 AllowTypoCorrection);
9907
9908 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009909 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009910 FunctionDecl *FDecl = (*Best)->Function;
9911 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9912 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9913 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9914 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9915 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9916 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009917 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009918
Richard Smithf50e88a2011-06-05 22:42:48 +00009919 case OR_No_Viable_Function: {
9920 // Try to recover by looking for viable functions which the user might
9921 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009922 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009923 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9924 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009925 /*EmptyLookup=*/false,
9926 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009927 if (!Recovery.isInvalid())
9928 return Recovery;
9929
Sam Panzere1715b62012-08-21 00:52:01 +00009930 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009931 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009932 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009933 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9934 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009935 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009936 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009937
9938 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009939 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009940 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009941 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9942 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009943 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009944
Sam Panzere1715b62012-08-21 00:52:01 +00009945 case OR_Deleted: {
9946 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9947 << (*Best)->Function->isDeleted()
9948 << ULE->getName()
9949 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9950 << Fn->getSourceRange();
9951 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9952 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009953
Sam Panzere1715b62012-08-21 00:52:01 +00009954 // We emitted an error for the unvailable/deleted function call but keep
9955 // the call in the AST.
9956 FunctionDecl *FDecl = (*Best)->Function;
9957 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9958 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9959 RParenLoc, ExecConfig);
9960 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009961 }
9962
Douglas Gregorff331c12010-07-25 18:17:45 +00009963 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009964 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009965}
9966
Sam Panzere1715b62012-08-21 00:52:01 +00009967/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9968/// (which eventually refers to the declaration Func) and the call
9969/// arguments Args/NumArgs, attempt to resolve the function call down
9970/// to a specific function. If overload resolution succeeds, returns
9971/// the call expression produced by overload resolution.
9972/// Otherwise, emits diagnostics and returns ExprError.
9973ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9974 UnresolvedLookupExpr *ULE,
9975 SourceLocation LParenLoc,
9976 Expr **Args, unsigned NumArgs,
9977 SourceLocation RParenLoc,
9978 Expr *ExecConfig,
9979 bool AllowTypoCorrection) {
9980 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9981 ExprResult result;
9982
9983 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9984 &CandidateSet, &result))
9985 return result;
9986
9987 OverloadCandidateSet::iterator Best;
9988 OverloadingResult OverloadResult =
9989 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9990
9991 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9992 RParenLoc, ExecConfig, &CandidateSet,
9993 &Best, OverloadResult,
9994 AllowTypoCorrection);
9995}
9996
John McCall6e266892010-01-26 03:27:55 +00009997static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009998 return Functions.size() > 1 ||
9999 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10000}
10001
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010002/// \brief Create a unary operation that may resolve to an overloaded
10003/// operator.
10004///
10005/// \param OpLoc The location of the operator itself (e.g., '*').
10006///
10007/// \param OpcIn The UnaryOperator::Opcode that describes this
10008/// operator.
10009///
James Dennett40ae6662012-06-22 08:52:37 +000010010/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010011/// considered by overload resolution. The caller needs to build this
10012/// set based on the context using, e.g.,
10013/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10014/// set should not contain any member functions; those will be added
10015/// by CreateOverloadedUnaryOp().
10016///
James Dennett8da16872012-06-22 10:32:46 +000010017/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010018ExprResult
John McCall6e266892010-01-26 03:27:55 +000010019Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10020 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010021 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010022 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010023
10024 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10025 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10026 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010027 // TODO: provide better source location info.
10028 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010029
John McCall5acb0c92011-10-17 18:40:02 +000010030 if (checkPlaceholderForOverload(*this, Input))
10031 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010032
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010033 Expr *Args[2] = { Input, 0 };
10034 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010035
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010036 // For post-increment and post-decrement, add the implicit '0' as
10037 // the second argument, so that we know this is a post-increment or
10038 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010039 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010040 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010041 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10042 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010043 NumArgs = 2;
10044 }
10045
10046 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010047 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010048 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010049 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010050 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010051 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010052 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010053
John McCallc373d482010-01-27 01:50:18 +000010054 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010055 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010056 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010057 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010058 /*ADL*/ true, IsOverloaded(Fns),
10059 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010060 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010061 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010062 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010063 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010064 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010065 }
10066
10067 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010068 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010069
10070 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010071 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10072 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010073
10074 // Add operator candidates that are member functions.
10075 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10076
John McCall6e266892010-01-26 03:27:55 +000010077 // Add candidates from ADL.
10078 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010079 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010080 /*ExplicitTemplateArgs*/ 0,
10081 CandidateSet);
10082
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010083 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010084 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010085
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010086 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10087
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010088 // Perform overload resolution.
10089 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010090 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010091 case OR_Success: {
10092 // We found a built-in operator or an overloaded operator.
10093 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010094
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010095 if (FnDecl) {
10096 // We matched an overloaded operator. Build a call to that
10097 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010098
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010099 // Convert the arguments.
10100 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010101 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010102
John Wiegley429bb272011-04-08 18:41:53 +000010103 ExprResult InputRes =
10104 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10105 Best->FoundDecl, Method);
10106 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010107 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010108 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010109 } else {
10110 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010111 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010112 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010113 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010114 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010115 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010116 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010117 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010118 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010119 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010120 }
10121
John McCallf89e55a2010-11-18 06:31:45 +000010122 // Determine the result type.
10123 QualType ResultTy = FnDecl->getResultType();
10124 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10125 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010126
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010127 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010128 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010129 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010130 if (FnExpr.isInvalid())
10131 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010132
Eli Friedman4c3b8962009-11-18 03:58:17 +000010133 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010134 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010135 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010136 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010137 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010138
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010139 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010140 FnDecl))
10141 return ExprError();
10142
John McCall9ae2f072010-08-23 23:25:46 +000010143 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010144 } else {
10145 // We matched a built-in operator. Convert the arguments, then
10146 // break out so that we will build the appropriate built-in
10147 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010148 ExprResult InputRes =
10149 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10150 Best->Conversions[0], AA_Passing);
10151 if (InputRes.isInvalid())
10152 return ExprError();
10153 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010154 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010155 }
John Wiegley429bb272011-04-08 18:41:53 +000010156 }
10157
10158 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010159 // This is an erroneous use of an operator which can be overloaded by
10160 // a non-member function. Check for non-member operators which were
10161 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010162 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10163 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010164 // FIXME: Recover by calling the found function.
10165 return ExprError();
10166
John Wiegley429bb272011-04-08 18:41:53 +000010167 // No viable function; fall through to handling this as a
10168 // built-in operator, which will produce an error message for us.
10169 break;
10170
10171 case OR_Ambiguous:
10172 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10173 << UnaryOperator::getOpcodeStr(Opc)
10174 << Input->getType()
10175 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010176 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10177 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010178 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10179 return ExprError();
10180
10181 case OR_Deleted:
10182 Diag(OpLoc, diag::err_ovl_deleted_oper)
10183 << Best->Function->isDeleted()
10184 << UnaryOperator::getOpcodeStr(Opc)
10185 << getDeletedOrUnavailableSuffix(Best->Function)
10186 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010187 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10188 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010189 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010190 return ExprError();
10191 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010192
10193 // Either we found no viable overloaded operator or we matched a
10194 // built-in operator. In either case, fall through to trying to
10195 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010196 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010197}
10198
Douglas Gregor063daf62009-03-13 18:40:31 +000010199/// \brief Create a binary operation that may resolve to an overloaded
10200/// operator.
10201///
10202/// \param OpLoc The location of the operator itself (e.g., '+').
10203///
10204/// \param OpcIn The BinaryOperator::Opcode that describes this
10205/// operator.
10206///
James Dennett40ae6662012-06-22 08:52:37 +000010207/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010208/// considered by overload resolution. The caller needs to build this
10209/// set based on the context using, e.g.,
10210/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10211/// set should not contain any member functions; those will be added
10212/// by CreateOverloadedBinOp().
10213///
10214/// \param LHS Left-hand argument.
10215/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010216ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010217Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010218 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010219 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010220 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010221 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010222 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010223
10224 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10225 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10226 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10227
10228 // If either side is type-dependent, create an appropriate dependent
10229 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010230 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010231 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010232 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010233 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010234 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010235 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010236 Context.DependentTy,
10237 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010238 OpLoc,
10239 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010240
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010241 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10242 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010243 VK_LValue,
10244 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010245 Context.DependentTy,
10246 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010247 OpLoc,
10248 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010249 }
John McCall6e266892010-01-26 03:27:55 +000010250
10251 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010252 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010253 // TODO: provide better source location info in DNLoc component.
10254 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010255 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010256 = UnresolvedLookupExpr::Create(Context, NamingClass,
10257 NestedNameSpecifierLoc(), OpNameInfo,
10258 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010259 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010260 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10261 Context.DependentTy, VK_RValue,
10262 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010263 }
10264
John McCall5acb0c92011-10-17 18:40:02 +000010265 // Always do placeholder-like conversions on the RHS.
10266 if (checkPlaceholderForOverload(*this, Args[1]))
10267 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010268
John McCall3c3b7f92011-10-25 17:37:35 +000010269 // Do placeholder-like conversion on the LHS; note that we should
10270 // not get here with a PseudoObject LHS.
10271 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010272 if (checkPlaceholderForOverload(*this, Args[0]))
10273 return ExprError();
10274
Sebastian Redl275c2b42009-11-18 23:10:33 +000010275 // If this is the assignment operator, we only perform overload resolution
10276 // if the left-hand side is a class or enumeration type. This is actually
10277 // a hack. The standard requires that we do overload resolution between the
10278 // various built-in candidates, but as DR507 points out, this can lead to
10279 // problems. So we do it this way, which pretty much follows what GCC does.
10280 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010281 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010282 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010283
John McCall0e800c92010-12-04 08:14:53 +000010284 // If this is the .* operator, which is not overloadable, just
10285 // create a built-in binary operator.
10286 if (Opc == BO_PtrMemD)
10287 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10288
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010289 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010290 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010291
10292 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010293 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010294
10295 // Add operator candidates that are member functions.
10296 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10297
John McCall6e266892010-01-26 03:27:55 +000010298 // Add candidates from ADL.
10299 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010300 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010301 /*ExplicitTemplateArgs*/ 0,
10302 CandidateSet);
10303
Douglas Gregor063daf62009-03-13 18:40:31 +000010304 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010305 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010306
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010307 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10308
Douglas Gregor063daf62009-03-13 18:40:31 +000010309 // Perform overload resolution.
10310 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010311 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010312 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010313 // We found a built-in operator or an overloaded operator.
10314 FunctionDecl *FnDecl = Best->Function;
10315
10316 if (FnDecl) {
10317 // We matched an overloaded operator. Build a call to that
10318 // operator.
10319
10320 // Convert the arguments.
10321 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010322 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010323 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010324
Chandler Carruth6df868e2010-12-12 08:17:55 +000010325 ExprResult Arg1 =
10326 PerformCopyInitialization(
10327 InitializedEntity::InitializeParameter(Context,
10328 FnDecl->getParamDecl(0)),
10329 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010330 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010331 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010332
John Wiegley429bb272011-04-08 18:41:53 +000010333 ExprResult Arg0 =
10334 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10335 Best->FoundDecl, Method);
10336 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010337 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010338 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010339 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010340 } else {
10341 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010342 ExprResult Arg0 = PerformCopyInitialization(
10343 InitializedEntity::InitializeParameter(Context,
10344 FnDecl->getParamDecl(0)),
10345 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010346 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010347 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010348
Chandler Carruth6df868e2010-12-12 08:17:55 +000010349 ExprResult Arg1 =
10350 PerformCopyInitialization(
10351 InitializedEntity::InitializeParameter(Context,
10352 FnDecl->getParamDecl(1)),
10353 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010354 if (Arg1.isInvalid())
10355 return ExprError();
10356 Args[0] = LHS = Arg0.takeAs<Expr>();
10357 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010358 }
10359
John McCallf89e55a2010-11-18 06:31:45 +000010360 // Determine the result type.
10361 QualType ResultTy = FnDecl->getResultType();
10362 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10363 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010364
10365 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010366 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010367 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010368 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010369 if (FnExpr.isInvalid())
10370 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010371
John McCall9ae2f072010-08-23 23:25:46 +000010372 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010373 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010374 Args, ResultTy, VK, OpLoc,
10375 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010376
10377 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010378 FnDecl))
10379 return ExprError();
10380
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010381 ArrayRef<const Expr *> ArgsArray(Args, 2);
10382 // Cut off the implicit 'this'.
10383 if (isa<CXXMethodDecl>(FnDecl))
10384 ArgsArray = ArgsArray.slice(1);
10385 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10386 TheCall->getSourceRange(), VariadicDoesNotApply);
10387
John McCall9ae2f072010-08-23 23:25:46 +000010388 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010389 } else {
10390 // We matched a built-in operator. Convert the arguments, then
10391 // break out so that we will build the appropriate built-in
10392 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010393 ExprResult ArgsRes0 =
10394 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10395 Best->Conversions[0], AA_Passing);
10396 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010397 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010398 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010399
John Wiegley429bb272011-04-08 18:41:53 +000010400 ExprResult ArgsRes1 =
10401 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10402 Best->Conversions[1], AA_Passing);
10403 if (ArgsRes1.isInvalid())
10404 return ExprError();
10405 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010406 break;
10407 }
10408 }
10409
Douglas Gregor33074752009-09-30 21:46:01 +000010410 case OR_No_Viable_Function: {
10411 // C++ [over.match.oper]p9:
10412 // If the operator is the operator , [...] and there are no
10413 // viable functions, then the operator is assumed to be the
10414 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010415 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010416 break;
10417
Chandler Carruth6df868e2010-12-12 08:17:55 +000010418 // For class as left operand for assignment or compound assigment
10419 // operator do not fall through to handling in built-in, but report that
10420 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010421 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010422 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010423 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010424 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10425 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010426 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010427 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010428 // This is an erroneous use of an operator which can be overloaded by
10429 // a non-member function. Check for non-member operators which were
10430 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010431 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010432 // FIXME: Recover by calling the found function.
10433 return ExprError();
10434
Douglas Gregor33074752009-09-30 21:46:01 +000010435 // No viable function; try to create a built-in operation, which will
10436 // produce an error. Then, show the non-viable candidates.
10437 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010438 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010439 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010440 "C++ binary operator overloading is missing candidates!");
10441 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010442 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010443 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010444 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010445 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010446
10447 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010448 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010449 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010450 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010452 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010453 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010454 return ExprError();
10455
10456 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010457 if (isImplicitlyDeleted(Best->Function)) {
10458 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10459 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010460 << Context.getRecordType(Method->getParent())
10461 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010462
Richard Smith0f46e642012-12-28 12:23:24 +000010463 // The user probably meant to call this special member. Just
10464 // explain why it's deleted.
10465 NoteDeletedFunction(Method);
10466 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010467 } else {
10468 Diag(OpLoc, diag::err_ovl_deleted_oper)
10469 << Best->Function->isDeleted()
10470 << BinaryOperator::getOpcodeStr(Opc)
10471 << getDeletedOrUnavailableSuffix(Best->Function)
10472 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10473 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010474 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010475 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010476 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010477 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010478
Douglas Gregor33074752009-09-30 21:46:01 +000010479 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010480 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010481}
10482
John McCall60d7b3a2010-08-24 06:29:42 +000010483ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010484Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10485 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010486 Expr *Base, Expr *Idx) {
10487 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010488 DeclarationName OpName =
10489 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10490
10491 // If either side is type-dependent, create an appropriate dependent
10492 // expression.
10493 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10494
John McCallc373d482010-01-27 01:50:18 +000010495 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010496 // CHECKME: no 'operator' keyword?
10497 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10498 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010499 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010500 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010501 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010502 /*ADL*/ true, /*Overloaded*/ false,
10503 UnresolvedSetIterator(),
10504 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010505 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010506
Sebastian Redlf322ed62009-10-29 20:17:01 +000010507 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010508 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010509 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010510 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010511 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010512 }
10513
John McCall5acb0c92011-10-17 18:40:02 +000010514 // Handle placeholders on both operands.
10515 if (checkPlaceholderForOverload(*this, Args[0]))
10516 return ExprError();
10517 if (checkPlaceholderForOverload(*this, Args[1]))
10518 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010519
Sebastian Redlf322ed62009-10-29 20:17:01 +000010520 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010521 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010522
10523 // Subscript can only be overloaded as a member function.
10524
10525 // Add operator candidates that are member functions.
10526 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10527
10528 // Add builtin operator candidates.
10529 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10530
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010531 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10532
Sebastian Redlf322ed62009-10-29 20:17:01 +000010533 // Perform overload resolution.
10534 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010535 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010536 case OR_Success: {
10537 // We found a built-in operator or an overloaded operator.
10538 FunctionDecl *FnDecl = Best->Function;
10539
10540 if (FnDecl) {
10541 // We matched an overloaded operator. Build a call to that
10542 // operator.
10543
John McCall9aa472c2010-03-19 07:35:19 +000010544 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010545
Sebastian Redlf322ed62009-10-29 20:17:01 +000010546 // Convert the arguments.
10547 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010548 ExprResult Arg0 =
10549 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10550 Best->FoundDecl, Method);
10551 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010552 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010553 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010554
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010555 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010556 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010557 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010558 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010559 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010560 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010561 Owned(Args[1]));
10562 if (InputInit.isInvalid())
10563 return ExprError();
10564
10565 Args[1] = InputInit.takeAs<Expr>();
10566
Sebastian Redlf322ed62009-10-29 20:17:01 +000010567 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010568 QualType ResultTy = FnDecl->getResultType();
10569 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10570 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010571
10572 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010573 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10574 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010575 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010576 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010577 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010578 OpLocInfo.getLoc(),
10579 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010580 if (FnExpr.isInvalid())
10581 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010582
John McCall9ae2f072010-08-23 23:25:46 +000010583 CXXOperatorCallExpr *TheCall =
10584 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010585 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010586 ResultTy, VK, RLoc,
10587 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010588
John McCall9ae2f072010-08-23 23:25:46 +000010589 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010590 FnDecl))
10591 return ExprError();
10592
John McCall9ae2f072010-08-23 23:25:46 +000010593 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010594 } else {
10595 // We matched a built-in operator. Convert the arguments, then
10596 // break out so that we will build the appropriate built-in
10597 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010598 ExprResult ArgsRes0 =
10599 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10600 Best->Conversions[0], AA_Passing);
10601 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010602 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010603 Args[0] = ArgsRes0.take();
10604
10605 ExprResult ArgsRes1 =
10606 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10607 Best->Conversions[1], AA_Passing);
10608 if (ArgsRes1.isInvalid())
10609 return ExprError();
10610 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010611
10612 break;
10613 }
10614 }
10615
10616 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010617 if (CandidateSet.empty())
10618 Diag(LLoc, diag::err_ovl_no_oper)
10619 << Args[0]->getType() << /*subscript*/ 0
10620 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10621 else
10622 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10623 << Args[0]->getType()
10624 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010625 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010626 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010627 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010628 }
10629
10630 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010631 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010632 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010633 << Args[0]->getType() << Args[1]->getType()
10634 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010635 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010636 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010637 return ExprError();
10638
10639 case OR_Deleted:
10640 Diag(LLoc, diag::err_ovl_deleted_oper)
10641 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010642 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010643 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010644 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010645 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010646 return ExprError();
10647 }
10648
10649 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010650 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010651}
10652
Douglas Gregor88a35142008-12-22 05:46:06 +000010653/// BuildCallToMemberFunction - Build a call to a member
10654/// function. MemExpr is the expression that refers to the member
10655/// function (and includes the object parameter), Args/NumArgs are the
10656/// arguments to the function call (not including the object
10657/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010658/// expression refers to a non-static member function or an overloaded
10659/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010660ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010661Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10662 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010663 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010664 assert(MemExprE->getType() == Context.BoundMemberTy ||
10665 MemExprE->getType() == Context.OverloadTy);
10666
Douglas Gregor88a35142008-12-22 05:46:06 +000010667 // Dig out the member expression. This holds both the object
10668 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010669 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010670
John McCall864c0412011-04-26 20:42:42 +000010671 // Determine whether this is a call to a pointer-to-member function.
10672 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10673 assert(op->getType() == Context.BoundMemberTy);
10674 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10675
10676 QualType fnType =
10677 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10678
10679 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10680 QualType resultType = proto->getCallResultType(Context);
10681 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10682
10683 // Check that the object type isn't more qualified than the
10684 // member function we're calling.
10685 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10686
10687 QualType objectType = op->getLHS()->getType();
10688 if (op->getOpcode() == BO_PtrMemI)
10689 objectType = objectType->castAs<PointerType>()->getPointeeType();
10690 Qualifiers objectQuals = objectType.getQualifiers();
10691
10692 Qualifiers difference = objectQuals - funcQuals;
10693 difference.removeObjCGCAttr();
10694 difference.removeAddressSpace();
10695 if (difference) {
10696 std::string qualsString = difference.getAsString();
10697 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10698 << fnType.getUnqualifiedType()
10699 << qualsString
10700 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10701 }
10702
10703 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010704 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10705 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010706 resultType, valueKind, RParenLoc);
10707
10708 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010709 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010710 call, 0))
10711 return ExprError();
10712
10713 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10714 return ExprError();
10715
10716 return MaybeBindToTemporary(call);
10717 }
10718
John McCall5acb0c92011-10-17 18:40:02 +000010719 UnbridgedCastsSet UnbridgedCasts;
10720 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10721 return ExprError();
10722
John McCall129e2df2009-11-30 22:42:35 +000010723 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010724 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010725 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010726 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010727 if (isa<MemberExpr>(NakedMemExpr)) {
10728 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010729 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010730 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010731 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010732 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010733 } else {
10734 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010735 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010736
John McCall701c89e2009-12-03 04:06:58 +000010737 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010738 Expr::Classification ObjectClassification
10739 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10740 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010741
Douglas Gregor88a35142008-12-22 05:46:06 +000010742 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010743 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010744
John McCallaa81e162009-12-01 22:10:20 +000010745 // FIXME: avoid copy.
10746 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10747 if (UnresExpr->hasExplicitTemplateArgs()) {
10748 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10749 TemplateArgs = &TemplateArgsBuffer;
10750 }
10751
John McCall129e2df2009-11-30 22:42:35 +000010752 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10753 E = UnresExpr->decls_end(); I != E; ++I) {
10754
John McCall701c89e2009-12-03 04:06:58 +000010755 NamedDecl *Func = *I;
10756 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10757 if (isa<UsingShadowDecl>(Func))
10758 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10759
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010760
Francois Pichetdbee3412011-01-18 05:04:39 +000010761 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010762 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010763 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10764 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010765 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010766 // If explicit template arguments were provided, we can't call a
10767 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010768 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010769 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010770
John McCall9aa472c2010-03-19 07:35:19 +000010771 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010772 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010773 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010774 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010775 } else {
John McCall129e2df2009-11-30 22:42:35 +000010776 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010777 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010778 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010779 llvm::makeArrayRef(Args, NumArgs),
10780 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010781 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010782 }
Douglas Gregordec06662009-08-21 18:42:58 +000010783 }
Mike Stump1eb44332009-09-09 15:08:12 +000010784
John McCall129e2df2009-11-30 22:42:35 +000010785 DeclarationName DeclName = UnresExpr->getMemberName();
10786
John McCall5acb0c92011-10-17 18:40:02 +000010787 UnbridgedCasts.restore();
10788
Douglas Gregor88a35142008-12-22 05:46:06 +000010789 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010790 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010791 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010792 case OR_Success:
10793 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010794 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010795 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010796 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010797 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010798 break;
10799
10800 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010801 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010802 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010803 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010804 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10805 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010806 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010807 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010808
10809 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010810 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010811 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010812 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10813 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010814 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010815 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010816
10817 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010818 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010819 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010820 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010821 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010822 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10824 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010825 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010826 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010827 }
10828
John McCall6bb80172010-03-30 21:47:33 +000010829 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010830
John McCallaa81e162009-12-01 22:10:20 +000010831 // If overload resolution picked a static member, build a
10832 // non-member call based on that function.
10833 if (Method->isStatic()) {
10834 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10835 Args, NumArgs, RParenLoc);
10836 }
10837
John McCall129e2df2009-11-30 22:42:35 +000010838 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010839 }
10840
John McCallf89e55a2010-11-18 06:31:45 +000010841 QualType ResultType = Method->getResultType();
10842 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10843 ResultType = ResultType.getNonLValueExprType(Context);
10844
Douglas Gregor88a35142008-12-22 05:46:06 +000010845 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010846 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010847 new (Context) CXXMemberCallExpr(Context, MemExprE,
10848 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010849 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010850
Anders Carlssoneed3e692009-10-10 00:06:20 +000010851 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010852 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010853 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010854 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010855
Douglas Gregor88a35142008-12-22 05:46:06 +000010856 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010857 // We only need to do this if there was actually an overload; otherwise
10858 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010859 if (!Method->isStatic()) {
10860 ExprResult ObjectArg =
10861 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10862 FoundDecl, Method);
10863 if (ObjectArg.isInvalid())
10864 return ExprError();
10865 MemExpr->setBase(ObjectArg.take());
10866 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010867
10868 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010869 const FunctionProtoType *Proto =
10870 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010871 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010872 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010873 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010874
Eli Friedmane61eb042012-02-18 04:48:30 +000010875 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10876
Richard Smith831421f2012-06-25 20:30:08 +000010877 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010878 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010879
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010880 if ((isa<CXXConstructorDecl>(CurContext) ||
10881 isa<CXXDestructorDecl>(CurContext)) &&
10882 TheCall->getMethodDecl()->isPure()) {
10883 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10884
Chandler Carruthae198062011-06-27 08:31:58 +000010885 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010886 Diag(MemExpr->getLocStart(),
10887 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10888 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10889 << MD->getParent()->getDeclName();
10890
10891 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010892 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010893 }
John McCall9ae2f072010-08-23 23:25:46 +000010894 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010895}
10896
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010897/// BuildCallToObjectOfClassType - Build a call to an object of class
10898/// type (C++ [over.call.object]), which can end up invoking an
10899/// overloaded function call operator (@c operator()) or performing a
10900/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010901ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010902Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010903 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010904 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010905 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010906 if (checkPlaceholderForOverload(*this, Obj))
10907 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010908 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010909
10910 UnbridgedCastsSet UnbridgedCasts;
10911 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10912 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010913
John Wiegley429bb272011-04-08 18:41:53 +000010914 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10915 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010916
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010917 // C++ [over.call.object]p1:
10918 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010919 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010920 // candidate functions includes at least the function call
10921 // operators of T. The function call operators of T are obtained by
10922 // ordinary lookup of the name operator() in the context of
10923 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010924 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010926
John Wiegley429bb272011-04-08 18:41:53 +000010927 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010928 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010929 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010930
John McCalla24dc2e2009-11-17 02:14:36 +000010931 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10932 LookupQualifiedName(R, Record->getDecl());
10933 R.suppressDiagnostics();
10934
Douglas Gregor593564b2009-11-15 07:48:03 +000010935 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010936 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010937 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10938 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010939 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010940 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010941
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010942 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010943 // In addition, for each (non-explicit in C++0x) conversion function
10944 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010945 //
10946 // operator conversion-type-id () cv-qualifier;
10947 //
10948 // where cv-qualifier is the same cv-qualification as, or a
10949 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010950 // denotes the type "pointer to function of (P1,...,Pn) returning
10951 // R", or the type "reference to pointer to function of
10952 // (P1,...,Pn) returning R", or the type "reference to function
10953 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010954 // is also considered as a candidate function. Similarly,
10955 // surrogate call functions are added to the set of candidate
10956 // functions for each conversion function declared in an
10957 // accessible base class provided the function is not hidden
10958 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010959 std::pair<CXXRecordDecl::conversion_iterator,
10960 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010961 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010962 for (CXXRecordDecl::conversion_iterator
10963 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010964 NamedDecl *D = *I;
10965 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10966 if (isa<UsingShadowDecl>(D))
10967 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010968
Douglas Gregor4a27d702009-10-21 06:18:39 +000010969 // Skip over templated conversion functions; they aren't
10970 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010971 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010972 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010973
John McCall701c89e2009-12-03 04:06:58 +000010974 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010975 if (!Conv->isExplicit()) {
10976 // Strip the reference type (if any) and then the pointer type (if
10977 // any) to get down to what might be a function type.
10978 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10979 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10980 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010981
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010982 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10983 {
10984 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010985 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10986 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010987 }
10988 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010989 }
Mike Stump1eb44332009-09-09 15:08:12 +000010990
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010991 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10992
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010993 // Perform overload resolution.
10994 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010995 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010996 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010997 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010998 // Overload resolution succeeded; we'll build the appropriate call
10999 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011000 break;
11001
11002 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011003 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011004 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011005 << Object.get()->getType() << /*call*/ 1
11006 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011007 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011008 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011009 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011010 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011011 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11012 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011013 break;
11014
11015 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011016 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011017 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011018 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011019 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11020 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011021 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011022
11023 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011024 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011025 diag::err_ovl_deleted_object_call)
11026 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011027 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011028 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011029 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011030 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11031 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011032 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011033 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011034
Douglas Gregorff331c12010-07-25 18:17:45 +000011035 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011036 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011037
John McCall5acb0c92011-10-17 18:40:02 +000011038 UnbridgedCasts.restore();
11039
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011040 if (Best->Function == 0) {
11041 // Since there is no function declaration, this is one of the
11042 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011043 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011044 = cast<CXXConversionDecl>(
11045 Best->Conversions[0].UserDefined.ConversionFunction);
11046
John Wiegley429bb272011-04-08 18:41:53 +000011047 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011048 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011049
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011050 // We selected one of the surrogate functions that converts the
11051 // object parameter to a function pointer. Perform the conversion
11052 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011053
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011054 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011055 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011056 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11057 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011058 if (Call.isInvalid())
11059 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011060 // Record usage of conversion in an implicit cast.
11061 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11062 CK_UserDefinedConversion,
11063 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011064
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011065 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011066 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011067 }
11068
John Wiegley429bb272011-04-08 18:41:53 +000011069 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011070
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011071 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11072 // that calls this method, using Object for the implicit object
11073 // parameter and passing along the remaining arguments.
11074 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011075
11076 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011077 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011078 return ExprError();
11079
Chandler Carruth6df868e2010-12-12 08:17:55 +000011080 const FunctionProtoType *Proto =
11081 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011082
11083 unsigned NumArgsInProto = Proto->getNumArgs();
11084 unsigned NumArgsToCheck = NumArgs;
11085
11086 // Build the full argument list for the method call (the
11087 // implicit object parameter is placed at the beginning of the
11088 // list).
11089 Expr **MethodArgs;
11090 if (NumArgs < NumArgsInProto) {
11091 NumArgsToCheck = NumArgsInProto;
11092 MethodArgs = new Expr*[NumArgsInProto + 1];
11093 } else {
11094 MethodArgs = new Expr*[NumArgs + 1];
11095 }
John Wiegley429bb272011-04-08 18:41:53 +000011096 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011097 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11098 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011099
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011100 DeclarationNameInfo OpLocInfo(
11101 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11102 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011103 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011104 HadMultipleCandidates,
11105 OpLocInfo.getLoc(),
11106 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011107 if (NewFn.isInvalid())
11108 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011109
11110 // Once we've built TheCall, all of the expressions are properly
11111 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011112 QualType ResultTy = Method->getResultType();
11113 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11114 ResultTy = ResultTy.getNonLValueExprType(Context);
11115
John McCall9ae2f072010-08-23 23:25:46 +000011116 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011117 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011118 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011119 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011120 delete [] MethodArgs;
11121
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011122 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011123 Method))
11124 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011125
Douglas Gregor518fda12009-01-13 05:10:00 +000011126 // We may have default arguments. If so, we need to allocate more
11127 // slots in the call for them.
11128 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011129 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011130 else if (NumArgs > NumArgsInProto)
11131 NumArgsToCheck = NumArgsInProto;
11132
Chris Lattner312531a2009-04-12 08:11:20 +000011133 bool IsError = false;
11134
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011135 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011136 ExprResult ObjRes =
11137 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11138 Best->FoundDecl, Method);
11139 if (ObjRes.isInvalid())
11140 IsError = true;
11141 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011142 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011143 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011144
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011145 // Check the argument types.
11146 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011147 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011148 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011149 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011150
Douglas Gregor518fda12009-01-13 05:10:00 +000011151 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011152
John McCall60d7b3a2010-08-24 06:29:42 +000011153 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011154 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011155 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011156 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011157 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011158
Anders Carlsson3faa4862010-01-29 18:43:53 +000011159 IsError |= InputInit.isInvalid();
11160 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011161 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011162 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011163 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11164 if (DefArg.isInvalid()) {
11165 IsError = true;
11166 break;
11167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011168
Douglas Gregord47c47d2009-11-09 19:27:57 +000011169 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011170 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011171
11172 TheCall->setArg(i + 1, Arg);
11173 }
11174
11175 // If this is a variadic call, handle args passed through "...".
11176 if (Proto->isVariadic()) {
11177 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011178 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011179 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11180 IsError |= Arg.isInvalid();
11181 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011182 }
11183 }
11184
Chris Lattner312531a2009-04-12 08:11:20 +000011185 if (IsError) return true;
11186
Eli Friedmane61eb042012-02-18 04:48:30 +000011187 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11188
Richard Smith831421f2012-06-25 20:30:08 +000011189 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011190 return true;
11191
John McCall182f7092010-08-24 06:09:16 +000011192 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011193}
11194
Douglas Gregor8ba10742008-11-20 16:27:02 +000011195/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011196/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011197/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011198ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011199Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011200 assert(Base->getType()->isRecordType() &&
11201 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011202
John McCall5acb0c92011-10-17 18:40:02 +000011203 if (checkPlaceholderForOverload(*this, Base))
11204 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011205
John McCall5769d612010-02-08 23:07:23 +000011206 SourceLocation Loc = Base->getExprLoc();
11207
Douglas Gregor8ba10742008-11-20 16:27:02 +000011208 // C++ [over.ref]p1:
11209 //
11210 // [...] An expression x->m is interpreted as (x.operator->())->m
11211 // for a class object x of type T if T::operator->() exists and if
11212 // the operator is selected as the best match function by the
11213 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011214 DeclarationName OpName =
11215 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011216 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011217 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011218
John McCall5769d612010-02-08 23:07:23 +000011219 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011220 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011221 return ExprError();
11222
John McCalla24dc2e2009-11-17 02:14:36 +000011223 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11224 LookupQualifiedName(R, BaseRecord->getDecl());
11225 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011226
11227 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011228 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011229 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11230 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011231 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011232
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011233 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11234
Douglas Gregor8ba10742008-11-20 16:27:02 +000011235 // Perform overload resolution.
11236 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011237 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011238 case OR_Success:
11239 // Overload resolution succeeded; we'll build the call below.
11240 break;
11241
11242 case OR_No_Viable_Function:
11243 if (CandidateSet.empty())
11244 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011245 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011246 else
11247 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011248 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011249 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011250 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011251
11252 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011253 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11254 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011255 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011256 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011257
11258 case OR_Deleted:
11259 Diag(OpLoc, diag::err_ovl_deleted_oper)
11260 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011261 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011262 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011263 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011265 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011266 }
11267
John McCall9aa472c2010-03-19 07:35:19 +000011268 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11269
Douglas Gregor8ba10742008-11-20 16:27:02 +000011270 // Convert the object parameter.
11271 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011272 ExprResult BaseResult =
11273 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11274 Best->FoundDecl, Method);
11275 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011276 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011277 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011278
Douglas Gregor8ba10742008-11-20 16:27:02 +000011279 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011280 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011281 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011282 if (FnExpr.isInvalid())
11283 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011284
John McCallf89e55a2010-11-18 06:31:45 +000011285 QualType ResultTy = Method->getResultType();
11286 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11287 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011288 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011289 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011290 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011291
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011292 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011293 Method))
11294 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011295
11296 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011297}
11298
Richard Smith36f5cfe2012-03-09 08:00:36 +000011299/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11300/// a literal operator described by the provided lookup results.
11301ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11302 DeclarationNameInfo &SuffixInfo,
11303 ArrayRef<Expr*> Args,
11304 SourceLocation LitEndLoc,
11305 TemplateArgumentListInfo *TemplateArgs) {
11306 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011307
Richard Smith36f5cfe2012-03-09 08:00:36 +000011308 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11309 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11310 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011311
Richard Smith36f5cfe2012-03-09 08:00:36 +000011312 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11313
Richard Smith36f5cfe2012-03-09 08:00:36 +000011314 // Perform overload resolution. This will usually be trivial, but might need
11315 // to perform substitutions for a literal operator template.
11316 OverloadCandidateSet::iterator Best;
11317 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11318 case OR_Success:
11319 case OR_Deleted:
11320 break;
11321
11322 case OR_No_Viable_Function:
11323 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11324 << R.getLookupName();
11325 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11326 return ExprError();
11327
11328 case OR_Ambiguous:
11329 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11330 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11331 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011332 }
11333
Richard Smith36f5cfe2012-03-09 08:00:36 +000011334 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011335 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11336 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011337 SuffixInfo.getLoc(),
11338 SuffixInfo.getInfo());
11339 if (Fn.isInvalid())
11340 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011341
11342 // Check the argument types. This should almost always be a no-op, except
11343 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011344 Expr *ConvArgs[2];
11345 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11346 ExprResult InputInit = PerformCopyInitialization(
11347 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11348 SourceLocation(), Args[ArgIdx]);
11349 if (InputInit.isInvalid())
11350 return true;
11351 ConvArgs[ArgIdx] = InputInit.take();
11352 }
11353
Richard Smith9fcce652012-03-07 08:35:16 +000011354 QualType ResultTy = FD->getResultType();
11355 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11356 ResultTy = ResultTy.getNonLValueExprType(Context);
11357
Richard Smith9fcce652012-03-07 08:35:16 +000011358 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011359 new (Context) UserDefinedLiteral(Context, Fn.take(),
11360 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011361 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11362
11363 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11364 return ExprError();
11365
Richard Smith831421f2012-06-25 20:30:08 +000011366 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011367 return ExprError();
11368
11369 return MaybeBindToTemporary(UDL);
11370}
11371
Sam Panzere1715b62012-08-21 00:52:01 +000011372/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11373/// given LookupResult is non-empty, it is assumed to describe a member which
11374/// will be invoked. Otherwise, the function will be found via argument
11375/// dependent lookup.
11376/// CallExpr is set to a valid expression and FRS_Success returned on success,
11377/// otherwise CallExpr is set to ExprError() and some non-success value
11378/// is returned.
11379Sema::ForRangeStatus
11380Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11381 SourceLocation RangeLoc, VarDecl *Decl,
11382 BeginEndFunction BEF,
11383 const DeclarationNameInfo &NameInfo,
11384 LookupResult &MemberLookup,
11385 OverloadCandidateSet *CandidateSet,
11386 Expr *Range, ExprResult *CallExpr) {
11387 CandidateSet->clear();
11388 if (!MemberLookup.empty()) {
11389 ExprResult MemberRef =
11390 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11391 /*IsPtr=*/false, CXXScopeSpec(),
11392 /*TemplateKWLoc=*/SourceLocation(),
11393 /*FirstQualifierInScope=*/0,
11394 MemberLookup,
11395 /*TemplateArgs=*/0);
11396 if (MemberRef.isInvalid()) {
11397 *CallExpr = ExprError();
11398 Diag(Range->getLocStart(), diag::note_in_for_range)
11399 << RangeLoc << BEF << Range->getType();
11400 return FRS_DiagnosticIssued;
11401 }
11402 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11403 if (CallExpr->isInvalid()) {
11404 *CallExpr = ExprError();
11405 Diag(Range->getLocStart(), diag::note_in_for_range)
11406 << RangeLoc << BEF << Range->getType();
11407 return FRS_DiagnosticIssued;
11408 }
11409 } else {
11410 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011411 UnresolvedLookupExpr *Fn =
11412 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11413 NestedNameSpecifierLoc(), NameInfo,
11414 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011415 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011416
11417 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11418 CandidateSet, CallExpr);
11419 if (CandidateSet->empty() || CandidateSetError) {
11420 *CallExpr = ExprError();
11421 return FRS_NoViableFunction;
11422 }
11423 OverloadCandidateSet::iterator Best;
11424 OverloadingResult OverloadResult =
11425 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11426
11427 if (OverloadResult == OR_No_Viable_Function) {
11428 *CallExpr = ExprError();
11429 return FRS_NoViableFunction;
11430 }
11431 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11432 Loc, 0, CandidateSet, &Best,
11433 OverloadResult,
11434 /*AllowTypoCorrection=*/false);
11435 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11436 *CallExpr = ExprError();
11437 Diag(Range->getLocStart(), diag::note_in_for_range)
11438 << RangeLoc << BEF << Range->getType();
11439 return FRS_DiagnosticIssued;
11440 }
11441 }
11442 return FRS_Success;
11443}
11444
11445
Douglas Gregor904eed32008-11-10 20:40:00 +000011446/// FixOverloadedFunctionReference - E is an expression that refers to
11447/// a C++ overloaded function (possibly with some parentheses and
11448/// perhaps a '&' around it). We have resolved the overloaded function
11449/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011450/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011451Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011452 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011453 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011454 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11455 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011456 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011457 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011458
Douglas Gregor699ee522009-11-20 19:42:02 +000011459 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011460 }
11461
Douglas Gregor699ee522009-11-20 19:42:02 +000011462 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011463 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11464 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011465 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011466 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011467 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011468 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011469 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011470 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011471
11472 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011473 ICE->getCastKind(),
11474 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011475 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011476 }
11477
Douglas Gregor699ee522009-11-20 19:42:02 +000011478 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011479 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011480 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11482 if (Method->isStatic()) {
11483 // Do nothing: static member functions aren't any different
11484 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011485 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011486 // Fix the sub expression, which really has to be an
11487 // UnresolvedLookupExpr holding an overloaded member function
11488 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011489 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11490 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011491 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011492 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011493
John McCallba135432009-11-21 08:51:07 +000011494 assert(isa<DeclRefExpr>(SubExpr)
11495 && "fixed to something other than a decl ref");
11496 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11497 && "fixed to a member ref with no nested name qualifier");
11498
11499 // We have taken the address of a pointer to member
11500 // function. Perform the computation here so that we get the
11501 // appropriate pointer to member type.
11502 QualType ClassType
11503 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11504 QualType MemPtrType
11505 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11506
John McCallf89e55a2010-11-18 06:31:45 +000011507 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11508 VK_RValue, OK_Ordinary,
11509 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011510 }
11511 }
John McCall6bb80172010-03-30 21:47:33 +000011512 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11513 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011514 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011515 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011516
John McCall2de56d12010-08-25 11:45:40 +000011517 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011518 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011519 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011520 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011521 }
John McCallba135432009-11-21 08:51:07 +000011522
11523 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011524 // FIXME: avoid copy.
11525 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011526 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011527 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11528 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011529 }
11530
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011531 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11532 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011533 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011534 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011535 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011536 ULE->getNameLoc(),
11537 Fn->getType(),
11538 VK_LValue,
11539 Found.getDecl(),
11540 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011541 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011542 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11543 return DRE;
John McCallba135432009-11-21 08:51:07 +000011544 }
11545
John McCall129e2df2009-11-30 22:42:35 +000011546 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011547 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011548 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11549 if (MemExpr->hasExplicitTemplateArgs()) {
11550 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11551 TemplateArgs = &TemplateArgsBuffer;
11552 }
John McCalld5532b62009-11-23 01:53:49 +000011553
John McCallaa81e162009-12-01 22:10:20 +000011554 Expr *Base;
11555
John McCallf89e55a2010-11-18 06:31:45 +000011556 // If we're filling in a static method where we used to have an
11557 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011558 if (MemExpr->isImplicitAccess()) {
11559 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011560 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11561 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011562 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011563 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011564 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011565 MemExpr->getMemberLoc(),
11566 Fn->getType(),
11567 VK_LValue,
11568 Found.getDecl(),
11569 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011570 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011571 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11572 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011573 } else {
11574 SourceLocation Loc = MemExpr->getMemberLoc();
11575 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011576 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011577 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011578 Base = new (Context) CXXThisExpr(Loc,
11579 MemExpr->getBaseType(),
11580 /*isImplicit=*/true);
11581 }
John McCallaa81e162009-12-01 22:10:20 +000011582 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011583 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011584
John McCallf5307512011-04-27 00:36:17 +000011585 ExprValueKind valueKind;
11586 QualType type;
11587 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11588 valueKind = VK_LValue;
11589 type = Fn->getType();
11590 } else {
11591 valueKind = VK_RValue;
11592 type = Context.BoundMemberTy;
11593 }
11594
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011595 MemberExpr *ME = MemberExpr::Create(Context, Base,
11596 MemExpr->isArrow(),
11597 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011598 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011599 Fn,
11600 Found,
11601 MemExpr->getMemberNameInfo(),
11602 TemplateArgs,
11603 type, valueKind, OK_Ordinary);
11604 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011605 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011606 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011607 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011608
John McCall3fa5cae2010-10-26 07:05:15 +000011609 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011610}
11611
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011612ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011613 DeclAccessPair Found,
11614 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011615 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011616}
11617
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011618} // end namespace clang