blob: 034790db20e3f8c01199012453efb9a853b1eac5 [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()){
Richard Smith82f145d2013-05-04 06:44:46 +000045 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
46 return ExprError();
47
John McCallf4b88a42012-03-10 09:33:50 +000048 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000049 VK_LValue, Loc, LocInfo);
50 if (HadMultipleCandidates)
51 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000052
53 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000054
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000055 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000056 E = S.DefaultFunctionArrayConversion(E.take());
57 if (E.isInvalid())
58 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000059 return E;
John McCallf89e55a2010-11-18 06:31:45 +000060}
61
John McCall120d63c2010-08-24 20:38:10 +000062static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
63 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000064 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000065 bool CStyle,
66 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000067
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000068static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
69 QualType &ToType,
70 bool InOverloadResolution,
71 StandardConversionSequence &SCS,
72 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000073static OverloadingResult
74IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
75 UserDefinedConversionSequence& User,
76 OverloadCandidateSet& Conversions,
77 bool AllowExplicit);
78
79
80static ImplicitConversionSequence::CompareKind
81CompareStandardConversionSequences(Sema &S,
82 const StandardConversionSequence& SCS1,
83 const StandardConversionSequence& SCS2);
84
85static ImplicitConversionSequence::CompareKind
86CompareQualificationConversions(Sema &S,
87 const StandardConversionSequence& SCS1,
88 const StandardConversionSequence& SCS2);
89
90static ImplicitConversionSequence::CompareKind
91CompareDerivedToBaseConversions(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95
96
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097/// GetConversionCategory - Retrieve the implicit conversion
98/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000099ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100GetConversionCategory(ImplicitConversionKind Kind) {
101 static const ImplicitConversionCategory
102 Category[(int)ICK_Num_Conversion_Kinds] = {
103 ICC_Identity,
104 ICC_Lvalue_Transformation,
105 ICC_Lvalue_Transformation,
106 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000107 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 ICC_Qualification_Adjustment,
109 ICC_Promotion,
110 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000111 ICC_Promotion,
112 ICC_Conversion,
113 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000114 ICC_Conversion,
115 ICC_Conversion,
116 ICC_Conversion,
117 ICC_Conversion,
118 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000119 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000120 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000121 ICC_Conversion,
122 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000123 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000124 ICC_Conversion
125 };
126 return Category[(int)Kind];
127}
128
129/// GetConversionRank - Retrieve the implicit conversion rank
130/// corresponding to the given implicit conversion kind.
131ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
132 static const ImplicitConversionRank
133 Rank[(int)ICK_Num_Conversion_Kinds] = {
134 ICR_Exact_Match,
135 ICR_Exact_Match,
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000139 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 ICR_Promotion,
141 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000142 ICR_Promotion,
143 ICR_Conversion,
144 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000150 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000151 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000152 ICR_Conversion,
153 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000154 ICR_Complex_Real_Conversion,
155 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000156 ICR_Conversion,
157 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 };
159 return Rank[(int)Kind];
160}
161
162/// GetImplicitConversionName - Return the name of this kind of
163/// implicit conversion.
164const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000165 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166 "No conversion",
167 "Lvalue-to-rvalue",
168 "Array-to-pointer",
169 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000170 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 "Qualification",
172 "Integral promotion",
173 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000174 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000175 "Integral conversion",
176 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000177 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000178 "Floating-integral conversion",
179 "Pointer conversion",
180 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000181 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000182 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000183 "Derived-to-base conversion",
184 "Vector conversion",
185 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000186 "Complex-real conversion",
187 "Block Pointer conversion",
188 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000189 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 };
191 return Name[Kind];
192}
193
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194/// StandardConversionSequence - Set the standard conversion
195/// sequence to the identity conversion.
196void StandardConversionSequence::setAsIdentityConversion() {
197 First = ICK_Identity;
198 Second = ICK_Identity;
199 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000200 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000201 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202 ReferenceBinding = false;
203 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000204 IsLvalueReference = true;
205 BindsToFunctionLvalue = false;
206 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000207 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000208 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000209 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000210}
211
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000212/// getRank - Retrieve the rank of this standard conversion sequence
213/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
214/// implicit conversions.
215ImplicitConversionRank StandardConversionSequence::getRank() const {
216 ImplicitConversionRank Rank = ICR_Exact_Match;
217 if (GetConversionRank(First) > Rank)
218 Rank = GetConversionRank(First);
219 if (GetConversionRank(Second) > Rank)
220 Rank = GetConversionRank(Second);
221 if (GetConversionRank(Third) > Rank)
222 Rank = GetConversionRank(Third);
223 return Rank;
224}
225
226/// isPointerConversionToBool - Determines whether this conversion is
227/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000228/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000230bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000231 // Note that FromType has not necessarily been transformed by the
232 // array-to-pointer or function-to-pointer implicit conversions, so
233 // check for their presence as well as checking whether FromType is
234 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000235 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000236 (getFromType()->isPointerType() ||
237 getFromType()->isObjCObjectPointerType() ||
238 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000239 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
241 return true;
242
243 return false;
244}
245
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000246/// isPointerConversionToVoidPointer - Determines whether this
247/// conversion is a conversion of a pointer to a void pointer. This is
248/// used as part of the ranking of standard conversion sequences (C++
249/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000250bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000251StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000252isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000253 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000254 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000255
256 // Note that FromType has not necessarily been transformed by the
257 // array-to-pointer implicit conversion, so check for its presence
258 // and redo the conversion to get a pointer.
259 if (First == ICK_Array_To_Pointer)
260 FromType = Context.getArrayDecayedType(FromType);
261
Douglas Gregorf9af5242011-04-15 20:45:44 +0000262 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000263 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000264 return ToPtrType->getPointeeType()->isVoidType();
265
266 return false;
267}
268
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000269/// Skip any implicit casts which could be either part of a narrowing conversion
270/// or after one in an implicit conversion.
271static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
272 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
273 switch (ICE->getCastKind()) {
274 case CK_NoOp:
275 case CK_IntegralCast:
276 case CK_IntegralToBoolean:
277 case CK_IntegralToFloating:
278 case CK_FloatingToIntegral:
279 case CK_FloatingToBoolean:
280 case CK_FloatingCast:
281 Converted = ICE->getSubExpr();
282 continue;
283
284 default:
285 return Converted;
286 }
287 }
288
289 return Converted;
290}
291
292/// Check if this standard conversion sequence represents a narrowing
293/// conversion, according to C++11 [dcl.init.list]p7.
294///
295/// \param Ctx The AST context.
296/// \param Converted The result of applying this standard conversion sequence.
297/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
298/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000299/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
300/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000301NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000302StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
303 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000304 APValue &ConstantValue,
305 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000306 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000307
308 // C++11 [dcl.init.list]p7:
309 // A narrowing conversion is an implicit conversion ...
310 QualType FromType = getToType(0);
311 QualType ToType = getToType(1);
312 switch (Second) {
313 // -- from a floating-point type to an integer type, or
314 //
315 // -- from an integer type or unscoped enumeration type to a floating-point
316 // type, except where the source is a constant expression and the actual
317 // value after conversion will fit into the target type and will produce
318 // the original value when converted back to the original type, or
319 case ICK_Floating_Integral:
320 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
321 return NK_Type_Narrowing;
322 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
323 llvm::APSInt IntConstantValue;
324 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
325 if (Initializer &&
326 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
327 // Convert the integer to the floating type.
328 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
329 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
330 llvm::APFloat::rmNearestTiesToEven);
331 // And back.
332 llvm::APSInt ConvertedValue = IntConstantValue;
333 bool ignored;
334 Result.convertToInteger(ConvertedValue,
335 llvm::APFloat::rmTowardZero, &ignored);
336 // If the resulting value is different, this was a narrowing conversion.
337 if (IntConstantValue != ConvertedValue) {
338 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000339 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000340 return NK_Constant_Narrowing;
341 }
342 } else {
343 // Variables are always narrowings.
344 return NK_Variable_Narrowing;
345 }
346 }
347 return NK_Not_Narrowing;
348
349 // -- from long double to double or float, or from double to float, except
350 // where the source is a constant expression and the actual value after
351 // conversion is within the range of values that can be represented (even
352 // if it cannot be represented exactly), or
353 case ICK_Floating_Conversion:
354 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
355 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
356 // FromType is larger than ToType.
357 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
358 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
359 // Constant!
360 assert(ConstantValue.isFloat());
361 llvm::APFloat FloatVal = ConstantValue.getFloat();
362 // Convert the source value into the target type.
363 bool ignored;
364 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
365 Ctx.getFloatTypeSemantics(ToType),
366 llvm::APFloat::rmNearestTiesToEven, &ignored);
367 // If there was no overflow, the source value is within the range of
368 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000369 if (ConvertStatus & llvm::APFloat::opOverflow) {
370 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000371 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000372 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000373 } else {
374 return NK_Variable_Narrowing;
375 }
376 }
377 return NK_Not_Narrowing;
378
379 // -- from an integer type or unscoped enumeration type to an integer type
380 // that cannot represent all the values of the original type, except where
381 // the source is a constant expression and the actual value after
382 // conversion will fit into the target type and will produce the original
383 // value when converted back to the original type.
384 case ICK_Boolean_Conversion: // Bools are integers too.
385 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
386 // Boolean conversions can be from pointers and pointers to members
387 // [conv.bool], and those aren't considered narrowing conversions.
388 return NK_Not_Narrowing;
389 } // Otherwise, fall through to the integral case.
390 case ICK_Integral_Conversion: {
391 assert(FromType->isIntegralOrUnscopedEnumerationType());
392 assert(ToType->isIntegralOrUnscopedEnumerationType());
393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394 const unsigned FromWidth = Ctx.getIntWidth(FromType);
395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396 const unsigned ToWidth = Ctx.getIntWidth(ToType);
397
398 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000399 (FromWidth == ToWidth && FromSigned != ToSigned) ||
400 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000401 // Not all values of FromType can be represented in ToType.
402 llvm::APSInt InitializerValue;
403 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405 // Such conversions on variables are always narrowing.
406 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000407 }
408 bool Narrowing = false;
409 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000410 // Negative -> unsigned is narrowing. Otherwise, more bits is never
411 // narrowing.
412 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000413 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000414 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000415 // Add a bit to the InitializerValue so we don't have to worry about
416 // signed vs. unsigned comparisons.
417 InitializerValue = InitializerValue.extend(
418 InitializerValue.getBitWidth() + 1);
419 // Convert the initializer to and from the target width and signed-ness.
420 llvm::APSInt ConvertedValue = InitializerValue;
421 ConvertedValue = ConvertedValue.trunc(ToWidth);
422 ConvertedValue.setIsSigned(ToSigned);
423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424 ConvertedValue.setIsSigned(InitializerValue.isSigned());
425 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000426 if (ConvertedValue != InitializerValue)
427 Narrowing = true;
428 }
429 if (Narrowing) {
430 ConstantType = Initializer->getType();
431 ConstantValue = APValue(InitializerValue);
432 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000433 }
434 }
435 return NK_Not_Narrowing;
436 }
437
438 default:
439 // Other kinds of conversions are not narrowings.
440 return NK_Not_Narrowing;
441 }
442}
443
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444/// DebugPrint - Print this standard conversion sequence to standard
445/// error. Useful for debugging overloading issues.
446void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000447 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448 bool PrintedSomething = false;
449 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (Second != ICK_Identity) {
455 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000459
460 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000461 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000462 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000464 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000466 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000467 PrintedSomething = true;
468 }
469
470 if (Third != ICK_Identity) {
471 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000474 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475 PrintedSomething = true;
476 }
477
478 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
481}
482
483/// DebugPrint - Print this user-defined conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 if (Before.First || Before.Second || Before.Third) {
488 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000491 if (ConversionFunction)
492 OS << '\'' << *ConversionFunction << '\'';
493 else
494 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 After.DebugPrint();
498 }
499}
500
501/// DebugPrint - Print this implicit conversion sequence to standard
502/// error. Useful for debugging overloading issues.
503void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 switch (ConversionKind) {
506 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000507 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 Standard.DebugPrint();
509 break;
510 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000511 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 UserDefined.DebugPrint();
513 break;
514 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000515 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 break;
John McCall1d318332010-01-12 00:44:57 +0000517 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000519 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000521 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000522 break;
523 }
524
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526}
527
John McCall1d318332010-01-12 00:44:57 +0000528void AmbiguousConversionSequence::construct() {
529 new (&conversions()) ConversionSet();
530}
531
532void AmbiguousConversionSequence::destruct() {
533 conversions().~ConversionSet();
534}
535
536void
537AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
538 FromTypePtr = O.FromTypePtr;
539 ToTypePtr = O.ToTypePtr;
540 new (&conversions()) ConversionSet(O.conversions());
541}
542
Douglas Gregora9333192010-05-08 17:41:32 +0000543namespace {
544 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000545 // template argument information.
546 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000547 TemplateArgument FirstArg;
548 TemplateArgument SecondArg;
549 };
Richard Smith29805ca2013-01-31 05:19:49 +0000550 // Structure used by OverloadCandidate::DeductionFailureInfo to store
551 // template parameter and template argument information.
552 struct DFIParamWithArguments : DFIArguments {
553 TemplateParameter Param;
554 };
Douglas Gregora9333192010-05-08 17:41:32 +0000555}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora9333192010-05-08 17:41:32 +0000557/// \brief Convert from Sema's representation of template deduction information
558/// to the form used in overload-candidate information.
559OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000560static MakeDeductionFailureInfo(ASTContext &Context,
561 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000562 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000563 OverloadCandidate::DeductionFailureInfo Result;
564 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000565 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000566 Result.Data = 0;
567 switch (TDK) {
568 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000569 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000570 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000571 case Sema::TDK_TooManyArguments:
572 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000573 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
Douglas Gregora9333192010-05-08 17:41:32 +0000575 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000576 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000577 Result.Data = Info.Param.getOpaqueValue();
578 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Richard Smith29805ca2013-01-31 05:19:49 +0000580 case Sema::TDK_NonDeducedMismatch: {
581 // FIXME: Should allocate from normal heap so that we can free this later.
582 DFIArguments *Saved = new (Context) DFIArguments;
583 Saved->FirstArg = Info.FirstArg;
584 Saved->SecondArg = Info.SecondArg;
585 Result.Data = Saved;
586 break;
587 }
588
Douglas Gregora9333192010-05-08 17:41:32 +0000589 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000590 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000593 Saved->Param = Info.Param;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
596 Result.Data = Saved;
597 break;
598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
Douglas Gregora9333192010-05-08 17:41:32 +0000600 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000601 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000602 if (Info.hasSFINAEDiagnostic()) {
603 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
604 SourceLocation(), PartialDiagnostic::NullDiagnostic());
605 Info.takeSFINAEDiagnostic(*Diag);
606 Result.HasDiagnostic = true;
607 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000611 Result.Data = Info.Expression;
612 break;
613
Richard Smith29805ca2013-01-31 05:19:49 +0000614 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 return Result;
619}
John McCall1d318332010-01-12 00:44:57 +0000620
Douglas Gregora9333192010-05-08 17:41:32 +0000621void OverloadCandidate::DeductionFailureInfo::Destroy() {
622 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
623 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000624 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000625 case Sema::TDK_InstantiationDepth:
626 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000627 case Sema::TDK_TooManyArguments:
628 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000629 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000630 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000631 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632
Douglas Gregora9333192010-05-08 17:41:32 +0000633 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000634 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000635 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000636 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000637 Data = 0;
638 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000639
640 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000641 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000642 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000643 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
644 Diag->~PartialDiagnosticAt();
645 HasDiagnostic = false;
646 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000647 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000649 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000650 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000651 break;
652 }
653}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654
Richard Smithb8590f32012-05-07 09:03:25 +0000655PartialDiagnosticAt *
656OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
657 if (HasDiagnostic)
658 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
659 return 0;
660}
661
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000663OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000666 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000667 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000668 case Sema::TDK_TooManyArguments:
669 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000670 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000671 case Sema::TDK_NonDeducedMismatch:
672 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000673 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000674
Douglas Gregora9333192010-05-08 17:41:32 +0000675 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000676 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000677 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000678
679 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000680 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000681 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682
Douglas Gregora9333192010-05-08 17:41:32 +0000683 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000684 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000685 break;
686 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return TemplateParameter();
689}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690
Douglas Gregorec20f462010-05-08 20:07:26 +0000691TemplateArgumentList *
692OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000694 case Sema::TDK_Success:
695 case Sema::TDK_Invalid:
696 case Sema::TDK_InstantiationDepth:
697 case Sema::TDK_TooManyArguments:
698 case Sema::TDK_TooFewArguments:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_InvalidExplicitArguments:
701 case Sema::TDK_Inconsistent:
702 case Sema::TDK_Underqualified:
703 case Sema::TDK_NonDeducedMismatch:
704 case Sema::TDK_FailedOverloadResolution:
705 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000706
Richard Smith29805ca2013-01-31 05:19:49 +0000707 case Sema::TDK_SubstitutionFailure:
708 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709
Richard Smith29805ca2013-01-31 05:19:49 +0000710 // Unhandled
711 case Sema::TDK_MiscellaneousDeductionFailure:
712 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000713 }
714
715 return 0;
716}
717
Douglas Gregora9333192010-05-08 17:41:32 +0000718const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000721 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000722 case Sema::TDK_InstantiationDepth:
723 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000724 case Sema::TDK_TooManyArguments:
725 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000726 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000727 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000728 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregora9333192010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000733 case Sema::TDK_NonDeducedMismatch:
734 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000735
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000736 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000737 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000738 break;
739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000740
Douglas Gregora9333192010-05-08 17:41:32 +0000741 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000742}
Douglas Gregora9333192010-05-08 17:41:32 +0000743
744const TemplateArgument *
745OverloadCandidate::DeductionFailureInfo::getSecondArg() {
746 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
747 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000748 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000749 case Sema::TDK_InstantiationDepth:
750 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000751 case Sema::TDK_TooManyArguments:
752 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000753 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000754 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000755 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000756 return 0;
757
Douglas Gregora9333192010-05-08 17:41:32 +0000758 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000759 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000760 case Sema::TDK_NonDeducedMismatch:
761 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000762
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000763 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000764 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000765 break;
766 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000767
Douglas Gregora9333192010-05-08 17:41:32 +0000768 return 0;
769}
770
Richard Smith0efa62f2013-01-31 04:03:12 +0000771Expr *
772OverloadCandidate::DeductionFailureInfo::getExpr() {
773 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
774 Sema::TDK_FailedOverloadResolution)
775 return static_cast<Expr*>(Data);
776
777 return 0;
778}
779
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000780void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000781 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000782 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
783 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000784 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
785 i->DeductionFailure.Destroy();
786 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000787}
788
789void OverloadCandidateSet::clear() {
790 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000791 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000792 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000793 Functions.clear();
794}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795
John McCall5acb0c92011-10-17 18:40:02 +0000796namespace {
797 class UnbridgedCastsSet {
798 struct Entry {
799 Expr **Addr;
800 Expr *Saved;
801 };
802 SmallVector<Entry, 2> Entries;
803
804 public:
805 void save(Sema &S, Expr *&E) {
806 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
807 Entry entry = { &E, E };
808 Entries.push_back(entry);
809 E = S.stripARCUnbridgedCast(E);
810 }
811
812 void restore() {
813 for (SmallVectorImpl<Entry>::iterator
814 i = Entries.begin(), e = Entries.end(); i != e; ++i)
815 *i->Addr = i->Saved;
816 }
817 };
818}
819
820/// checkPlaceholderForOverload - Do any interesting placeholder-like
821/// preprocessing on the given expression.
822///
823/// \param unbridgedCasts a collection to which to add unbridged casts;
824/// without this, they will be immediately diagnosed as errors
825///
826/// Return true on unrecoverable error.
827static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
828 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000829 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
830 // We can't handle overloaded expressions here because overload
831 // resolution might reasonably tweak them.
832 if (placeholder->getKind() == BuiltinType::Overload) return false;
833
834 // If the context potentially accepts unbridged ARC casts, strip
835 // the unbridged cast and add it to the collection for later restoration.
836 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
837 unbridgedCasts) {
838 unbridgedCasts->save(S, E);
839 return false;
840 }
841
842 // Go ahead and check everything else.
843 ExprResult result = S.CheckPlaceholderExpr(E);
844 if (result.isInvalid())
845 return true;
846
847 E = result.take();
848 return false;
849 }
850
851 // Nothing to do.
852 return false;
853}
854
855/// checkArgPlaceholdersForOverload - Check a set of call operands for
856/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000857static bool checkArgPlaceholdersForOverload(Sema &S,
858 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000859 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000860 for (unsigned i = 0, e = Args.size(); i != e; ++i)
861 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000862 return true;
863
864 return false;
865}
866
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000868// overload of the declarations in Old. This routine returns false if
869// New and Old cannot be overloaded, e.g., if New has the same
870// signature as some function in Old (C++ 1.3.10) or if the Old
871// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000872// it does return false, MatchedDecl will point to the decl that New
873// cannot be overloaded with. This decl may be a UsingShadowDecl on
874// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000875//
876// Example: Given the following input:
877//
878// void f(int, float); // #1
879// void f(int, int); // #2
880// int f(int, int); // #3
881//
882// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000883// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000884//
John McCall51fa86f2009-12-02 08:47:38 +0000885// When we process #2, Old contains only the FunctionDecl for #1. By
886// comparing the parameter types, we see that #1 and #2 are overloaded
887// (since they have different signatures), so this routine returns
888// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000889//
John McCall51fa86f2009-12-02 08:47:38 +0000890// When we process #3, Old is an overload set containing #1 and #2. We
891// compare the signatures of #3 to #1 (they're overloaded, so we do
892// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
893// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000894// signature), IsOverload returns false and MatchedDecl will be set to
895// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000896//
897// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
898// into a class by a using declaration. The rules for whether to hide
899// shadow declarations ignore some properties which otherwise figure
900// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000901Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000902Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
903 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000904 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000905 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000906 NamedDecl *OldD = *I;
907
908 bool OldIsUsingDecl = false;
909 if (isa<UsingShadowDecl>(OldD)) {
910 OldIsUsingDecl = true;
911
912 // We can always introduce two using declarations into the same
913 // context, even if they have identical signatures.
914 if (NewIsUsingDecl) continue;
915
916 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
917 }
918
919 // If either declaration was introduced by a using declaration,
920 // we'll need to use slightly different rules for matching.
921 // Essentially, these rules are the normal rules, except that
922 // function templates hide function templates with different
923 // return types or template parameter lists.
924 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000925 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
926 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000927
John McCall51fa86f2009-12-02 08:47:38 +0000928 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000929 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
930 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
931 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
932 continue;
933 }
934
John McCall871b2e72009-12-09 03:35:25 +0000935 Match = *I;
936 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000937 }
John McCall51fa86f2009-12-02 08:47:38 +0000938 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000939 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
940 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
941 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
942 continue;
943 }
944
Rafael Espindola90cc3902013-04-15 12:49:13 +0000945 if (!shouldLinkPossiblyHiddenDecl(*I, New))
946 continue;
947
John McCall871b2e72009-12-09 03:35:25 +0000948 Match = *I;
949 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000950 }
John McCalld7945c62010-11-10 03:01:53 +0000951 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000952 // We can overload with these, which can show up when doing
953 // redeclaration checks for UsingDecls.
954 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000955 } else if (isa<TagDecl>(OldD)) {
956 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000957 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
958 // Optimistically assume that an unresolved using decl will
959 // overload; if it doesn't, we'll have to diagnose during
960 // template instantiation.
961 } else {
John McCall68263142009-11-18 22:49:29 +0000962 // (C++ 13p1):
963 // Only function declarations can be overloaded; object and type
964 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000965 Match = *I;
966 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000967 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000968 }
John McCall68263142009-11-18 22:49:29 +0000969
John McCall871b2e72009-12-09 03:35:25 +0000970 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000971}
972
Rafael Espindola78eeba82012-12-28 14:21:58 +0000973static bool canBeOverloaded(const FunctionDecl &D) {
974 if (D.getAttr<OverloadableAttr>())
975 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000976 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000977 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000978
979 // Main cannot be overloaded (basic.start.main).
980 if (D.isMain())
981 return false;
982
Rafael Espindola78eeba82012-12-28 14:21:58 +0000983 return true;
984}
985
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000986static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
987 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991 // C++ [temp.fct]p2:
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
995 return true;
996
997 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000998 QualType OldQType = S.Context.getCanonicalType(Old->getType());
999 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +00001000
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1004
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009 return false;
1010
John McCallf4c73712011-01-19 06:33:43 +00001011 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001013
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
1018 (OldType->getNumArgs() != NewType->getNumArgs() ||
1019 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001020 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001021 return true;
1022
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1028 // signature.
1029 //
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001032 //
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001036 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001039 OldType->getResultType() != NewType->getResultType()))
1040 return true;
1041
1042 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001044 //
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001052 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001064 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001066 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001067 }
1068 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001069 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001070
Richard Smith21c8fa82013-01-14 05:37:29 +00001071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
1075 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001076 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001077 NewQuals |= Qualifiers::Const;
1078 if (OldMethod->getTypeQualifiers() != NewQuals)
1079 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001080 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001081
John McCall68263142009-11-18 22:49:29 +00001082 // The signatures match; this is not an overload.
1083 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001084}
1085
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001086bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1087 bool UseUsingDeclRules) {
1088 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1089 return false;
1090
1091 // If both of the functions are extern "C", then they are not
1092 // overloads.
1093 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1094 return false;
1095
1096 return true;
1097}
1098
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001099/// \brief Checks availability of the function depending on the current
1100/// function context. Inside an unavailable function, unavailability is ignored.
1101///
1102/// \returns true if \arg FD is unavailable and current context is inside
1103/// an available function, false otherwise.
1104bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1106}
1107
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001108/// \brief Tries a user-defined conversion from From to ToType.
1109///
1110/// Produces an implicit conversion sequence for when a standard conversion
1111/// is not an option. See TryImplicitConversion for more information.
1112static ImplicitConversionSequence
1113TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1114 bool SuppressUserConversions,
1115 bool AllowExplicit,
1116 bool InOverloadResolution,
1117 bool CStyle,
1118 bool AllowObjCWritebackConversion) {
1119 ImplicitConversionSequence ICS;
1120
1121 if (SuppressUserConversions) {
1122 // We're not in the case above, so there is no conversion that
1123 // we can perform.
1124 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1125 return ICS;
1126 }
1127
1128 // Attempt user-defined conversion.
1129 OverloadCandidateSet Conversions(From->getExprLoc());
1130 OverloadingResult UserDefResult
1131 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1132 AllowExplicit);
1133
1134 if (UserDefResult == OR_Success) {
1135 ICS.setUserDefined();
1136 // C++ [over.ics.user]p4:
1137 // A conversion of an expression of class type to the same class
1138 // type is given Exact Match rank, and a conversion of an
1139 // expression of class type to a base class of that type is
1140 // given Conversion rank, in spite of the fact that a copy
1141 // constructor (i.e., a user-defined conversion function) is
1142 // called for those cases.
1143 if (CXXConstructorDecl *Constructor
1144 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1145 QualType FromCanon
1146 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1147 QualType ToCanon
1148 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1149 if (Constructor->isCopyConstructor() &&
1150 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1151 // Turn this into a "standard" conversion sequence, so that it
1152 // gets ranked with standard conversion sequences.
1153 ICS.setStandard();
1154 ICS.Standard.setAsIdentityConversion();
1155 ICS.Standard.setFromType(From->getType());
1156 ICS.Standard.setAllToTypes(ToType);
1157 ICS.Standard.CopyConstructor = Constructor;
1158 if (ToCanon != FromCanon)
1159 ICS.Standard.Second = ICK_Derived_To_Base;
1160 }
1161 }
1162
1163 // C++ [over.best.ics]p4:
1164 // However, when considering the argument of a user-defined
1165 // conversion function that is a candidate by 13.3.1.3 when
1166 // invoked for the copying of the temporary in the second step
1167 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1168 // 13.3.1.6 in all cases, only standard conversion sequences and
1169 // ellipsis conversion sequences are allowed.
1170 if (SuppressUserConversions && ICS.isUserDefined()) {
1171 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1172 }
1173 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1174 ICS.setAmbiguous();
1175 ICS.Ambiguous.setFromType(From->getType());
1176 ICS.Ambiguous.setToType(ToType);
1177 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1178 Cand != Conversions.end(); ++Cand)
1179 if (Cand->Viable)
1180 ICS.Ambiguous.addConversion(Cand->Function);
1181 } else {
1182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1183 }
1184
1185 return ICS;
1186}
1187
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001188/// TryImplicitConversion - Attempt to perform an implicit conversion
1189/// from the given expression (Expr) to the given type (ToType). This
1190/// function returns an implicit conversion sequence that can be used
1191/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001192///
1193/// void f(float f);
1194/// void g(int i) { f(i); }
1195///
1196/// this routine would produce an implicit conversion sequence to
1197/// describe the initialization of f from i, which will be a standard
1198/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1199/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1200//
1201/// Note that this routine only determines how the conversion can be
1202/// performed; it does not actually perform the conversion. As such,
1203/// it will not produce any diagnostics if no conversion is available,
1204/// but will instead return an implicit conversion sequence of kind
1205/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001206///
1207/// If @p SuppressUserConversions, then user-defined conversions are
1208/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001209/// If @p AllowExplicit, then explicit user-defined conversions are
1210/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001211///
1212/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1213/// writeback conversion, which allows __autoreleasing id* parameters to
1214/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001215static ImplicitConversionSequence
1216TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1217 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001218 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001219 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001220 bool CStyle,
1221 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001222 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001223 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001224 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001225 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001226 return ICS;
1227 }
1228
David Blaikie4e4d0842012-03-11 07:00:24 +00001229 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001230 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001231 return ICS;
1232 }
1233
Douglas Gregor604eb652010-08-11 02:15:33 +00001234 // C++ [over.ics.user]p4:
1235 // A conversion of an expression of class type to the same class
1236 // type is given Exact Match rank, and a conversion of an
1237 // expression of class type to a base class of that type is
1238 // given Conversion rank, in spite of the fact that a copy/move
1239 // constructor (i.e., a user-defined conversion function) is
1240 // called for those cases.
1241 QualType FromType = From->getType();
1242 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001243 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1244 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001245 ICS.setStandard();
1246 ICS.Standard.setAsIdentityConversion();
1247 ICS.Standard.setFromType(FromType);
1248 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001250 // We don't actually check at this point whether there is a valid
1251 // copy/move constructor, since overloading just assumes that it
1252 // exists. When we actually perform initialization, we'll find the
1253 // appropriate constructor to copy the returned object, if needed.
1254 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001255
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001256 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001257 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001258 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001259
Douglas Gregor604eb652010-08-11 02:15:33 +00001260 return ICS;
1261 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001262
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001263 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1264 AllowExplicit, InOverloadResolution, CStyle,
1265 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001266}
1267
John McCallf85e1932011-06-15 23:02:42 +00001268ImplicitConversionSequence
1269Sema::TryImplicitConversion(Expr *From, QualType ToType,
1270 bool SuppressUserConversions,
1271 bool AllowExplicit,
1272 bool InOverloadResolution,
1273 bool CStyle,
1274 bool AllowObjCWritebackConversion) {
1275 return clang::TryImplicitConversion(*this, From, ToType,
1276 SuppressUserConversions, AllowExplicit,
1277 InOverloadResolution, CStyle,
1278 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001279}
1280
Douglas Gregor575c63a2010-04-16 22:27:05 +00001281/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001282/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001283/// converted expression. Flavor is the kind of conversion we're
1284/// performing, used in the error message. If @p AllowExplicit,
1285/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001286ExprResult
1287Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001288 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001289 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001290 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001291}
1292
John Wiegley429bb272011-04-08 18:41:53 +00001293ExprResult
1294Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001295 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001296 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001297 if (checkPlaceholderForOverload(*this, From))
1298 return ExprError();
1299
John McCallf85e1932011-06-15 23:02:42 +00001300 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1301 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001302 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001303 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001304
John McCall120d63c2010-08-24 20:38:10 +00001305 ICS = clang::TryImplicitConversion(*this, From, ToType,
1306 /*SuppressUserConversions=*/false,
1307 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001308 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001309 /*CStyle=*/false,
1310 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001311 return PerformImplicitConversion(From, ToType, ICS, Action);
1312}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313
1314/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001315/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001316bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001318 if (Context.hasSameUnqualifiedType(FromType, ToType))
1319 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001320
John McCall00ccbef2010-12-21 00:44:39 +00001321 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322 // where F adds one of the following at most once:
1323 // - a pointer
1324 // - a member pointer
1325 // - a block pointer
1326 CanQualType CanTo = Context.getCanonicalType(ToType);
1327 CanQualType CanFrom = Context.getCanonicalType(FromType);
1328 Type::TypeClass TyClass = CanTo->getTypeClass();
1329 if (TyClass != CanFrom->getTypeClass()) return false;
1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331 if (TyClass == Type::Pointer) {
1332 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334 } else if (TyClass == Type::BlockPointer) {
1335 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337 } else if (TyClass == Type::MemberPointer) {
1338 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1340 } else {
1341 return false;
1342 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001343
John McCall00ccbef2010-12-21 00:44:39 +00001344 TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1347 return false;
1348 }
1349
1350 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352 if (!EInfo.getNoReturn()) return false;
1353
1354 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355 assert(QualType(FromFn, 0).isCanonical());
1356 if (QualType(FromFn, 0) != CanTo) return false;
1357
1358 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001359 return true;
1360}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001362/// \brief Determine whether the conversion from FromType to ToType is a valid
1363/// vector conversion.
1364///
1365/// \param ICK Will be set to the vector conversion kind, if this is a vector
1366/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001367static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1368 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001369 // We need at least one of these types to be a vector type to have a vector
1370 // conversion.
1371 if (!ToType->isVectorType() && !FromType->isVectorType())
1372 return false;
1373
1374 // Identical types require no conversions.
1375 if (Context.hasSameUnqualifiedType(FromType, ToType))
1376 return false;
1377
1378 // There are no conversions between extended vector types, only identity.
1379 if (ToType->isExtVectorType()) {
1380 // There are no conversions between extended vector types other than the
1381 // identity conversion.
1382 if (FromType->isExtVectorType())
1383 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001384
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001386 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001387 ICK = ICK_Vector_Splat;
1388 return true;
1389 }
1390 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001391
1392 // We can perform the conversion between vector types in the following cases:
1393 // 1)vector types are equivalent AltiVec and GCC vector types
1394 // 2)lax vector conversions are permitted and the vector types are of the
1395 // same size
1396 if (ToType->isVectorType() && FromType->isVectorType()) {
1397 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001398 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001399 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001400 ICK = ICK_Vector_Conversion;
1401 return true;
1402 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001403 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001404
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001405 return false;
1406}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregor7d000652012-04-12 20:48:09 +00001408static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1409 bool InOverloadResolution,
1410 StandardConversionSequence &SCS,
1411 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001412
Douglas Gregor60d62c22008-10-31 16:23:19 +00001413/// IsStandardConversion - Determines whether there is a standard
1414/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1415/// expression From to the type ToType. Standard conversion sequences
1416/// only consider non-class types; for conversions that involve class
1417/// types, use TryImplicitConversion. If a conversion exists, SCS will
1418/// contain the standard conversion sequence required to perform this
1419/// conversion and this routine will return true. Otherwise, this
1420/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001421static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1422 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001423 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001424 bool CStyle,
1425 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001426 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001427
Douglas Gregor60d62c22008-10-31 16:23:19 +00001428 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001429 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001430 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001431 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001432 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001433 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434
Douglas Gregorf9201e02009-02-11 23:02:49 +00001435 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001436 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001437 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001438 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001439 return false;
1440
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001442 }
1443
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444 // The first conversion can be an lvalue-to-rvalue conversion,
1445 // array-to-pointer conversion, or function-to-pointer conversion
1446 // (C++ 4p1).
1447
John McCall120d63c2010-08-24 20:38:10 +00001448 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001449 DeclAccessPair AccessPair;
1450 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001452 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001453 // We were able to resolve the address of the overloaded function,
1454 // so we can convert to the type of that function.
1455 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001456
1457 // we can sometimes resolve &foo<int> regardless of ToType, so check
1458 // if the type matches (identity) or we are converting to bool
1459 if (!S.Context.hasSameUnqualifiedType(
1460 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1461 QualType resultTy;
1462 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001463 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001464 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1465 // otherwise, only a boolean conversion is standard
1466 if (!ToType->isBooleanType())
1467 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001468 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469
Chandler Carruth90434232011-03-29 08:08:18 +00001470 // Check if the "from" expression is taking the address of an overloaded
1471 // function and recompute the FromType accordingly. Take advantage of the
1472 // fact that non-static member functions *must* have such an address-of
1473 // expression.
1474 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1475 if (Method && !Method->isStatic()) {
1476 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1477 "Non-unary operator on non-static member address");
1478 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1479 == UO_AddrOf &&
1480 "Non-address-of operator on non-static member address");
1481 const Type *ClassType
1482 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1483 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001484 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1485 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1486 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001487 "Non-address-of operator for overloaded function expression");
1488 FromType = S.Context.getPointerType(FromType);
1489 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001490
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001491 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001492 assert(S.Context.hasSameType(
1493 FromType,
1494 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001495 } else {
1496 return false;
1497 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001498 }
John McCall21480112011-08-30 00:57:29 +00001499 // Lvalue-to-rvalue conversion (C++11 4.1):
1500 // A glvalue (3.10) of a non-function, non-array type T can
1501 // be converted to a prvalue.
1502 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001503 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001504 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001505 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001506 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001507
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001508 // C11 6.3.2.1p2:
1509 // ... if the lvalue has atomic type, the value has the non-atomic version
1510 // of the type of the lvalue ...
1511 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1512 FromType = Atomic->getValueType();
1513
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001514 // If T is a non-class type, the type of the rvalue is the
1515 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001516 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1517 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001518 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001519 } else if (FromType->isArrayType()) {
1520 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001521 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522
1523 // An lvalue or rvalue of type "array of N T" or "array of unknown
1524 // bound of T" can be converted to an rvalue of type "pointer to
1525 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001526 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527
John McCall120d63c2010-08-24 20:38:10 +00001528 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001530 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531
1532 // For the purpose of ranking in overload resolution
1533 // (13.3.3.1.1), this conversion is considered an
1534 // array-to-pointer conversion followed by a qualification
1535 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001536 SCS.Second = ICK_Identity;
1537 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001538 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001539 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001540 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001541 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001542 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001543 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001544 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001545
1546 // An lvalue of function type T can be converted to an rvalue of
1547 // type "pointer to T." The result is a pointer to the
1548 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001549 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001550 } else {
1551 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001554 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001555
1556 // The second conversion can be an integral promotion, floating
1557 // point promotion, integral conversion, floating point conversion,
1558 // floating-integral conversion, pointer conversion,
1559 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001560 // For overloading in C, this can also be a "compatible-type"
1561 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001562 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001563 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001564 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565 // The unqualified versions of the types are the same: there's no
1566 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001567 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001568 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001569 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001570 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001571 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001572 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001574 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001576 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001577 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001578 SCS.Second = ICK_Complex_Promotion;
1579 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001580 } else if (ToType->isBooleanType() &&
1581 (FromType->isArithmeticType() ||
1582 FromType->isAnyPointerType() ||
1583 FromType->isBlockPointerType() ||
1584 FromType->isMemberPointerType() ||
1585 FromType->isNullPtrType())) {
1586 // Boolean conversions (C++ 4.12).
1587 SCS.Second = ICK_Boolean_Conversion;
1588 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001589 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001590 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001591 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001594 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001595 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001596 SCS.Second = ICK_Complex_Conversion;
1597 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001598 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1599 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001600 // Complex-real conversions (C99 6.3.1.7)
1601 SCS.Second = ICK_Complex_Real;
1602 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001603 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001604 // Floating point conversions (C++ 4.8).
1605 SCS.Second = ICK_Floating_Conversion;
1606 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001608 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001609 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001610 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001611 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001612 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001613 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001614 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001615 SCS.Second = ICK_Block_Pointer_Conversion;
1616 } else if (AllowObjCWritebackConversion &&
1617 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1618 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001619 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1620 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001621 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001623 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001624 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001626 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001627 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001628 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001629 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001630 SCS.Second = SecondICK;
1631 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001632 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001633 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001634 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001635 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001636 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001637 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001638 // Treat a conversion that strips "noreturn" as an identity conversion.
1639 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001640 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1641 InOverloadResolution,
1642 SCS, CStyle)) {
1643 SCS.Second = ICK_TransparentUnionConversion;
1644 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001645 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1646 CStyle)) {
1647 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001648 // appropriately.
1649 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001650 } else if (ToType->isEventT() &&
1651 From->isIntegerConstantExpr(S.getASTContext()) &&
1652 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1653 SCS.Second = ICK_Zero_Event_Conversion;
1654 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001655 } else {
1656 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001657 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001659 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001660
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001661 QualType CanonFrom;
1662 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001664 bool ObjCLifetimeConversion;
1665 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1666 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001667 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001668 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001670 CanonFrom = S.Context.getCanonicalType(FromType);
1671 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001672 } else {
1673 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001674 SCS.Third = ICK_Identity;
1675
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001677 // [...] Any difference in top-level cv-qualification is
1678 // subsumed by the initialization itself and does not constitute
1679 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001680 CanonFrom = S.Context.getCanonicalType(FromType);
1681 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001682 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001683 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001684 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001685 FromType = ToType;
1686 CanonFrom = CanonTo;
1687 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001688 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001689 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690
1691 // If we have not converted the argument type to the parameter type,
1692 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001693 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001694 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001695
Douglas Gregor60d62c22008-10-31 16:23:19 +00001696 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001697}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001698
1699static bool
1700IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1701 QualType &ToType,
1702 bool InOverloadResolution,
1703 StandardConversionSequence &SCS,
1704 bool CStyle) {
1705
1706 const RecordType *UT = ToType->getAsUnionType();
1707 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1708 return false;
1709 // The field to initialize within the transparent union.
1710 RecordDecl *UD = UT->getDecl();
1711 // It's compatible if the expression matches any of the fields.
1712 for (RecordDecl::field_iterator it = UD->field_begin(),
1713 itend = UD->field_end();
1714 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001715 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1716 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001717 ToType = it->getType();
1718 return true;
1719 }
1720 }
1721 return false;
1722}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001723
1724/// IsIntegralPromotion - Determines whether the conversion from the
1725/// expression From (whose potentially-adjusted type is FromType) to
1726/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1727/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001728bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001729 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001730 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001731 if (!To) {
1732 return false;
1733 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001734
1735 // An rvalue of type char, signed char, unsigned char, short int, or
1736 // unsigned short int can be converted to an rvalue of type int if
1737 // int can represent all the values of the source type; otherwise,
1738 // the source rvalue can be converted to an rvalue of type unsigned
1739 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001740 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1741 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742 if (// We can promote any signed, promotable integer type to an int
1743 (FromType->isSignedIntegerType() ||
1744 // We can promote any unsigned integer type whose size is
1745 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001746 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001747 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001748 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001749 }
1750
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001751 return To->getKind() == BuiltinType::UInt;
1752 }
1753
Richard Smithe7ff9192012-09-13 21:18:54 +00001754 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755 // A prvalue of an unscoped enumeration type whose underlying type is not
1756 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1757 // following types that can represent all the values of the enumeration
1758 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1759 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001760 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001761 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001762 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 // with lowest integer conversion rank (4.13) greater than the rank of long
1764 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001765 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001766 // C++11 [conv.prom]p4:
1767 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1768 // can be converted to a prvalue of its underlying type. Moreover, if
1769 // integral promotion can be applied to its underlying type, a prvalue of an
1770 // unscoped enumeration type whose underlying type is fixed can also be
1771 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001772 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1773 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1774 // provided for a scoped enumeration.
1775 if (FromEnumType->getDecl()->isScoped())
1776 return false;
1777
Richard Smithe7ff9192012-09-13 21:18:54 +00001778 // We can perform an integral promotion to the underlying type of the enum,
1779 // even if that's not the promoted type.
1780 if (FromEnumType->getDecl()->isFixed()) {
1781 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1782 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1783 IsIntegralPromotion(From, Underlying, ToType);
1784 }
1785
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001786 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001788 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001789 return Context.hasSameUnqualifiedType(ToType,
1790 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001791 }
John McCall842aef82009-12-09 09:09:27 +00001792
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001793 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1795 // to an rvalue a prvalue of the first of the following types that can
1796 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001797 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001799 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001801 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001803 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804 // Determine whether the type we're converting from is signed or
1805 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001806 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001809 // The types we'll try to promote to, in the appropriate
1810 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001811 QualType PromoteTypes[6] = {
1812 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001813 Context.LongTy, Context.UnsignedLongTy ,
1814 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001816 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001817 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1818 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001819 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001820 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1821 // We found the type that we can promote to. If this is the
1822 // type we wanted, we have a promotion. Otherwise, no
1823 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001824 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001825 }
1826 }
1827 }
1828
1829 // An rvalue for an integral bit-field (9.6) can be converted to an
1830 // rvalue of type int if int can represent all the values of the
1831 // bit-field; otherwise, it can be converted to unsigned int if
1832 // unsigned int can represent all the values of the bit-field. If
1833 // the bit-field is larger yet, no integral promotion applies to
1834 // it. If the bit-field has an enumerated type, it is treated as any
1835 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001836 // FIXME: We should delay checking of bit-fields until we actually perform the
1837 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001838 using llvm::APSInt;
1839 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001840 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001841 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001842 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001843 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1844 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1845 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor86f19402008-12-20 23:49:58 +00001847 // Are we promoting to an int from a bitfield that fits in an int?
1848 if (BitWidth < ToSize ||
1849 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1850 return To->getKind() == BuiltinType::Int;
1851 }
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor86f19402008-12-20 23:49:58 +00001853 // Are we promoting to an unsigned int from an unsigned bitfield
1854 // that fits into an unsigned int?
1855 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1856 return To->getKind() == BuiltinType::UInt;
1857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Douglas Gregor86f19402008-12-20 23:49:58 +00001859 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001860 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001861 }
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001863 // An rvalue of type bool can be converted to an rvalue of type int,
1864 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001865 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001867 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001868
1869 return false;
1870}
1871
1872/// IsFloatingPointPromotion - Determines whether the conversion from
1873/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1874/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001875bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001876 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1877 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001878 /// An rvalue of type float can be converted to an rvalue of type
1879 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001880 if (FromBuiltin->getKind() == BuiltinType::Float &&
1881 ToBuiltin->getKind() == BuiltinType::Double)
1882 return true;
1883
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001884 // C99 6.3.1.5p1:
1885 // When a float is promoted to double or long double, or a
1886 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001887 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001888 (FromBuiltin->getKind() == BuiltinType::Float ||
1889 FromBuiltin->getKind() == BuiltinType::Double) &&
1890 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1891 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001892
1893 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001894 if (!getLangOpts().NativeHalfType &&
1895 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001896 ToBuiltin->getKind() == BuiltinType::Float)
1897 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001898 }
1899
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001900 return false;
1901}
1902
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001903/// \brief Determine if a conversion is a complex promotion.
1904///
1905/// A complex promotion is defined as a complex -> complex conversion
1906/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001907/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001908bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001909 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001910 if (!FromComplex)
1911 return false;
1912
John McCall183700f2009-09-21 23:43:11 +00001913 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001914 if (!ToComplex)
1915 return false;
1916
1917 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001918 ToComplex->getElementType()) ||
1919 IsIntegralPromotion(0, FromComplex->getElementType(),
1920 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001921}
1922
Douglas Gregorcb7de522008-11-26 23:31:11 +00001923/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1924/// the pointer type FromPtr to a pointer to type ToPointee, with the
1925/// same type qualifiers as FromPtr has on its pointee type. ToType,
1926/// if non-empty, will be a pointer to ToType that may or may not have
1927/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001928///
Mike Stump1eb44332009-09-09 15:08:12 +00001929static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001930BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001932 ASTContext &Context,
1933 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001934 assert((FromPtr->getTypeClass() == Type::Pointer ||
1935 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1936 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001937
John McCallf85e1932011-06-15 23:02:42 +00001938 /// Conversions to 'id' subsume cv-qualifier conversions.
1939 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001940 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001941
1942 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001943 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001944 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001945 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001946
John McCallf85e1932011-06-15 23:02:42 +00001947 if (StripObjCLifetime)
1948 Quals.removeObjCLifetime();
1949
Mike Stump1eb44332009-09-09 15:08:12 +00001950 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001951 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001953 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001954 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001955
1956 // Build a pointer to ToPointee. It has the right qualifiers
1957 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001958 if (isa<ObjCObjectPointerType>(ToType))
1959 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001960 return Context.getPointerType(ToPointee);
1961 }
1962
1963 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001964 QualType QualifiedCanonToPointee
1965 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001966
Douglas Gregorda80f742010-12-01 21:43:58 +00001967 if (isa<ObjCObjectPointerType>(ToType))
1968 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1969 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001970}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001971
Mike Stump1eb44332009-09-09 15:08:12 +00001972static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001973 bool InOverloadResolution,
1974 ASTContext &Context) {
1975 // Handle value-dependent integral null pointer constants correctly.
1976 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1977 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001978 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001979 return !InOverloadResolution;
1980
Douglas Gregorce940492009-09-25 04:25:58 +00001981 return Expr->isNullPointerConstant(Context,
1982 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1983 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001984}
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001986/// IsPointerConversion - Determines whether the conversion of the
1987/// expression From, which has the (possibly adjusted) type FromType,
1988/// can be converted to the type ToType via a pointer conversion (C++
1989/// 4.10). If so, returns true and places the converted type (that
1990/// might differ from ToType in its cv-qualifiers at some level) into
1991/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001992///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001993/// This routine also supports conversions to and from block pointers
1994/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1995/// pointers to interfaces. FIXME: Once we've determined the
1996/// appropriate overloading rules for Objective-C, we may want to
1997/// split the Objective-C checks into a different routine; however,
1998/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001999/// conversions, so for now they live here. IncompatibleObjC will be
2000/// set if the conversion is an allowed Objective-C conversion that
2001/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002002bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002003 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002004 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002005 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002006 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002007 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2008 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002009 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002010
Mike Stump1eb44332009-09-09 15:08:12 +00002011 // Conversion from a null pointer constant to any Objective-C pointer type.
2012 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002014 ConvertedType = ToType;
2015 return true;
2016 }
2017
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002018 // Blocks: Block pointers can be converted to void*.
2019 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002021 ConvertedType = ToType;
2022 return true;
2023 }
2024 // Blocks: A null pointer constant can be converted to a block
2025 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002026 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002027 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002028 ConvertedType = ToType;
2029 return true;
2030 }
2031
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002032 // If the left-hand-side is nullptr_t, the right side can be a null
2033 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039
Ted Kremenek6217b802009-07-29 21:53:49 +00002040 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002041 if (!ToTypePtr)
2042 return false;
2043
2044 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002045 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002046 ConvertedType = ToType;
2047 return true;
2048 }
Sebastian Redl07779722008-10-31 14:43:28 +00002049
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002051 // , including objective-c pointers.
2052 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002053 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002054 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002055 ConvertedType = BuildSimilarlyQualifiedPointerType(
2056 FromType->getAs<ObjCObjectPointerType>(),
2057 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002058 ToType, Context);
2059 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002060 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002061 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002062 if (!FromTypePtr)
2063 return false;
2064
2065 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002066
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002067 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002068 // pointer conversion, so don't do all of the work below.
2069 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2070 return false;
2071
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002072 // An rvalue of type "pointer to cv T," where T is an object type,
2073 // can be converted to an rvalue of type "pointer to cv void" (C++
2074 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002075 if (FromPointeeType->isIncompleteOrObjectType() &&
2076 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002078 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002079 ToType, Context,
2080 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002081 return true;
2082 }
2083
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002084 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002085 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002086 ToPointeeType->isVoidType()) {
2087 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2088 ToPointeeType,
2089 ToType, Context);
2090 return true;
2091 }
2092
Douglas Gregorf9201e02009-02-11 23:02:49 +00002093 // When we're overloading in C, we allow a special kind of pointer
2094 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002095 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002096 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002098 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002099 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002100 return true;
2101 }
2102
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002103 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002104 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002105 // An rvalue of type "pointer to cv D," where D is a class type,
2106 // can be converted to an rvalue of type "pointer to cv B," where
2107 // B is a base class (clause 10) of D. If B is an inaccessible
2108 // (clause 11) or ambiguous (10.2) base class of D, a program that
2109 // necessitates this conversion is ill-formed. The result of the
2110 // conversion is a pointer to the base class sub-object of the
2111 // derived class object. The null pointer value is converted to
2112 // the null pointer value of the destination type.
2113 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002114 // Note that we do not check for ambiguity or inaccessibility
2115 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002116 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002117 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002118 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002119 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002120 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002121 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002122 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002123 ToType, Context);
2124 return true;
2125 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002126
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002127 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2128 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2130 ToPointeeType,
2131 ToType, Context);
2132 return true;
2133 }
2134
Douglas Gregorc7887512008-12-19 19:13:09 +00002135 return false;
2136}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002137
2138/// \brief Adopt the given qualifiers for the given type.
2139static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2140 Qualifiers TQs = T.getQualifiers();
2141
2142 // Check whether qualifiers already match.
2143 if (TQs == Qs)
2144 return T;
2145
2146 if (Qs.compatiblyIncludes(TQs))
2147 return Context.getQualifiedType(T, Qs);
2148
2149 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2150}
Douglas Gregorc7887512008-12-19 19:13:09 +00002151
2152/// isObjCPointerConversion - Determines whether this is an
2153/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2154/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002155bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002156 QualType& ConvertedType,
2157 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002158 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002159 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002161 // The set of qualifiers on the type we're converting from.
2162 Qualifiers FromQualifiers = FromType.getQualifiers();
2163
Steve Naroff14108da2009-07-10 23:34:53 +00002164 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002165 const ObjCObjectPointerType* ToObjCPtr =
2166 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002167 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002168 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002169
Steve Naroff14108da2009-07-10 23:34:53 +00002170 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002171 // If the pointee types are the same (ignoring qualifications),
2172 // then this is not a pointer conversion.
2173 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2174 FromObjCPtr->getPointeeType()))
2175 return false;
2176
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002177 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002178 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002179 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002180 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002181 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002182 return true;
2183 }
2184 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002185 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002186 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002187 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002188 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002190 return true;
2191 }
2192 // Objective C++: We're able to convert from a pointer to an
2193 // interface to a pointer to a different interface.
2194 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002195 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2196 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002197 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002198 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2199 FromObjCPtr->getPointeeType()))
2200 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002202 ToObjCPtr->getPointeeType(),
2203 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002205 return true;
2206 }
2207
2208 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2209 // Okay: this is some kind of implicit downcast of Objective-C
2210 // interfaces, which is permitted. However, we're going to
2211 // complain about it.
2212 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002213 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002214 ToObjCPtr->getPointeeType(),
2215 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002216 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002217 return true;
2218 }
Mike Stump1eb44332009-09-09 15:08:12 +00002219 }
Steve Naroff14108da2009-07-10 23:34:53 +00002220 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002221 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002222 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002223 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002224 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002225 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002226 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002227 // to a block pointer type.
2228 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002229 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002230 return true;
2231 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002232 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002233 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002234 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002235 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002236 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002237 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002238 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002239 return true;
2240 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002241 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002242 return false;
2243
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002244 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002245 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002246 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002247 else if (const BlockPointerType *FromBlockPtr =
2248 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002249 FromPointeeType = FromBlockPtr->getPointeeType();
2250 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002251 return false;
2252
Douglas Gregorc7887512008-12-19 19:13:09 +00002253 // If we have pointers to pointers, recursively check whether this
2254 // is an Objective-C conversion.
2255 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2256 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2257 IncompatibleObjC)) {
2258 // We always complain about this conversion.
2259 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002260 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002261 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002262 return true;
2263 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002264 // Allow conversion of pointee being objective-c pointer to another one;
2265 // as in I* to id.
2266 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2267 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2268 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2269 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002270
Douglas Gregorda80f742010-12-01 21:43:58 +00002271 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002272 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002273 return true;
2274 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002275
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002276 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002277 // differences in the argument and result types are in Objective-C
2278 // pointer conversions. If so, we permit the conversion (but
2279 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002280 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002281 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002282 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002283 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002284 if (FromFunctionType && ToFunctionType) {
2285 // If the function types are exactly the same, this isn't an
2286 // Objective-C pointer conversion.
2287 if (Context.getCanonicalType(FromPointeeType)
2288 == Context.getCanonicalType(ToPointeeType))
2289 return false;
2290
2291 // Perform the quick checks that will tell us whether these
2292 // function types are obviously different.
2293 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2294 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2295 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2296 return false;
2297
2298 bool HasObjCConversion = false;
2299 if (Context.getCanonicalType(FromFunctionType->getResultType())
2300 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2301 // Okay, the types match exactly. Nothing to do.
2302 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2303 ToFunctionType->getResultType(),
2304 ConvertedType, IncompatibleObjC)) {
2305 // Okay, we have an Objective-C pointer conversion.
2306 HasObjCConversion = true;
2307 } else {
2308 // Function types are too different. Abort.
2309 return false;
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregorc7887512008-12-19 19:13:09 +00002312 // Check argument types.
2313 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2314 ArgIdx != NumArgs; ++ArgIdx) {
2315 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2316 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2317 if (Context.getCanonicalType(FromArgType)
2318 == Context.getCanonicalType(ToArgType)) {
2319 // Okay, the types match exactly. Nothing to do.
2320 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2321 ConvertedType, IncompatibleObjC)) {
2322 // Okay, we have an Objective-C pointer conversion.
2323 HasObjCConversion = true;
2324 } else {
2325 // Argument types are too different. Abort.
2326 return false;
2327 }
2328 }
2329
2330 if (HasObjCConversion) {
2331 // We had an Objective-C conversion. Allow this pointer
2332 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002333 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002334 IncompatibleObjC = true;
2335 return true;
2336 }
2337 }
2338
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002339 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002340}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341
John McCallf85e1932011-06-15 23:02:42 +00002342/// \brief Determine whether this is an Objective-C writeback conversion,
2343/// used for parameter passing when performing automatic reference counting.
2344///
2345/// \param FromType The type we're converting form.
2346///
2347/// \param ToType The type we're converting to.
2348///
2349/// \param ConvertedType The type that will be produced after applying
2350/// this conversion.
2351bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2352 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002353 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002354 Context.hasSameUnqualifiedType(FromType, ToType))
2355 return false;
2356
2357 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2358 QualType ToPointee;
2359 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2360 ToPointee = ToPointer->getPointeeType();
2361 else
2362 return false;
2363
2364 Qualifiers ToQuals = ToPointee.getQualifiers();
2365 if (!ToPointee->isObjCLifetimeType() ||
2366 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002367 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002368 return false;
2369
2370 // Argument must be a pointer to __strong to __weak.
2371 QualType FromPointee;
2372 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2373 FromPointee = FromPointer->getPointeeType();
2374 else
2375 return false;
2376
2377 Qualifiers FromQuals = FromPointee.getQualifiers();
2378 if (!FromPointee->isObjCLifetimeType() ||
2379 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2380 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2381 return false;
2382
2383 // Make sure that we have compatible qualifiers.
2384 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2385 if (!ToQuals.compatiblyIncludes(FromQuals))
2386 return false;
2387
2388 // Remove qualifiers from the pointee type we're converting from; they
2389 // aren't used in the compatibility check belong, and we'll be adding back
2390 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2391 FromPointee = FromPointee.getUnqualifiedType();
2392
2393 // The unqualified form of the pointee types must be compatible.
2394 ToPointee = ToPointee.getUnqualifiedType();
2395 bool IncompatibleObjC;
2396 if (Context.typesAreCompatible(FromPointee, ToPointee))
2397 FromPointee = ToPointee;
2398 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2399 IncompatibleObjC))
2400 return false;
2401
2402 /// \brief Construct the type we're converting to, which is a pointer to
2403 /// __autoreleasing pointee.
2404 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2405 ConvertedType = Context.getPointerType(FromPointee);
2406 return true;
2407}
2408
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002409bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2410 QualType& ConvertedType) {
2411 QualType ToPointeeType;
2412 if (const BlockPointerType *ToBlockPtr =
2413 ToType->getAs<BlockPointerType>())
2414 ToPointeeType = ToBlockPtr->getPointeeType();
2415 else
2416 return false;
2417
2418 QualType FromPointeeType;
2419 if (const BlockPointerType *FromBlockPtr =
2420 FromType->getAs<BlockPointerType>())
2421 FromPointeeType = FromBlockPtr->getPointeeType();
2422 else
2423 return false;
2424 // We have pointer to blocks, check whether the only
2425 // differences in the argument and result types are in Objective-C
2426 // pointer conversions. If so, we permit the conversion.
2427
2428 const FunctionProtoType *FromFunctionType
2429 = FromPointeeType->getAs<FunctionProtoType>();
2430 const FunctionProtoType *ToFunctionType
2431 = ToPointeeType->getAs<FunctionProtoType>();
2432
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002433 if (!FromFunctionType || !ToFunctionType)
2434 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002435
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002436 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002437 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002438
2439 // Perform the quick checks that will tell us whether these
2440 // function types are obviously different.
2441 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2442 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2443 return false;
2444
2445 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2446 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2447 if (FromEInfo != ToEInfo)
2448 return false;
2449
2450 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002451 if (Context.hasSameType(FromFunctionType->getResultType(),
2452 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002453 // Okay, the types match exactly. Nothing to do.
2454 } else {
2455 QualType RHS = FromFunctionType->getResultType();
2456 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002457 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002458 !RHS.hasQualifiers() && LHS.hasQualifiers())
2459 LHS = LHS.getUnqualifiedType();
2460
2461 if (Context.hasSameType(RHS,LHS)) {
2462 // OK exact match.
2463 } else if (isObjCPointerConversion(RHS, LHS,
2464 ConvertedType, IncompatibleObjC)) {
2465 if (IncompatibleObjC)
2466 return false;
2467 // Okay, we have an Objective-C pointer conversion.
2468 }
2469 else
2470 return false;
2471 }
2472
2473 // Check argument types.
2474 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2475 ArgIdx != NumArgs; ++ArgIdx) {
2476 IncompatibleObjC = false;
2477 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2478 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2479 if (Context.hasSameType(FromArgType, ToArgType)) {
2480 // Okay, the types match exactly. Nothing to do.
2481 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2482 ConvertedType, IncompatibleObjC)) {
2483 if (IncompatibleObjC)
2484 return false;
2485 // Okay, we have an Objective-C pointer conversion.
2486 } else
2487 // Argument types are too different. Abort.
2488 return false;
2489 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002490 if (LangOpts.ObjCAutoRefCount &&
2491 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2492 ToFunctionType))
2493 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002494
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002495 ConvertedType = ToType;
2496 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002497}
2498
Richard Trieu6efd4c52011-11-23 22:32:32 +00002499enum {
2500 ft_default,
2501 ft_different_class,
2502 ft_parameter_arity,
2503 ft_parameter_mismatch,
2504 ft_return_type,
2505 ft_qualifer_mismatch
2506};
2507
2508/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2509/// function types. Catches different number of parameter, mismatch in
2510/// parameter types, and different return types.
2511void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2512 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002513 // If either type is not valid, include no extra info.
2514 if (FromType.isNull() || ToType.isNull()) {
2515 PDiag << ft_default;
2516 return;
2517 }
2518
Richard Trieu6efd4c52011-11-23 22:32:32 +00002519 // Get the function type from the pointers.
2520 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2521 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2522 *ToMember = ToType->getAs<MemberPointerType>();
2523 if (FromMember->getClass() != ToMember->getClass()) {
2524 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2525 << QualType(FromMember->getClass(), 0);
2526 return;
2527 }
2528 FromType = FromMember->getPointeeType();
2529 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002530 }
2531
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002532 if (FromType->isPointerType())
2533 FromType = FromType->getPointeeType();
2534 if (ToType->isPointerType())
2535 ToType = ToType->getPointeeType();
2536
2537 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002538 FromType = FromType.getNonReferenceType();
2539 ToType = ToType.getNonReferenceType();
2540
Richard Trieu6efd4c52011-11-23 22:32:32 +00002541 // Don't print extra info for non-specialized template functions.
2542 if (FromType->isInstantiationDependentType() &&
2543 !FromType->getAs<TemplateSpecializationType>()) {
2544 PDiag << ft_default;
2545 return;
2546 }
2547
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002548 // No extra info for same types.
2549 if (Context.hasSameType(FromType, ToType)) {
2550 PDiag << ft_default;
2551 return;
2552 }
2553
Richard Trieu6efd4c52011-11-23 22:32:32 +00002554 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2555 *ToFunction = ToType->getAs<FunctionProtoType>();
2556
2557 // Both types need to be function types.
2558 if (!FromFunction || !ToFunction) {
2559 PDiag << ft_default;
2560 return;
2561 }
2562
2563 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2564 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2565 << FromFunction->getNumArgs();
2566 return;
2567 }
2568
2569 // Handle different parameter types.
2570 unsigned ArgPos;
2571 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2572 PDiag << ft_parameter_mismatch << ArgPos + 1
2573 << ToFunction->getArgType(ArgPos)
2574 << FromFunction->getArgType(ArgPos);
2575 return;
2576 }
2577
2578 // Handle different return type.
2579 if (!Context.hasSameType(FromFunction->getResultType(),
2580 ToFunction->getResultType())) {
2581 PDiag << ft_return_type << ToFunction->getResultType()
2582 << FromFunction->getResultType();
2583 return;
2584 }
2585
2586 unsigned FromQuals = FromFunction->getTypeQuals(),
2587 ToQuals = ToFunction->getTypeQuals();
2588 if (FromQuals != ToQuals) {
2589 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2590 return;
2591 }
2592
2593 // Unable to find a difference, so add no extra info.
2594 PDiag << ft_default;
2595}
2596
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002597/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002598/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002599/// they have same number of arguments. This routine assumes that Objective-C
2600/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002601/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002602/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002603bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002604 const FunctionProtoType *NewType,
2605 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002606 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002607 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2608 N = NewType->arg_type_begin(),
2609 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2610 if (!Context.hasSameType(*O, *N)) {
2611 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2612 return false;
2613 }
2614 }
2615 return true;
2616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002617
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002618 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2619 N = NewType->arg_type_begin(),
2620 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2621 QualType ToType = (*O);
2622 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002623 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002624 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2625 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002626 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2627 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2628 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2629 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002630 continue;
2631 }
John McCallc12c5bb2010-05-15 11:32:37 +00002632 else if (const ObjCObjectPointerType *PTTo =
2633 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002634 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002635 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002636 if (Context.hasSameUnqualifiedType(
2637 PTTo->getObjectType()->getBaseType(),
2638 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002639 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002640 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002641 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002642 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002643 }
2644 }
2645 return true;
2646}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002647
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002648/// CheckPointerConversion - Check the pointer conversion from the
2649/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002650/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002651/// conversions for which IsPointerConversion has already returned
2652/// true. It returns true and produces a diagnostic if there was an
2653/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002654bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002655 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002656 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002657 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002658 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002659 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002660
John McCalldaa8e4e2010-11-15 09:13:47 +00002661 Kind = CK_BitCast;
2662
David Blaikie50800fc2012-08-08 17:33:31 +00002663 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2664 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2665 Expr::NPCK_ZeroExpression) {
2666 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2667 DiagRuntimeBehavior(From->getExprLoc(), From,
2668 PDiag(diag::warn_impcast_bool_to_null_pointer)
2669 << ToType << From->getSourceRange());
2670 else if (!isUnevaluatedContext())
2671 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2672 << ToType << From->getSourceRange();
2673 }
John McCall1d9b3b22011-09-09 05:25:32 +00002674 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2675 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002676 QualType FromPointeeType = FromPtrType->getPointeeType(),
2677 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002678
Douglas Gregor5fccd362010-03-03 23:55:11 +00002679 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2680 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002681 // We must have a derived-to-base conversion. Check an
2682 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002683 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2684 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002685 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002686 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002687 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002688
Anders Carlsson61faec12009-09-12 04:46:44 +00002689 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002690 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002691 }
2692 }
John McCall1d9b3b22011-09-09 05:25:32 +00002693 } else if (const ObjCObjectPointerType *ToPtrType =
2694 ToType->getAs<ObjCObjectPointerType>()) {
2695 if (const ObjCObjectPointerType *FromPtrType =
2696 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002697 // Objective-C++ conversions are always okay.
2698 // FIXME: We should have a different class of conversions for the
2699 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002700 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002701 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002702 } else if (FromType->isBlockPointerType()) {
2703 Kind = CK_BlockPointerToObjCPointerCast;
2704 } else {
2705 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002706 }
John McCall1d9b3b22011-09-09 05:25:32 +00002707 } else if (ToType->isBlockPointerType()) {
2708 if (!FromType->isBlockPointerType())
2709 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002710 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002711
2712 // We shouldn't fall into this case unless it's valid for other
2713 // reasons.
2714 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2715 Kind = CK_NullToPointer;
2716
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002717 return false;
2718}
2719
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720/// IsMemberPointerConversion - Determines whether the conversion of the
2721/// expression From, which has the (possibly adjusted) type FromType, can be
2722/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2723/// If so, returns true and places the converted type (that might differ from
2724/// ToType in its cv-qualifiers at some level) into ConvertedType.
2725bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002727 bool InOverloadResolution,
2728 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002729 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002730 if (!ToTypePtr)
2731 return false;
2732
2733 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002734 if (From->isNullPointerConstant(Context,
2735 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2736 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737 ConvertedType = ToType;
2738 return true;
2739 }
2740
2741 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002742 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002743 if (!FromTypePtr)
2744 return false;
2745
2746 // A pointer to member of B can be converted to a pointer to member of D,
2747 // where D is derived from B (C++ 4.11p2).
2748 QualType FromClass(FromTypePtr->getClass(), 0);
2749 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002750
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002751 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002752 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002753 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002754 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2755 ToClass.getTypePtr());
2756 return true;
2757 }
2758
2759 return false;
2760}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002761
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002762/// CheckMemberPointerConversion - Check the member pointer conversion from the
2763/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002764/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002765/// for which IsMemberPointerConversion has already returned true. It returns
2766/// true and produces a diagnostic if there was an error, or returns false
2767/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002768bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002769 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002770 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002771 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002772 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002773 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002774 if (!FromPtrType) {
2775 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002776 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002777 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002778 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002779 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002780 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002781 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002782
Ted Kremenek6217b802009-07-29 21:53:49 +00002783 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002784 assert(ToPtrType && "No member pointer cast has a target type "
2785 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002786
Sebastian Redl21593ac2009-01-28 18:33:18 +00002787 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2788 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002789
Sebastian Redl21593ac2009-01-28 18:33:18 +00002790 // FIXME: What about dependent types?
2791 assert(FromClass->isRecordType() && "Pointer into non-class.");
2792 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002793
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002794 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002795 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002796 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2797 assert(DerivationOkay &&
2798 "Should not have been called if derivation isn't OK.");
2799 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002800
Sebastian Redl21593ac2009-01-28 18:33:18 +00002801 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2802 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002803 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2804 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2805 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2806 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002807 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002808
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002809 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002810 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2811 << FromClass << ToClass << QualType(VBase, 0)
2812 << From->getSourceRange();
2813 return true;
2814 }
2815
John McCall6b2accb2010-02-10 09:31:12 +00002816 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002817 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2818 Paths.front(),
2819 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002820
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002821 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002822 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002823 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002824 return false;
2825}
2826
Douglas Gregor98cd5992008-10-21 23:43:52 +00002827/// IsQualificationConversion - Determines whether the conversion from
2828/// an rvalue of type FromType to ToType is a qualification conversion
2829/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002830///
2831/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2832/// when the qualification conversion involves a change in the Objective-C
2833/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002834bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002835Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002836 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002837 FromType = Context.getCanonicalType(FromType);
2838 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002839 ObjCLifetimeConversion = false;
2840
Douglas Gregor98cd5992008-10-21 23:43:52 +00002841 // If FromType and ToType are the same type, this is not a
2842 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002843 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002844 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002845
Douglas Gregor98cd5992008-10-21 23:43:52 +00002846 // (C++ 4.4p4):
2847 // A conversion can add cv-qualifiers at levels other than the first
2848 // in multi-level pointers, subject to the following rules: [...]
2849 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002850 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002851 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002852 // Within each iteration of the loop, we check the qualifiers to
2853 // determine if this still looks like a qualification
2854 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002855 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002856 // until there are no more pointers or pointers-to-members left to
2857 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002858 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002859
Douglas Gregor621c92a2011-04-25 18:40:17 +00002860 Qualifiers FromQuals = FromType.getQualifiers();
2861 Qualifiers ToQuals = ToType.getQualifiers();
2862
John McCallf85e1932011-06-15 23:02:42 +00002863 // Objective-C ARC:
2864 // Check Objective-C lifetime conversions.
2865 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2866 UnwrappedAnyPointer) {
2867 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2868 ObjCLifetimeConversion = true;
2869 FromQuals.removeObjCLifetime();
2870 ToQuals.removeObjCLifetime();
2871 } else {
2872 // Qualification conversions cannot cast between different
2873 // Objective-C lifetime qualifiers.
2874 return false;
2875 }
2876 }
2877
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002878 // Allow addition/removal of GC attributes but not changing GC attributes.
2879 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2880 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2881 FromQuals.removeObjCGCAttr();
2882 ToQuals.removeObjCGCAttr();
2883 }
2884
Douglas Gregor98cd5992008-10-21 23:43:52 +00002885 // -- for every j > 0, if const is in cv 1,j then const is in cv
2886 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002887 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002888 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Douglas Gregor98cd5992008-10-21 23:43:52 +00002890 // -- if the cv 1,j and cv 2,j are different, then const is in
2891 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002892 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002893 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002894 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Douglas Gregor98cd5992008-10-21 23:43:52 +00002896 // Keep track of whether all prior cv-qualifiers in the "to" type
2897 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002898 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002899 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002900 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002901
2902 // We are left with FromType and ToType being the pointee types
2903 // after unwrapping the original FromType and ToType the same number
2904 // of types. If we unwrapped any pointers, and if FromType and
2905 // ToType have the same unqualified type (since we checked
2906 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002907 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002908}
2909
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002910/// \brief - Determine whether this is a conversion from a scalar type to an
2911/// atomic type.
2912///
2913/// If successful, updates \c SCS's second and third steps in the conversion
2914/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002915static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2916 bool InOverloadResolution,
2917 StandardConversionSequence &SCS,
2918 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002919 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2920 if (!ToAtomic)
2921 return false;
2922
2923 StandardConversionSequence InnerSCS;
2924 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2925 InOverloadResolution, InnerSCS,
2926 CStyle, /*AllowObjCWritebackConversion=*/false))
2927 return false;
2928
2929 SCS.Second = InnerSCS.Second;
2930 SCS.setToType(1, InnerSCS.getToType(1));
2931 SCS.Third = InnerSCS.Third;
2932 SCS.QualificationIncludesObjCLifetime
2933 = InnerSCS.QualificationIncludesObjCLifetime;
2934 SCS.setToType(2, InnerSCS.getToType(2));
2935 return true;
2936}
2937
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002938static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2939 CXXConstructorDecl *Constructor,
2940 QualType Type) {
2941 const FunctionProtoType *CtorType =
2942 Constructor->getType()->getAs<FunctionProtoType>();
2943 if (CtorType->getNumArgs() > 0) {
2944 QualType FirstArg = CtorType->getArgType(0);
2945 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2946 return true;
2947 }
2948 return false;
2949}
2950
Sebastian Redl56a04282012-02-11 23:51:08 +00002951static OverloadingResult
2952IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2953 CXXRecordDecl *To,
2954 UserDefinedConversionSequence &User,
2955 OverloadCandidateSet &CandidateSet,
2956 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002957 DeclContext::lookup_result R = S.LookupConstructors(To);
2958 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002959 Con != ConEnd; ++Con) {
2960 NamedDecl *D = *Con;
2961 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2962
2963 // Find the constructor (which may be a template).
2964 CXXConstructorDecl *Constructor = 0;
2965 FunctionTemplateDecl *ConstructorTmpl
2966 = dyn_cast<FunctionTemplateDecl>(D);
2967 if (ConstructorTmpl)
2968 Constructor
2969 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2970 else
2971 Constructor = cast<CXXConstructorDecl>(D);
2972
2973 bool Usable = !Constructor->isInvalidDecl() &&
2974 S.isInitListConstructor(Constructor) &&
2975 (AllowExplicit || !Constructor->isExplicit());
2976 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002977 // If the first argument is (a reference to) the target type,
2978 // suppress conversions.
2979 bool SuppressUserConversions =
2980 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002981 if (ConstructorTmpl)
2982 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2983 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002984 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002985 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002986 else
2987 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002988 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002989 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002990 }
2991 }
2992
2993 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2994
2995 OverloadCandidateSet::iterator Best;
2996 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2997 case OR_Success: {
2998 // Record the standard conversion we used and the conversion function.
2999 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00003000 QualType ThisType = Constructor->getThisType(S.Context);
3001 // Initializer lists don't have conversions as such.
3002 User.Before.setAsIdentityConversion();
3003 User.HadMultipleCandidates = HadMultipleCandidates;
3004 User.ConversionFunction = Constructor;
3005 User.FoundConversionFunction = Best->FoundDecl;
3006 User.After.setAsIdentityConversion();
3007 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3008 User.After.setAllToTypes(ToType);
3009 return OR_Success;
3010 }
3011
3012 case OR_No_Viable_Function:
3013 return OR_No_Viable_Function;
3014 case OR_Deleted:
3015 return OR_Deleted;
3016 case OR_Ambiguous:
3017 return OR_Ambiguous;
3018 }
3019
3020 llvm_unreachable("Invalid OverloadResult!");
3021}
3022
Douglas Gregor734d9862009-01-30 23:27:23 +00003023/// Determines whether there is a user-defined conversion sequence
3024/// (C++ [over.ics.user]) that converts expression From to the type
3025/// ToType. If such a conversion exists, User will contain the
3026/// user-defined conversion sequence that performs such a conversion
3027/// and this routine will return true. Otherwise, this routine returns
3028/// false and User is unspecified.
3029///
Douglas Gregor734d9862009-01-30 23:27:23 +00003030/// \param AllowExplicit true if the conversion should consider C++0x
3031/// "explicit" conversion functions as well as non-explicit conversion
3032/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003033static OverloadingResult
3034IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003035 UserDefinedConversionSequence &User,
3036 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003037 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003038 // Whether we will only visit constructors.
3039 bool ConstructorsOnly = false;
3040
3041 // If the type we are conversion to is a class type, enumerate its
3042 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003044 // C++ [over.match.ctor]p1:
3045 // When objects of class type are direct-initialized (8.5), or
3046 // copy-initialized from an expression of the same or a
3047 // derived class type (8.5), overload resolution selects the
3048 // constructor. [...] For copy-initialization, the candidate
3049 // functions are all the converting constructors (12.3.1) of
3050 // that class. The argument list is the expression-list within
3051 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003052 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003053 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003054 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003055 ConstructorsOnly = true;
3056
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003057 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003058 // RequireCompleteType may have returned true due to some invalid decl
3059 // during template instantiation, but ToType may be complete enough now
3060 // to try to recover.
3061 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003062 // We're not going to find any constructors.
3063 } else if (CXXRecordDecl *ToRecordDecl
3064 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003065
3066 Expr **Args = &From;
3067 unsigned NumArgs = 1;
3068 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003069 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003070 // But first, see if there is an init-list-contructor that will work.
3071 OverloadingResult Result = IsInitializerListConstructorConversion(
3072 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3073 if (Result != OR_No_Viable_Function)
3074 return Result;
3075 // Never mind.
3076 CandidateSet.clear();
3077
3078 // If we're list-initializing, we pass the individual elements as
3079 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003080 Args = InitList->getInits();
3081 NumArgs = InitList->getNumInits();
3082 ListInitializing = true;
3083 }
3084
David Blaikie3bc93e32012-12-19 00:45:41 +00003085 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3086 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003087 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003088 NamedDecl *D = *Con;
3089 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3090
Douglas Gregordec06662009-08-21 18:42:58 +00003091 // Find the constructor (which may be a template).
3092 CXXConstructorDecl *Constructor = 0;
3093 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003094 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003095 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003096 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003097 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3098 else
John McCall9aa472c2010-03-19 07:35:19 +00003099 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003100
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003101 bool Usable = !Constructor->isInvalidDecl();
3102 if (ListInitializing)
3103 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3104 else
3105 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3106 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003107 bool SuppressUserConversions = !ConstructorsOnly;
3108 if (SuppressUserConversions && ListInitializing) {
3109 SuppressUserConversions = false;
3110 if (NumArgs == 1) {
3111 // If the first argument is (a reference to) the target type,
3112 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003113 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3114 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003115 }
3116 }
Douglas Gregordec06662009-08-21 18:42:58 +00003117 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003118 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3119 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003120 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003121 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003122 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003123 // Allow one user-defined conversion when user specifies a
3124 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003125 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003126 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003127 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003128 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003129 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003130 }
3131 }
3132
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003133 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003134 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003135 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003136 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003137 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003138 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003139 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003140 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3141 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003142 std::pair<CXXRecordDecl::conversion_iterator,
3143 CXXRecordDecl::conversion_iterator>
3144 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3145 for (CXXRecordDecl::conversion_iterator
3146 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003147 DeclAccessPair FoundDecl = I.getPair();
3148 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003149 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3150 if (isa<UsingShadowDecl>(D))
3151 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3152
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003153 CXXConversionDecl *Conv;
3154 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003155 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3156 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003157 else
John McCall32daa422010-03-31 01:36:47 +00003158 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003159
3160 if (AllowExplicit || !Conv->isExplicit()) {
3161 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003162 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3163 ActingContext, From, ToType,
3164 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003165 else
John McCall120d63c2010-08-24 20:38:10 +00003166 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3167 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003168 }
3169 }
3170 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003171 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003172
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3174
Douglas Gregor60d62c22008-10-31 16:23:19 +00003175 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003176 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003177 case OR_Success:
3178 // Record the standard conversion we used and the conversion function.
3179 if (CXXConstructorDecl *Constructor
3180 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3181 // C++ [over.ics.user]p1:
3182 // If the user-defined conversion is specified by a
3183 // constructor (12.3.1), the initial standard conversion
3184 // sequence converts the source type to the type required by
3185 // the argument of the constructor.
3186 //
3187 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003188 if (isa<InitListExpr>(From)) {
3189 // Initializer lists don't have conversions as such.
3190 User.Before.setAsIdentityConversion();
3191 } else {
3192 if (Best->Conversions[0].isEllipsis())
3193 User.EllipsisConversion = true;
3194 else {
3195 User.Before = Best->Conversions[0].Standard;
3196 User.EllipsisConversion = false;
3197 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003198 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003199 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003200 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003201 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003202 User.After.setAsIdentityConversion();
3203 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3204 User.After.setAllToTypes(ToType);
3205 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003206 }
3207 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003208 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3209 // C++ [over.ics.user]p1:
3210 //
3211 // [...] If the user-defined conversion is specified by a
3212 // conversion function (12.3.2), the initial standard
3213 // conversion sequence converts the source type to the
3214 // implicit object parameter of the conversion function.
3215 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003216 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003217 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003218 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003219 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003220
John McCall120d63c2010-08-24 20:38:10 +00003221 // C++ [over.ics.user]p2:
3222 // The second standard conversion sequence converts the
3223 // result of the user-defined conversion to the target type
3224 // for the sequence. Since an implicit conversion sequence
3225 // is an initialization, the special rules for
3226 // initialization by user-defined conversion apply when
3227 // selecting the best user-defined conversion for a
3228 // user-defined conversion sequence (see 13.3.3 and
3229 // 13.3.3.1).
3230 User.After = Best->FinalConversion;
3231 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003232 }
David Blaikie7530c032012-01-17 06:56:22 +00003233 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003234
John McCall120d63c2010-08-24 20:38:10 +00003235 case OR_No_Viable_Function:
3236 return OR_No_Viable_Function;
3237 case OR_Deleted:
3238 // No conversion here! We're done.
3239 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003240
John McCall120d63c2010-08-24 20:38:10 +00003241 case OR_Ambiguous:
3242 return OR_Ambiguous;
3243 }
3244
David Blaikie7530c032012-01-17 06:56:22 +00003245 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003246}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003247
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003248bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003249Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003250 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003251 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003252 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003253 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003254 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003255 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003256 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003257 diag::err_typecheck_ambiguous_condition)
3258 << From->getType() << ToType << From->getSourceRange();
3259 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003260 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003261 diag::err_typecheck_nonviable_condition)
3262 << From->getType() << ToType << From->getSourceRange();
3263 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003264 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003266 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003267}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003268
Douglas Gregorb734e242012-02-22 17:32:19 +00003269/// \brief Compare the user-defined conversion functions or constructors
3270/// of two user-defined conversion sequences to determine whether any ordering
3271/// is possible.
3272static ImplicitConversionSequence::CompareKind
3273compareConversionFunctions(Sema &S,
3274 FunctionDecl *Function1,
3275 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003276 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003277 return ImplicitConversionSequence::Indistinguishable;
3278
3279 // Objective-C++:
3280 // If both conversion functions are implicitly-declared conversions from
3281 // a lambda closure type to a function pointer and a block pointer,
3282 // respectively, always prefer the conversion to a function pointer,
3283 // because the function pointer is more lightweight and is more likely
3284 // to keep code working.
3285 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3286 if (!Conv1)
3287 return ImplicitConversionSequence::Indistinguishable;
3288
3289 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3290 if (!Conv2)
3291 return ImplicitConversionSequence::Indistinguishable;
3292
3293 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3294 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3295 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3296 if (Block1 != Block2)
3297 return Block1? ImplicitConversionSequence::Worse
3298 : ImplicitConversionSequence::Better;
3299 }
3300
3301 return ImplicitConversionSequence::Indistinguishable;
3302}
3303
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003304/// CompareImplicitConversionSequences - Compare two implicit
3305/// conversion sequences to determine whether one is better than the
3306/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003307static ImplicitConversionSequence::CompareKind
3308CompareImplicitConversionSequences(Sema &S,
3309 const ImplicitConversionSequence& ICS1,
3310 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003311{
3312 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3313 // conversion sequences (as defined in 13.3.3.1)
3314 // -- a standard conversion sequence (13.3.3.1.1) is a better
3315 // conversion sequence than a user-defined conversion sequence or
3316 // an ellipsis conversion sequence, and
3317 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3318 // conversion sequence than an ellipsis conversion sequence
3319 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003320 //
John McCall1d318332010-01-12 00:44:57 +00003321 // C++0x [over.best.ics]p10:
3322 // For the purpose of ranking implicit conversion sequences as
3323 // described in 13.3.3.2, the ambiguous conversion sequence is
3324 // treated as a user-defined sequence that is indistinguishable
3325 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003326 if (ICS1.getKindRank() < ICS2.getKindRank())
3327 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003328 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003329 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003330
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003331 // The following checks require both conversion sequences to be of
3332 // the same kind.
3333 if (ICS1.getKind() != ICS2.getKind())
3334 return ImplicitConversionSequence::Indistinguishable;
3335
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003336 ImplicitConversionSequence::CompareKind Result =
3337 ImplicitConversionSequence::Indistinguishable;
3338
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003339 // Two implicit conversion sequences of the same form are
3340 // indistinguishable conversion sequences unless one of the
3341 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003342 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003343 Result = CompareStandardConversionSequences(S,
3344 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003345 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003346 // User-defined conversion sequence U1 is a better conversion
3347 // sequence than another user-defined conversion sequence U2 if
3348 // they contain the same user-defined conversion function or
3349 // constructor and if the second standard conversion sequence of
3350 // U1 is better than the second standard conversion sequence of
3351 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003352 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003354 Result = CompareStandardConversionSequences(S,
3355 ICS1.UserDefined.After,
3356 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003357 else
3358 Result = compareConversionFunctions(S,
3359 ICS1.UserDefined.ConversionFunction,
3360 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003361 }
3362
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003363 // List-initialization sequence L1 is a better conversion sequence than
3364 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3365 // for some X and L2 does not.
3366 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003367 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003368 ICS1.isListInitializationSequence() &&
3369 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003370 if (ICS1.isStdInitializerListElement() &&
3371 !ICS2.isStdInitializerListElement())
3372 return ImplicitConversionSequence::Better;
3373 if (!ICS1.isStdInitializerListElement() &&
3374 ICS2.isStdInitializerListElement())
3375 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003376 }
3377
3378 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003379}
3380
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003381static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3382 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3383 Qualifiers Quals;
3384 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003388 return Context.hasSameUnqualifiedType(T1, T2);
3389}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390
Douglas Gregorad323a82010-01-27 03:51:04 +00003391// Per 13.3.3.2p3, compare the given standard conversion sequences to
3392// determine if one is a proper subset of the other.
3393static ImplicitConversionSequence::CompareKind
3394compareStandardConversionSubsets(ASTContext &Context,
3395 const StandardConversionSequence& SCS1,
3396 const StandardConversionSequence& SCS2) {
3397 ImplicitConversionSequence::CompareKind Result
3398 = ImplicitConversionSequence::Indistinguishable;
3399
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003401 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003402 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3403 return ImplicitConversionSequence::Better;
3404 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3405 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Douglas Gregorad323a82010-01-27 03:51:04 +00003407 if (SCS1.Second != SCS2.Second) {
3408 if (SCS1.Second == ICK_Identity)
3409 Result = ImplicitConversionSequence::Better;
3410 else if (SCS2.Second == ICK_Identity)
3411 Result = ImplicitConversionSequence::Worse;
3412 else
3413 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003414 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003415 return ImplicitConversionSequence::Indistinguishable;
3416
3417 if (SCS1.Third == SCS2.Third) {
3418 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3419 : ImplicitConversionSequence::Indistinguishable;
3420 }
3421
3422 if (SCS1.Third == ICK_Identity)
3423 return Result == ImplicitConversionSequence::Worse
3424 ? ImplicitConversionSequence::Indistinguishable
3425 : ImplicitConversionSequence::Better;
3426
3427 if (SCS2.Third == ICK_Identity)
3428 return Result == ImplicitConversionSequence::Better
3429 ? ImplicitConversionSequence::Indistinguishable
3430 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431
Douglas Gregorad323a82010-01-27 03:51:04 +00003432 return ImplicitConversionSequence::Indistinguishable;
3433}
3434
Douglas Gregor440a4832011-01-26 14:52:12 +00003435/// \brief Determine whether one of the given reference bindings is better
3436/// than the other based on what kind of bindings they are.
3437static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3438 const StandardConversionSequence &SCS2) {
3439 // C++0x [over.ics.rank]p3b4:
3440 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3441 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003442 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003443 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003445 // reference*.
3446 //
3447 // FIXME: Rvalue references. We're going rogue with the above edits,
3448 // because the semantics in the current C++0x working paper (N3225 at the
3449 // time of this writing) break the standard definition of std::forward
3450 // and std::reference_wrapper when dealing with references to functions.
3451 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003452 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3453 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3454 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455
Douglas Gregor440a4832011-01-26 14:52:12 +00003456 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3457 SCS2.IsLvalueReference) ||
3458 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3459 !SCS2.IsLvalueReference);
3460}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003462/// CompareStandardConversionSequences - Compare two standard
3463/// conversion sequences to determine whether one is better than the
3464/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003465static ImplicitConversionSequence::CompareKind
3466CompareStandardConversionSequences(Sema &S,
3467 const StandardConversionSequence& SCS1,
3468 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003469{
3470 // Standard conversion sequence S1 is a better conversion sequence
3471 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3472
3473 // -- S1 is a proper subsequence of S2 (comparing the conversion
3474 // sequences in the canonical form defined by 13.3.3.1.1,
3475 // excluding any Lvalue Transformation; the identity conversion
3476 // sequence is considered to be a subsequence of any
3477 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003478 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003479 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003480 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003481
3482 // -- the rank of S1 is better than the rank of S2 (by the rules
3483 // defined below), or, if not that,
3484 ImplicitConversionRank Rank1 = SCS1.getRank();
3485 ImplicitConversionRank Rank2 = SCS2.getRank();
3486 if (Rank1 < Rank2)
3487 return ImplicitConversionSequence::Better;
3488 else if (Rank2 < Rank1)
3489 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003490
Douglas Gregor57373262008-10-22 14:17:15 +00003491 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3492 // are indistinguishable unless one of the following rules
3493 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Douglas Gregor57373262008-10-22 14:17:15 +00003495 // A conversion that is not a conversion of a pointer, or
3496 // pointer to member, to bool is better than another conversion
3497 // that is such a conversion.
3498 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3499 return SCS2.isPointerConversionToBool()
3500 ? ImplicitConversionSequence::Better
3501 : ImplicitConversionSequence::Worse;
3502
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003503 // C++ [over.ics.rank]p4b2:
3504 //
3505 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003506 // conversion of B* to A* is better than conversion of B* to
3507 // void*, and conversion of A* to void* is better than conversion
3508 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003509 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003510 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003511 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003512 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003513 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3514 // Exactly one of the conversion sequences is a conversion to
3515 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003516 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3517 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003518 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3519 // Neither conversion sequence converts to a void pointer; compare
3520 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003521 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003522 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003523 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003524 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3525 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003526 // Both conversion sequences are conversions to void
3527 // pointers. Compare the source types to determine if there's an
3528 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003529 QualType FromType1 = SCS1.getFromType();
3530 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003531
3532 // Adjust the types we're converting from via the array-to-pointer
3533 // conversion, if we need to.
3534 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003535 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003536 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003537 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003538
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003539 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3540 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003541
John McCall120d63c2010-08-24 20:38:10 +00003542 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003543 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003544 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003545 return ImplicitConversionSequence::Worse;
3546
3547 // Objective-C++: If one interface is more specific than the
3548 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003549 const ObjCObjectPointerType* FromObjCPtr1
3550 = FromType1->getAs<ObjCObjectPointerType>();
3551 const ObjCObjectPointerType* FromObjCPtr2
3552 = FromType2->getAs<ObjCObjectPointerType>();
3553 if (FromObjCPtr1 && FromObjCPtr2) {
3554 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3555 FromObjCPtr2);
3556 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3557 FromObjCPtr1);
3558 if (AssignLeft != AssignRight) {
3559 return AssignLeft? ImplicitConversionSequence::Better
3560 : ImplicitConversionSequence::Worse;
3561 }
Douglas Gregor01919692009-12-13 21:37:05 +00003562 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003563 }
Douglas Gregor57373262008-10-22 14:17:15 +00003564
3565 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3566 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003567 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003568 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003569 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003570
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003571 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003572 // Check for a better reference binding based on the kind of bindings.
3573 if (isBetterReferenceBindingKind(SCS1, SCS2))
3574 return ImplicitConversionSequence::Better;
3575 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3576 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003578 // C++ [over.ics.rank]p3b4:
3579 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3580 // which the references refer are the same type except for
3581 // top-level cv-qualifiers, and the type to which the reference
3582 // initialized by S2 refers is more cv-qualified than the type
3583 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003584 QualType T1 = SCS1.getToType(2);
3585 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003586 T1 = S.Context.getCanonicalType(T1);
3587 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003588 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003589 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3590 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003591 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003592 // Objective-C++ ARC: If the references refer to objects with different
3593 // lifetimes, prefer bindings that don't change lifetime.
3594 if (SCS1.ObjCLifetimeConversionBinding !=
3595 SCS2.ObjCLifetimeConversionBinding) {
3596 return SCS1.ObjCLifetimeConversionBinding
3597 ? ImplicitConversionSequence::Worse
3598 : ImplicitConversionSequence::Better;
3599 }
3600
Chandler Carruth6df868e2010-12-12 08:17:55 +00003601 // If the type is an array type, promote the element qualifiers to the
3602 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003603 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003604 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003605 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003606 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003607 if (T2.isMoreQualifiedThan(T1))
3608 return ImplicitConversionSequence::Better;
3609 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003610 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003611 }
3612 }
Douglas Gregor57373262008-10-22 14:17:15 +00003613
Francois Pichet1c98d622011-09-18 21:37:37 +00003614 // In Microsoft mode, prefer an integral conversion to a
3615 // floating-to-integral conversion if the integral conversion
3616 // is between types of the same size.
3617 // For example:
3618 // void f(float);
3619 // void f(int);
3620 // int main {
3621 // long a;
3622 // f(a);
3623 // }
3624 // Here, MSVC will call f(int) instead of generating a compile error
3625 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003626 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003627 SCS1.Second == ICK_Integral_Conversion &&
3628 SCS2.Second == ICK_Floating_Integral &&
3629 S.Context.getTypeSize(SCS1.getFromType()) ==
3630 S.Context.getTypeSize(SCS1.getToType(2)))
3631 return ImplicitConversionSequence::Better;
3632
Douglas Gregor57373262008-10-22 14:17:15 +00003633 return ImplicitConversionSequence::Indistinguishable;
3634}
3635
3636/// CompareQualificationConversions - Compares two standard conversion
3637/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003638/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3639ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003640CompareQualificationConversions(Sema &S,
3641 const StandardConversionSequence& SCS1,
3642 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003643 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003644 // -- S1 and S2 differ only in their qualification conversion and
3645 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3646 // cv-qualification signature of type T1 is a proper subset of
3647 // the cv-qualification signature of type T2, and S1 is not the
3648 // deprecated string literal array-to-pointer conversion (4.2).
3649 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3650 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3651 return ImplicitConversionSequence::Indistinguishable;
3652
3653 // FIXME: the example in the standard doesn't use a qualification
3654 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003655 QualType T1 = SCS1.getToType(2);
3656 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003657 T1 = S.Context.getCanonicalType(T1);
3658 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003659 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003660 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3661 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003662
3663 // If the types are the same, we won't learn anything by unwrapped
3664 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003665 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003666 return ImplicitConversionSequence::Indistinguishable;
3667
Chandler Carruth28e318c2009-12-29 07:16:59 +00003668 // If the type is an array type, promote the element qualifiers to the type
3669 // for comparison.
3670 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003671 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003672 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003673 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003674
Mike Stump1eb44332009-09-09 15:08:12 +00003675 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003676 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003677
3678 // Objective-C++ ARC:
3679 // Prefer qualification conversions not involving a change in lifetime
3680 // to qualification conversions that do not change lifetime.
3681 if (SCS1.QualificationIncludesObjCLifetime !=
3682 SCS2.QualificationIncludesObjCLifetime) {
3683 Result = SCS1.QualificationIncludesObjCLifetime
3684 ? ImplicitConversionSequence::Worse
3685 : ImplicitConversionSequence::Better;
3686 }
3687
John McCall120d63c2010-08-24 20:38:10 +00003688 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003689 // Within each iteration of the loop, we check the qualifiers to
3690 // determine if this still looks like a qualification
3691 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003692 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003693 // until there are no more pointers or pointers-to-members left
3694 // to unwrap. This essentially mimics what
3695 // IsQualificationConversion does, but here we're checking for a
3696 // strict subset of qualifiers.
3697 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3698 // The qualifiers are the same, so this doesn't tell us anything
3699 // about how the sequences rank.
3700 ;
3701 else if (T2.isMoreQualifiedThan(T1)) {
3702 // T1 has fewer qualifiers, so it could be the better sequence.
3703 if (Result == ImplicitConversionSequence::Worse)
3704 // Neither has qualifiers that are a subset of the other's
3705 // qualifiers.
3706 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Douglas Gregor57373262008-10-22 14:17:15 +00003708 Result = ImplicitConversionSequence::Better;
3709 } else if (T1.isMoreQualifiedThan(T2)) {
3710 // T2 has fewer qualifiers, so it could be the better sequence.
3711 if (Result == ImplicitConversionSequence::Better)
3712 // Neither has qualifiers that are a subset of the other's
3713 // qualifiers.
3714 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Douglas Gregor57373262008-10-22 14:17:15 +00003716 Result = ImplicitConversionSequence::Worse;
3717 } else {
3718 // Qualifiers are disjoint.
3719 return ImplicitConversionSequence::Indistinguishable;
3720 }
3721
3722 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003723 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003724 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003725 }
3726
Douglas Gregor57373262008-10-22 14:17:15 +00003727 // Check that the winning standard conversion sequence isn't using
3728 // the deprecated string literal array to pointer conversion.
3729 switch (Result) {
3730 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003731 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003732 Result = ImplicitConversionSequence::Indistinguishable;
3733 break;
3734
3735 case ImplicitConversionSequence::Indistinguishable:
3736 break;
3737
3738 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003739 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003740 Result = ImplicitConversionSequence::Indistinguishable;
3741 break;
3742 }
3743
3744 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003745}
3746
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003747/// CompareDerivedToBaseConversions - Compares two standard conversion
3748/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003749/// various kinds of derived-to-base conversions (C++
3750/// [over.ics.rank]p4b3). As part of these checks, we also look at
3751/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003753CompareDerivedToBaseConversions(Sema &S,
3754 const StandardConversionSequence& SCS1,
3755 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003756 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003757 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003758 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003759 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003760
3761 // Adjust the types we're converting from via the array-to-pointer
3762 // conversion, if we need to.
3763 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003764 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003765 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003766 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003767
3768 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003769 FromType1 = S.Context.getCanonicalType(FromType1);
3770 ToType1 = S.Context.getCanonicalType(ToType1);
3771 FromType2 = S.Context.getCanonicalType(FromType2);
3772 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003773
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003774 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003775 //
3776 // If class B is derived directly or indirectly from class A and
3777 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003778 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003779 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003780 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003781 SCS2.Second == ICK_Pointer_Conversion &&
3782 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3783 FromType1->isPointerType() && FromType2->isPointerType() &&
3784 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003785 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003787 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003789 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003790 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003791 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003792 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003793
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003794 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003795 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003796 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003797 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003798 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003799 return ImplicitConversionSequence::Worse;
3800 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003801
3802 // -- conversion of B* to A* is better than conversion of C* to A*,
3803 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003804 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003805 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003806 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003807 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003808 }
3809 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3810 SCS2.Second == ICK_Pointer_Conversion) {
3811 const ObjCObjectPointerType *FromPtr1
3812 = FromType1->getAs<ObjCObjectPointerType>();
3813 const ObjCObjectPointerType *FromPtr2
3814 = FromType2->getAs<ObjCObjectPointerType>();
3815 const ObjCObjectPointerType *ToPtr1
3816 = ToType1->getAs<ObjCObjectPointerType>();
3817 const ObjCObjectPointerType *ToPtr2
3818 = ToType2->getAs<ObjCObjectPointerType>();
3819
3820 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3821 // Apply the same conversion ranking rules for Objective-C pointer types
3822 // that we do for C++ pointers to class types. However, we employ the
3823 // Objective-C pseudo-subtyping relationship used for assignment of
3824 // Objective-C pointer types.
3825 bool FromAssignLeft
3826 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3827 bool FromAssignRight
3828 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3829 bool ToAssignLeft
3830 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3831 bool ToAssignRight
3832 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3833
3834 // A conversion to an a non-id object pointer type or qualified 'id'
3835 // type is better than a conversion to 'id'.
3836 if (ToPtr1->isObjCIdType() &&
3837 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3838 return ImplicitConversionSequence::Worse;
3839 if (ToPtr2->isObjCIdType() &&
3840 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3841 return ImplicitConversionSequence::Better;
3842
3843 // A conversion to a non-id object pointer type is better than a
3844 // conversion to a qualified 'id' type
3845 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3846 return ImplicitConversionSequence::Worse;
3847 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3848 return ImplicitConversionSequence::Better;
3849
3850 // A conversion to an a non-Class object pointer type or qualified 'Class'
3851 // type is better than a conversion to 'Class'.
3852 if (ToPtr1->isObjCClassType() &&
3853 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3854 return ImplicitConversionSequence::Worse;
3855 if (ToPtr2->isObjCClassType() &&
3856 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3857 return ImplicitConversionSequence::Better;
3858
3859 // A conversion to a non-Class object pointer type is better than a
3860 // conversion to a qualified 'Class' type.
3861 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3862 return ImplicitConversionSequence::Worse;
3863 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3864 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Douglas Gregor395cc372011-01-31 18:51:41 +00003866 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3867 if (S.Context.hasSameType(FromType1, FromType2) &&
3868 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3869 (ToAssignLeft != ToAssignRight))
3870 return ToAssignLeft? ImplicitConversionSequence::Worse
3871 : ImplicitConversionSequence::Better;
3872
3873 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3874 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3875 (FromAssignLeft != FromAssignRight))
3876 return FromAssignLeft? ImplicitConversionSequence::Better
3877 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003878 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003879 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003880
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003881 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003882 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3883 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3884 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003886 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003888 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003890 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003892 ToType2->getAs<MemberPointerType>();
3893 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3894 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3895 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3896 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3897 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3898 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3899 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3900 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003901 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003902 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003903 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003904 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003905 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003906 return ImplicitConversionSequence::Better;
3907 }
3908 // conversion of B::* to C::* is better than conversion of A::* to C::*
3909 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003910 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003911 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003912 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003913 return ImplicitConversionSequence::Worse;
3914 }
3915 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003917 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003918 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003919 // -- binding of an expression of type C to a reference of type
3920 // B& is better than binding an expression of type C to a
3921 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003922 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003925 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003926 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Worse;
3928 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003929
Douglas Gregor225c41e2008-11-03 19:09:14 +00003930 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003931 // -- binding of an expression of type B to a reference of type
3932 // A& is better than binding an expression of type C to a
3933 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003934 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3935 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3936 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003937 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003938 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003939 return ImplicitConversionSequence::Worse;
3940 }
3941 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003942
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003943 return ImplicitConversionSequence::Indistinguishable;
3944}
3945
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003946/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3947/// C++ class.
3948static bool isTypeValid(QualType T) {
3949 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3950 return !Record->isInvalidDecl();
3951
3952 return true;
3953}
3954
Douglas Gregorabe183d2010-04-13 16:31:36 +00003955/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3956/// determine whether they are reference-related,
3957/// reference-compatible, reference-compatible with added
3958/// qualification, or incompatible, for use in C++ initialization by
3959/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3960/// type, and the first type (T1) is the pointee type of the reference
3961/// type being initialized.
3962Sema::ReferenceCompareResult
3963Sema::CompareReferenceRelationship(SourceLocation Loc,
3964 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003965 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003966 bool &ObjCConversion,
3967 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003968 assert(!OrigT1->isReferenceType() &&
3969 "T1 must be the pointee type of the reference type");
3970 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3971
3972 QualType T1 = Context.getCanonicalType(OrigT1);
3973 QualType T2 = Context.getCanonicalType(OrigT2);
3974 Qualifiers T1Quals, T2Quals;
3975 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3976 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3977
3978 // C++ [dcl.init.ref]p4:
3979 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3980 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3981 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003982 DerivedToBase = false;
3983 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003984 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003985 if (UnqualT1 == UnqualT2) {
3986 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003987 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003988 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3989 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003990 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003991 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3992 UnqualT2->isObjCObjectOrInterfaceType() &&
3993 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3994 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003995 else
3996 return Ref_Incompatible;
3997
3998 // At this point, we know that T1 and T2 are reference-related (at
3999 // least).
4000
4001 // If the type is an array type, promote the element qualifiers to the type
4002 // for comparison.
4003 if (isa<ArrayType>(T1) && T1Quals)
4004 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4005 if (isa<ArrayType>(T2) && T2Quals)
4006 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4007
4008 // C++ [dcl.init.ref]p4:
4009 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4010 // reference-related to T2 and cv1 is the same cv-qualification
4011 // as, or greater cv-qualification than, cv2. For purposes of
4012 // overload resolution, cases for which cv1 is greater
4013 // cv-qualification than cv2 are identified as
4014 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004015 //
4016 // Note that we also require equivalence of Objective-C GC and address-space
4017 // qualifiers when performing these computations, so that e.g., an int in
4018 // address space 1 is not reference-compatible with an int in address
4019 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004020 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4021 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4022 T1Quals.removeObjCLifetime();
4023 T2Quals.removeObjCLifetime();
4024 ObjCLifetimeConversion = true;
4025 }
4026
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004027 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004028 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004029 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004030 return Ref_Compatible_With_Added_Qualification;
4031 else
4032 return Ref_Related;
4033}
4034
Douglas Gregor604eb652010-08-11 02:15:33 +00004035/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004036/// with DeclType. Return true if something definite is found.
4037static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004038FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4039 QualType DeclType, SourceLocation DeclLoc,
4040 Expr *Init, QualType T2, bool AllowRvalues,
4041 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004042 assert(T2->isRecordType() && "Can only find conversions of record types.");
4043 CXXRecordDecl *T2RecordDecl
4044 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4045
4046 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004047 std::pair<CXXRecordDecl::conversion_iterator,
4048 CXXRecordDecl::conversion_iterator>
4049 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4050 for (CXXRecordDecl::conversion_iterator
4051 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004052 NamedDecl *D = *I;
4053 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4054 if (isa<UsingShadowDecl>(D))
4055 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4056
4057 FunctionTemplateDecl *ConvTemplate
4058 = dyn_cast<FunctionTemplateDecl>(D);
4059 CXXConversionDecl *Conv;
4060 if (ConvTemplate)
4061 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4062 else
4063 Conv = cast<CXXConversionDecl>(D);
4064
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004066 // explicit conversions, skip it.
4067 if (!AllowExplicit && Conv->isExplicit())
4068 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069
Douglas Gregor604eb652010-08-11 02:15:33 +00004070 if (AllowRvalues) {
4071 bool DerivedToBase = false;
4072 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004073 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004074
4075 // If we are initializing an rvalue reference, don't permit conversion
4076 // functions that return lvalues.
4077 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4078 const ReferenceType *RefType
4079 = Conv->getConversionType()->getAs<LValueReferenceType>();
4080 if (RefType && !RefType->getPointeeType()->isFunctionType())
4081 continue;
4082 }
4083
Douglas Gregor604eb652010-08-11 02:15:33 +00004084 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004085 S.CompareReferenceRelationship(
4086 DeclLoc,
4087 Conv->getConversionType().getNonReferenceType()
4088 .getUnqualifiedType(),
4089 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004090 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004091 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004092 continue;
4093 } else {
4094 // If the conversion function doesn't return a reference type,
4095 // it can't be considered for this conversion. An rvalue reference
4096 // is only acceptable if its referencee is a function type.
4097
4098 const ReferenceType *RefType =
4099 Conv->getConversionType()->getAs<ReferenceType>();
4100 if (!RefType ||
4101 (!RefType->isLValueReferenceType() &&
4102 !RefType->getPointeeType()->isFunctionType()))
4103 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105
Douglas Gregor604eb652010-08-11 02:15:33 +00004106 if (ConvTemplate)
4107 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004108 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004109 else
4110 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004111 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004112 }
4113
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004114 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4115
Sebastian Redl4680bf22010-06-30 18:13:39 +00004116 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004117 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004118 case OR_Success:
4119 // C++ [over.ics.ref]p1:
4120 //
4121 // [...] If the parameter binds directly to the result of
4122 // applying a conversion function to the argument
4123 // expression, the implicit conversion sequence is a
4124 // user-defined conversion sequence (13.3.3.1.2), with the
4125 // second standard conversion sequence either an identity
4126 // conversion or, if the conversion function returns an
4127 // entity of a type that is a derived class of the parameter
4128 // type, a derived-to-base Conversion.
4129 if (!Best->FinalConversion.DirectBinding)
4130 return false;
4131
4132 ICS.setUserDefined();
4133 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4134 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004135 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004136 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004137 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004138 ICS.UserDefined.EllipsisConversion = false;
4139 assert(ICS.UserDefined.After.ReferenceBinding &&
4140 ICS.UserDefined.After.DirectBinding &&
4141 "Expected a direct reference binding!");
4142 return true;
4143
4144 case OR_Ambiguous:
4145 ICS.setAmbiguous();
4146 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4147 Cand != CandidateSet.end(); ++Cand)
4148 if (Cand->Viable)
4149 ICS.Ambiguous.addConversion(Cand->Function);
4150 return true;
4151
4152 case OR_No_Viable_Function:
4153 case OR_Deleted:
4154 // There was no suitable conversion, or we found a deleted
4155 // conversion; continue with other checks.
4156 return false;
4157 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004158
David Blaikie7530c032012-01-17 06:56:22 +00004159 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004160}
4161
Douglas Gregorabe183d2010-04-13 16:31:36 +00004162/// \brief Compute an implicit conversion sequence for reference
4163/// initialization.
4164static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004165TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004166 SourceLocation DeclLoc,
4167 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004168 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004169 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4170
4171 // Most paths end in a failed conversion.
4172 ImplicitConversionSequence ICS;
4173 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4174
4175 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4176 QualType T2 = Init->getType();
4177
4178 // If the initializer is the address of an overloaded function, try
4179 // to resolve the overloaded function. If all goes well, T2 is the
4180 // type of the resulting function.
4181 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4182 DeclAccessPair Found;
4183 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4184 false, Found))
4185 T2 = Fn->getType();
4186 }
4187
4188 // Compute some basic properties of the types and the initializer.
4189 bool isRValRef = DeclType->isRValueReferenceType();
4190 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004191 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004192 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004193 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004194 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004195 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004196 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004197
Douglas Gregorabe183d2010-04-13 16:31:36 +00004198
Sebastian Redl4680bf22010-06-30 18:13:39 +00004199 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004200 // A reference to type "cv1 T1" is initialized by an expression
4201 // of type "cv2 T2" as follows:
4202
Sebastian Redl4680bf22010-06-30 18:13:39 +00004203 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004204 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004205 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4206 // reference-compatible with "cv2 T2," or
4207 //
4208 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4209 if (InitCategory.isLValue() &&
4210 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004211 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004212 // When a parameter of reference type binds directly (8.5.3)
4213 // to an argument expression, the implicit conversion sequence
4214 // is the identity conversion, unless the argument expression
4215 // has a type that is a derived class of the parameter type,
4216 // in which case the implicit conversion sequence is a
4217 // derived-to-base Conversion (13.3.3.1).
4218 ICS.setStandard();
4219 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004220 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4221 : ObjCConversion? ICK_Compatible_Conversion
4222 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004223 ICS.Standard.Third = ICK_Identity;
4224 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4225 ICS.Standard.setToType(0, T2);
4226 ICS.Standard.setToType(1, T1);
4227 ICS.Standard.setToType(2, T1);
4228 ICS.Standard.ReferenceBinding = true;
4229 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004230 ICS.Standard.IsLvalueReference = !isRValRef;
4231 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4232 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004233 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004234 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004235 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004236
Sebastian Redl4680bf22010-06-30 18:13:39 +00004237 // Nothing more to do: the inaccessibility/ambiguity check for
4238 // derived-to-base conversions is suppressed when we're
4239 // computing the implicit conversion sequence (C++
4240 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004241 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004242 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004243
Sebastian Redl4680bf22010-06-30 18:13:39 +00004244 // -- has a class type (i.e., T2 is a class type), where T1 is
4245 // not reference-related to T2, and can be implicitly
4246 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4247 // is reference-compatible with "cv3 T3" 92) (this
4248 // conversion is selected by enumerating the applicable
4249 // conversion functions (13.3.1.6) and choosing the best
4250 // one through overload resolution (13.3)),
4251 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004252 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004253 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004254 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4255 Init, T2, /*AllowRvalues=*/false,
4256 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004257 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004258 }
4259 }
4260
Sebastian Redl4680bf22010-06-30 18:13:39 +00004261 // -- Otherwise, the reference shall be an lvalue reference to a
4262 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004263 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004264 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004265 // We actually handle one oddity of C++ [over.ics.ref] at this
4266 // point, which is that, due to p2 (which short-circuits reference
4267 // binding by only attempting a simple conversion for non-direct
4268 // bindings) and p3's strange wording, we allow a const volatile
4269 // reference to bind to an rvalue. Hence the check for the presence
4270 // of "const" rather than checking for "const" being the only
4271 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004272 // This is also the point where rvalue references and lvalue inits no longer
4273 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004274 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004275 return ICS;
4276
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004277 // -- If the initializer expression
4278 //
4279 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004280 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004281 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4282 (InitCategory.isXValue() ||
4283 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4284 (InitCategory.isLValue() && T2->isFunctionType()))) {
4285 ICS.setStandard();
4286 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004288 : ObjCConversion? ICK_Compatible_Conversion
4289 : ICK_Identity;
4290 ICS.Standard.Third = ICK_Identity;
4291 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4292 ICS.Standard.setToType(0, T2);
4293 ICS.Standard.setToType(1, T1);
4294 ICS.Standard.setToType(2, T1);
4295 ICS.Standard.ReferenceBinding = true;
4296 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4297 // binding unless we're binding to a class prvalue.
4298 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4299 // allow the use of rvalue references in C++98/03 for the benefit of
4300 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004302 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004303 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004304 ICS.Standard.IsLvalueReference = !isRValRef;
4305 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004307 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004308 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004309 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004310 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004313 // -- has a class type (i.e., T2 is a class type), where T1 is not
4314 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315 // an xvalue, class prvalue, or function lvalue of type
4316 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004317 // "cv3 T3",
4318 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004320 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004321 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004322 // class subobject).
4323 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004325 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4326 Init, T2, /*AllowRvalues=*/true,
4327 AllowExplicit)) {
4328 // In the second case, if the reference is an rvalue reference
4329 // and the second standard conversion sequence of the
4330 // user-defined conversion sequence includes an lvalue-to-rvalue
4331 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004333 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4334 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4335
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004336 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004337 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004338
Douglas Gregorabe183d2010-04-13 16:31:36 +00004339 // -- Otherwise, a temporary of type "cv1 T1" is created and
4340 // initialized from the initializer expression using the
4341 // rules for a non-reference copy initialization (8.5). The
4342 // reference is then bound to the temporary. If T1 is
4343 // reference-related to T2, cv1 must be the same
4344 // cv-qualification as, or greater cv-qualification than,
4345 // cv2; otherwise, the program is ill-formed.
4346 if (RefRelationship == Sema::Ref_Related) {
4347 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4348 // we would be reference-compatible or reference-compatible with
4349 // added qualification. But that wasn't the case, so the reference
4350 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004351 //
4352 // Note that we only want to check address spaces and cvr-qualifiers here.
4353 // ObjC GC and lifetime qualifiers aren't important.
4354 Qualifiers T1Quals = T1.getQualifiers();
4355 Qualifiers T2Quals = T2.getQualifiers();
4356 T1Quals.removeObjCGCAttr();
4357 T1Quals.removeObjCLifetime();
4358 T2Quals.removeObjCGCAttr();
4359 T2Quals.removeObjCLifetime();
4360 if (!T1Quals.compatiblyIncludes(T2Quals))
4361 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004362 }
4363
4364 // If at least one of the types is a class type, the types are not
4365 // related, and we aren't allowed any user conversions, the
4366 // reference binding fails. This case is important for breaking
4367 // recursion, since TryImplicitConversion below will attempt to
4368 // create a temporary through the use of a copy constructor.
4369 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4370 (T1->isRecordType() || T2->isRecordType()))
4371 return ICS;
4372
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004373 // If T1 is reference-related to T2 and the reference is an rvalue
4374 // reference, the initializer expression shall not be an lvalue.
4375 if (RefRelationship >= Sema::Ref_Related &&
4376 isRValRef && Init->Classify(S.Context).isLValue())
4377 return ICS;
4378
Douglas Gregorabe183d2010-04-13 16:31:36 +00004379 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004380 // When a parameter of reference type is not bound directly to
4381 // an argument expression, the conversion sequence is the one
4382 // required to convert the argument expression to the
4383 // underlying type of the reference according to
4384 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4385 // to copy-initializing a temporary of the underlying type with
4386 // the argument expression. Any difference in top-level
4387 // cv-qualification is subsumed by the initialization itself
4388 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004389 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4390 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004391 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004392 /*CStyle=*/false,
4393 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004394
4395 // Of course, that's still a reference binding.
4396 if (ICS.isStandard()) {
4397 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004398 ICS.Standard.IsLvalueReference = !isRValRef;
4399 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4400 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004401 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004402 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004403 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004404 // Don't allow rvalue references to bind to lvalues.
4405 if (DeclType->isRValueReferenceType()) {
4406 if (const ReferenceType *RefType
4407 = ICS.UserDefined.ConversionFunction->getResultType()
4408 ->getAs<LValueReferenceType>()) {
4409 if (!RefType->getPointeeType()->isFunctionType()) {
4410 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4411 DeclType);
4412 return ICS;
4413 }
4414 }
4415 }
4416
Douglas Gregorabe183d2010-04-13 16:31:36 +00004417 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004418 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4419 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4420 ICS.UserDefined.After.BindsToRvalue = true;
4421 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4422 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004423 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004424
Douglas Gregorabe183d2010-04-13 16:31:36 +00004425 return ICS;
4426}
4427
Sebastian Redl5405b812011-10-16 18:19:34 +00004428static ImplicitConversionSequence
4429TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4430 bool SuppressUserConversions,
4431 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004432 bool AllowObjCWritebackConversion,
4433 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004434
4435/// TryListConversion - Try to copy-initialize a value of type ToType from the
4436/// initializer list From.
4437static ImplicitConversionSequence
4438TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4439 bool SuppressUserConversions,
4440 bool InOverloadResolution,
4441 bool AllowObjCWritebackConversion) {
4442 // C++11 [over.ics.list]p1:
4443 // When an argument is an initializer list, it is not an expression and
4444 // special rules apply for converting it to a parameter type.
4445
4446 ImplicitConversionSequence Result;
4447 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004448 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004449
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004450 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004451 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004452 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004453 return Result;
4454
Sebastian Redl5405b812011-10-16 18:19:34 +00004455 // C++11 [over.ics.list]p2:
4456 // If the parameter type is std::initializer_list<X> or "array of X" and
4457 // all the elements can be implicitly converted to X, the implicit
4458 // conversion sequence is the worst conversion necessary to convert an
4459 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004460 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004461 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004462 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004463 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004464 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004465 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004466 if (!X.isNull()) {
4467 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4468 Expr *Init = From->getInit(i);
4469 ImplicitConversionSequence ICS =
4470 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4471 InOverloadResolution,
4472 AllowObjCWritebackConversion);
4473 // If a single element isn't convertible, fail.
4474 if (ICS.isBad()) {
4475 Result = ICS;
4476 break;
4477 }
4478 // Otherwise, look for the worst conversion.
4479 if (Result.isBad() ||
4480 CompareImplicitConversionSequences(S, ICS, Result) ==
4481 ImplicitConversionSequence::Worse)
4482 Result = ICS;
4483 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004484
4485 // For an empty list, we won't have computed any conversion sequence.
4486 // Introduce the identity conversion sequence.
4487 if (From->getNumInits() == 0) {
4488 Result.setStandard();
4489 Result.Standard.setAsIdentityConversion();
4490 Result.Standard.setFromType(ToType);
4491 Result.Standard.setAllToTypes(ToType);
4492 }
4493
Sebastian Redlfe592282012-01-17 22:49:48 +00004494 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004495 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004496 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004497 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004498
4499 // C++11 [over.ics.list]p3:
4500 // Otherwise, if the parameter is a non-aggregate class X and overload
4501 // resolution chooses a single best constructor [...] the implicit
4502 // conversion sequence is a user-defined conversion sequence. If multiple
4503 // constructors are viable but none is better than the others, the
4504 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004505 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4506 // This function can deal with initializer lists.
4507 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4508 /*AllowExplicit=*/false,
4509 InOverloadResolution, /*CStyle=*/false,
4510 AllowObjCWritebackConversion);
4511 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004512 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004513 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004514
4515 // C++11 [over.ics.list]p4:
4516 // Otherwise, if the parameter has an aggregate type which can be
4517 // initialized from the initializer list [...] the implicit conversion
4518 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004519 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004520 // Type is an aggregate, argument is an init list. At this point it comes
4521 // down to checking whether the initialization works.
4522 // FIXME: Find out whether this parameter is consumed or not.
4523 InitializedEntity Entity =
4524 InitializedEntity::InitializeParameter(S.Context, ToType,
4525 /*Consumed=*/false);
4526 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4527 Result.setUserDefined();
4528 Result.UserDefined.Before.setAsIdentityConversion();
4529 // Initializer lists don't have a type.
4530 Result.UserDefined.Before.setFromType(QualType());
4531 Result.UserDefined.Before.setAllToTypes(QualType());
4532
4533 Result.UserDefined.After.setAsIdentityConversion();
4534 Result.UserDefined.After.setFromType(ToType);
4535 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004536 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004537 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004538 return Result;
4539 }
4540
4541 // C++11 [over.ics.list]p5:
4542 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004543 if (ToType->isReferenceType()) {
4544 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4545 // mention initializer lists in any way. So we go by what list-
4546 // initialization would do and try to extrapolate from that.
4547
4548 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4549
4550 // If the initializer list has a single element that is reference-related
4551 // to the parameter type, we initialize the reference from that.
4552 if (From->getNumInits() == 1) {
4553 Expr *Init = From->getInit(0);
4554
4555 QualType T2 = Init->getType();
4556
4557 // If the initializer is the address of an overloaded function, try
4558 // to resolve the overloaded function. If all goes well, T2 is the
4559 // type of the resulting function.
4560 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4561 DeclAccessPair Found;
4562 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4563 Init, ToType, false, Found))
4564 T2 = Fn->getType();
4565 }
4566
4567 // Compute some basic properties of the types and the initializer.
4568 bool dummy1 = false;
4569 bool dummy2 = false;
4570 bool dummy3 = false;
4571 Sema::ReferenceCompareResult RefRelationship
4572 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4573 dummy2, dummy3);
4574
4575 if (RefRelationship >= Sema::Ref_Related)
4576 return TryReferenceInit(S, Init, ToType,
4577 /*FIXME:*/From->getLocStart(),
4578 SuppressUserConversions,
4579 /*AllowExplicit=*/false);
4580 }
4581
4582 // Otherwise, we bind the reference to a temporary created from the
4583 // initializer list.
4584 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4585 InOverloadResolution,
4586 AllowObjCWritebackConversion);
4587 if (Result.isFailure())
4588 return Result;
4589 assert(!Result.isEllipsis() &&
4590 "Sub-initialization cannot result in ellipsis conversion.");
4591
4592 // Can we even bind to a temporary?
4593 if (ToType->isRValueReferenceType() ||
4594 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4595 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4596 Result.UserDefined.After;
4597 SCS.ReferenceBinding = true;
4598 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4599 SCS.BindsToRvalue = true;
4600 SCS.BindsToFunctionLvalue = false;
4601 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4602 SCS.ObjCLifetimeConversionBinding = false;
4603 } else
4604 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4605 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004606 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004607 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004608
4609 // C++11 [over.ics.list]p6:
4610 // Otherwise, if the parameter type is not a class:
4611 if (!ToType->isRecordType()) {
4612 // - if the initializer list has one element, the implicit conversion
4613 // sequence is the one required to convert the element to the
4614 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004615 unsigned NumInits = From->getNumInits();
4616 if (NumInits == 1)
4617 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4618 SuppressUserConversions,
4619 InOverloadResolution,
4620 AllowObjCWritebackConversion);
4621 // - if the initializer list has no elements, the implicit conversion
4622 // sequence is the identity conversion.
4623 else if (NumInits == 0) {
4624 Result.setStandard();
4625 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004626 Result.Standard.setFromType(ToType);
4627 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004628 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004629 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004630 return Result;
4631 }
4632
4633 // C++11 [over.ics.list]p7:
4634 // In all cases other than those enumerated above, no conversion is possible
4635 return Result;
4636}
4637
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004638/// TryCopyInitialization - Try to copy-initialize a value of type
4639/// ToType from the expression From. Return the implicit conversion
4640/// sequence required to pass this argument, which may be a bad
4641/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004642/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004643/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004644static ImplicitConversionSequence
4645TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004646 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004647 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004648 bool AllowObjCWritebackConversion,
4649 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004650 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4651 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4652 InOverloadResolution,AllowObjCWritebackConversion);
4653
Douglas Gregorabe183d2010-04-13 16:31:36 +00004654 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004655 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004656 /*FIXME:*/From->getLocStart(),
4657 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004658 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004659
John McCall120d63c2010-08-24 20:38:10 +00004660 return TryImplicitConversion(S, From, ToType,
4661 SuppressUserConversions,
4662 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004663 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004664 /*CStyle=*/false,
4665 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004666}
4667
Anna Zaksf3546ee2011-07-28 19:46:48 +00004668static bool TryCopyInitialization(const CanQualType FromQTy,
4669 const CanQualType ToQTy,
4670 Sema &S,
4671 SourceLocation Loc,
4672 ExprValueKind FromVK) {
4673 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4674 ImplicitConversionSequence ICS =
4675 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4676
4677 return !ICS.isBad();
4678}
4679
Douglas Gregor96176b32008-11-18 23:14:02 +00004680/// TryObjectArgumentInitialization - Try to initialize the object
4681/// parameter of the given member function (@c Method) from the
4682/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004683static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004684TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004685 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004686 CXXMethodDecl *Method,
4687 CXXRecordDecl *ActingContext) {
4688 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004689 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4690 // const volatile object.
4691 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4692 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004693 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004694
4695 // Set up the conversion sequence as a "bad" conversion, to allow us
4696 // to exit early.
4697 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004698
4699 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004700 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004701 FromType = PT->getPointeeType();
4702
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004703 // When we had a pointer, it's implicitly dereferenced, so we
4704 // better have an lvalue.
4705 assert(FromClassification.isLValue());
4706 }
4707
Anders Carlssona552f7c2009-05-01 18:34:30 +00004708 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004709
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004710 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004712 // parameter is
4713 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004714 // - "lvalue reference to cv X" for functions declared without a
4715 // ref-qualifier or with the & ref-qualifier
4716 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004717 // ref-qualifier
4718 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004720 // cv-qualification on the member function declaration.
4721 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004723 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004724 // (C++ [over.match.funcs]p5). We perform a simplified version of
4725 // reference binding here, that allows class rvalues to bind to
4726 // non-constant references.
4727
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004728 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004729 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004730 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004731 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004732 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004733 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004734 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004735 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004736 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004737
4738 // Check that we have either the same type or a derived type. It
4739 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004740 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004741 ImplicitConversionKind SecondKind;
4742 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4743 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004744 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004745 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004746 else {
John McCallb1bdc622010-02-25 01:37:24 +00004747 ICS.setBad(BadConversionSequence::unrelated_class,
4748 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004749 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004750 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004751
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004752 // Check the ref-qualifier.
4753 switch (Method->getRefQualifier()) {
4754 case RQ_None:
4755 // Do nothing; we don't care about lvalueness or rvalueness.
4756 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004757
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004758 case RQ_LValue:
4759 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4760 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004761 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004762 ImplicitParamType);
4763 return ICS;
4764 }
4765 break;
4766
4767 case RQ_RValue:
4768 if (!FromClassification.isRValue()) {
4769 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004770 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004771 ImplicitParamType);
4772 return ICS;
4773 }
4774 break;
4775 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004776
Douglas Gregor96176b32008-11-18 23:14:02 +00004777 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004778 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004779 ICS.Standard.setAsIdentityConversion();
4780 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004781 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004782 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004783 ICS.Standard.ReferenceBinding = true;
4784 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004785 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004786 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004787 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4788 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4789 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004790 return ICS;
4791}
4792
4793/// PerformObjectArgumentInitialization - Perform initialization of
4794/// the implicit object parameter for the given Method with the given
4795/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004796ExprResult
4797Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004798 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004799 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004800 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004801 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004802 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004803 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004804
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004805 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004806 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004807 FromRecordType = PT->getPointeeType();
4808 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004809 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004810 } else {
4811 FromRecordType = From->getType();
4812 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004813 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004814 }
4815
John McCall701c89e2009-12-03 04:06:58 +00004816 // Note that we always use the true parent context when performing
4817 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004818 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004819 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4820 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004821 if (ICS.isBad()) {
4822 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4823 Qualifiers FromQs = FromRecordType.getQualifiers();
4824 Qualifiers ToQs = DestType.getQualifiers();
4825 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4826 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004827 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004828 diag::err_member_function_call_bad_cvr)
4829 << Method->getDeclName() << FromRecordType << (CVR - 1)
4830 << From->getSourceRange();
4831 Diag(Method->getLocation(), diag::note_previous_decl)
4832 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004833 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004834 }
4835 }
4836
Daniel Dunbar96a00142012-03-09 18:35:03 +00004837 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004838 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004839 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004840 }
Mike Stump1eb44332009-09-09 15:08:12 +00004841
John Wiegley429bb272011-04-08 18:41:53 +00004842 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4843 ExprResult FromRes =
4844 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4845 if (FromRes.isInvalid())
4846 return ExprError();
4847 From = FromRes.take();
4848 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004849
Douglas Gregor5fccd362010-03-03 23:55:11 +00004850 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004851 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004852 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004853 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004854}
4855
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004856/// TryContextuallyConvertToBool - Attempt to contextually convert the
4857/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004858static ImplicitConversionSequence
4859TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004860 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004861 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004862 // FIXME: Are these flags correct?
4863 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004864 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004865 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004866 /*CStyle=*/false,
4867 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004868}
4869
4870/// PerformContextuallyConvertToBool - Perform a contextual conversion
4871/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004872ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004873 if (checkPlaceholderForOverload(*this, From))
4874 return ExprError();
4875
John McCall120d63c2010-08-24 20:38:10 +00004876 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004877 if (!ICS.isBad())
4878 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004879
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004880 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004881 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004882 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004883 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004884 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004885}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
Richard Smith8ef7b202012-01-18 23:55:52 +00004887/// Check that the specified conversion is permitted in a converted constant
4888/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4889/// is acceptable.
4890static bool CheckConvertedConstantConversions(Sema &S,
4891 StandardConversionSequence &SCS) {
4892 // Since we know that the target type is an integral or unscoped enumeration
4893 // type, most conversion kinds are impossible. All possible First and Third
4894 // conversions are fine.
4895 switch (SCS.Second) {
4896 case ICK_Identity:
4897 case ICK_Integral_Promotion:
4898 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004899 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004900 return true;
4901
4902 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004903 // Conversion from an integral or unscoped enumeration type to bool is
4904 // classified as ICK_Boolean_Conversion, but it's also an integral
4905 // conversion, so it's permitted in a converted constant expression.
4906 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4907 SCS.getToType(2)->isBooleanType();
4908
Richard Smith8ef7b202012-01-18 23:55:52 +00004909 case ICK_Floating_Integral:
4910 case ICK_Complex_Real:
4911 return false;
4912
4913 case ICK_Lvalue_To_Rvalue:
4914 case ICK_Array_To_Pointer:
4915 case ICK_Function_To_Pointer:
4916 case ICK_NoReturn_Adjustment:
4917 case ICK_Qualification:
4918 case ICK_Compatible_Conversion:
4919 case ICK_Vector_Conversion:
4920 case ICK_Vector_Splat:
4921 case ICK_Derived_To_Base:
4922 case ICK_Pointer_Conversion:
4923 case ICK_Pointer_Member:
4924 case ICK_Block_Pointer_Conversion:
4925 case ICK_Writeback_Conversion:
4926 case ICK_Floating_Promotion:
4927 case ICK_Complex_Promotion:
4928 case ICK_Complex_Conversion:
4929 case ICK_Floating_Conversion:
4930 case ICK_TransparentUnionConversion:
4931 llvm_unreachable("unexpected second conversion kind");
4932
4933 case ICK_Num_Conversion_Kinds:
4934 break;
4935 }
4936
4937 llvm_unreachable("unknown conversion kind");
4938}
4939
4940/// CheckConvertedConstantExpression - Check that the expression From is a
4941/// converted constant expression of type T, perform the conversion and produce
4942/// the converted expression, per C++11 [expr.const]p3.
4943ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4944 llvm::APSInt &Value,
4945 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004946 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004947 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4948
4949 if (checkPlaceholderForOverload(*this, From))
4950 return ExprError();
4951
4952 // C++11 [expr.const]p3 with proposed wording fixes:
4953 // A converted constant expression of type T is a core constant expression,
4954 // implicitly converted to a prvalue of type T, where the converted
4955 // expression is a literal constant expression and the implicit conversion
4956 // sequence contains only user-defined conversions, lvalue-to-rvalue
4957 // conversions, integral promotions, and integral conversions other than
4958 // narrowing conversions.
4959 ImplicitConversionSequence ICS =
4960 TryImplicitConversion(From, T,
4961 /*SuppressUserConversions=*/false,
4962 /*AllowExplicit=*/false,
4963 /*InOverloadResolution=*/false,
4964 /*CStyle=*/false,
4965 /*AllowObjcWritebackConversion=*/false);
4966 StandardConversionSequence *SCS = 0;
4967 switch (ICS.getKind()) {
4968 case ImplicitConversionSequence::StandardConversion:
4969 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004970 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004971 diag::err_typecheck_converted_constant_expression_disallowed)
4972 << From->getType() << From->getSourceRange() << T;
4973 SCS = &ICS.Standard;
4974 break;
4975 case ImplicitConversionSequence::UserDefinedConversion:
4976 // We are converting from class type to an integral or enumeration type, so
4977 // the Before sequence must be trivial.
4978 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004979 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004980 diag::err_typecheck_converted_constant_expression_disallowed)
4981 << From->getType() << From->getSourceRange() << T;
4982 SCS = &ICS.UserDefined.After;
4983 break;
4984 case ImplicitConversionSequence::AmbiguousConversion:
4985 case ImplicitConversionSequence::BadConversion:
4986 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004987 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004988 diag::err_typecheck_converted_constant_expression)
4989 << From->getType() << From->getSourceRange() << T;
4990 return ExprError();
4991
4992 case ImplicitConversionSequence::EllipsisConversion:
4993 llvm_unreachable("ellipsis conversion in converted constant expression");
4994 }
4995
4996 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4997 if (Result.isInvalid())
4998 return Result;
4999
5000 // Check for a narrowing implicit conversion.
5001 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00005002 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00005003 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5004 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005005 case NK_Variable_Narrowing:
5006 // Implicit conversion to a narrower type, and the value is not a constant
5007 // expression. We'll diagnose this in a moment.
5008 case NK_Not_Narrowing:
5009 break;
5010
5011 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005012 Diag(From->getLocStart(),
5013 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5014 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005015 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005016 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005017 break;
5018
5019 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005020 Diag(From->getLocStart(),
5021 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5022 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005023 << CCE << /*Constant*/0 << From->getType() << T;
5024 break;
5025 }
5026
5027 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005028 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005029 Expr::EvalResult Eval;
5030 Eval.Diag = &Notes;
5031
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005032 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005033 // The expression can't be folded, so we can't keep it at this position in
5034 // the AST.
5035 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005036 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005037 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005038
5039 if (Notes.empty()) {
5040 // It's a constant expression.
5041 return Result;
5042 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005043 }
5044
5045 // It's not a constant expression. Produce an appropriate diagnostic.
5046 if (Notes.size() == 1 &&
5047 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5048 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5049 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005050 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005051 << CCE << From->getSourceRange();
5052 for (unsigned I = 0; I < Notes.size(); ++I)
5053 Diag(Notes[I].first, Notes[I].second);
5054 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005055 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005056}
5057
John McCall0bcc9bc2011-09-09 06:11:02 +00005058/// dropPointerConversions - If the given standard conversion sequence
5059/// involves any pointer conversions, remove them. This may change
5060/// the result type of the conversion sequence.
5061static void dropPointerConversion(StandardConversionSequence &SCS) {
5062 if (SCS.Second == ICK_Pointer_Conversion) {
5063 SCS.Second = ICK_Identity;
5064 SCS.Third = ICK_Identity;
5065 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5066 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005067}
John McCall120d63c2010-08-24 20:38:10 +00005068
John McCall0bcc9bc2011-09-09 06:11:02 +00005069/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5070/// convert the expression From to an Objective-C pointer type.
5071static ImplicitConversionSequence
5072TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5073 // Do an implicit conversion to 'id'.
5074 QualType Ty = S.Context.getObjCIdType();
5075 ImplicitConversionSequence ICS
5076 = TryImplicitConversion(S, From, Ty,
5077 // FIXME: Are these flags correct?
5078 /*SuppressUserConversions=*/false,
5079 /*AllowExplicit=*/true,
5080 /*InOverloadResolution=*/false,
5081 /*CStyle=*/false,
5082 /*AllowObjCWritebackConversion=*/false);
5083
5084 // Strip off any final conversions to 'id'.
5085 switch (ICS.getKind()) {
5086 case ImplicitConversionSequence::BadConversion:
5087 case ImplicitConversionSequence::AmbiguousConversion:
5088 case ImplicitConversionSequence::EllipsisConversion:
5089 break;
5090
5091 case ImplicitConversionSequence::UserDefinedConversion:
5092 dropPointerConversion(ICS.UserDefined.After);
5093 break;
5094
5095 case ImplicitConversionSequence::StandardConversion:
5096 dropPointerConversion(ICS.Standard);
5097 break;
5098 }
5099
5100 return ICS;
5101}
5102
5103/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5104/// conversion of the expression From to an Objective-C pointer type.
5105ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005106 if (checkPlaceholderForOverload(*this, From))
5107 return ExprError();
5108
John McCallc12c5bb2010-05-15 11:32:37 +00005109 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005110 ImplicitConversionSequence ICS =
5111 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005112 if (!ICS.isBad())
5113 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005114 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005115}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005116
Richard Smithf39aec12012-02-04 07:07:42 +00005117/// Determine whether the provided type is an integral type, or an enumeration
5118/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005119bool Sema::ICEConvertDiagnoser::match(QualType T) {
5120 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5121 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005122}
5123
Richard Smith097e0a22013-05-21 19:05:48 +00005124/// \brief Attempt to convert the given expression to a type which is accepted
5125/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005126///
Richard Smith097e0a22013-05-21 19:05:48 +00005127/// This routine will attempt to convert an expression of class type to a
5128/// type accepted by the specified converter. In C++11 and before, the class
5129/// must have a single non-explicit conversion function converting to a matching
5130/// type. In C++1y, there can be multiple such conversion functions, but only
5131/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005132///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005133/// \param Loc The source location of the construct that requires the
5134/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135///
James Dennett40ae6662012-06-22 08:52:37 +00005136/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005137///
Richard Smith097e0a22013-05-21 19:05:48 +00005138/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005139///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005140/// \returns The expression, converted to an integral or enumeration type if
5141/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005142ExprResult Sema::PerformContextualImplicitConversion(
5143 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005144 // We can't perform any more checking for type-dependent expressions.
5145 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005146 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005147
Eli Friedmanceccab92012-01-26 00:26:18 +00005148 // Process placeholders immediately.
5149 if (From->hasPlaceholderType()) {
5150 ExprResult result = CheckPlaceholderExpr(From);
5151 if (result.isInvalid()) return result;
5152 From = result.take();
5153 }
5154
Richard Smith097e0a22013-05-21 19:05:48 +00005155 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005156 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005157 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005158 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005159
5160 // FIXME: Check for missing '()' if T is a function type?
5161
Richard Smith097e0a22013-05-21 19:05:48 +00005162 // We can only perform contextual implicit conversions on objects of class
5163 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005164 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005165 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005166 if (!Converter.Suppress)
5167 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005168 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005170
Douglas Gregorc30614b2010-06-29 23:17:37 +00005171 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005172 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005173 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005174 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005175
5176 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5177 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5178
Douglas Gregord10099e2012-05-04 16:32:21 +00005179 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005180 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005181 }
Richard Smith097e0a22013-05-21 19:05:48 +00005182 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005183
5184 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005185 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186
Douglas Gregorc30614b2010-06-29 23:17:37 +00005187 // Look for a conversion to an integral or enumeration type.
5188 UnresolvedSet<4> ViableConversions;
5189 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005190 std::pair<CXXRecordDecl::conversion_iterator,
5191 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005192 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005194 bool HadMultipleCandidates
5195 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005196
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005197 for (CXXRecordDecl::conversion_iterator
5198 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005199 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005200 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
Richard Smith097e0a22013-05-21 19:05:48 +00005201 if (Converter.match(
5202 Conversion->getConversionType().getNonReferenceType())) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005203 if (Conversion->isExplicit())
5204 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5205 else
5206 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5207 }
Richard Smithf39aec12012-02-04 07:07:42 +00005208 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005210
Richard Smith097e0a22013-05-21 19:05:48 +00005211 // FIXME: Implement the C++11 rules!
Douglas Gregorc30614b2010-06-29 23:17:37 +00005212 switch (ViableConversions.size()) {
5213 case 0:
Richard Smith097e0a22013-05-21 19:05:48 +00005214 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215 DeclAccessPair Found = ExplicitConversions[0];
5216 CXXConversionDecl *Conversion
5217 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005218
Douglas Gregorc30614b2010-06-29 23:17:37 +00005219 // The user probably meant to invoke the given explicit
5220 // conversion; use it.
5221 QualType ConvTy
5222 = Conversion->getConversionType().getNonReferenceType();
5223 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005224 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005225
Richard Smith097e0a22013-05-21 19:05:48 +00005226 Converter.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005227 << FixItHint::CreateInsertion(From->getLocStart(),
5228 "static_cast<" + TypeStr + ">(")
5229 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5230 ")");
Richard Smith097e0a22013-05-21 19:05:48 +00005231 Converter.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005232
5233 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005234 // explicit conversion function.
5235 if (isSFINAEContext())
5236 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005237
Douglas Gregorc30614b2010-06-29 23:17:37 +00005238 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005239 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5240 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005241 if (Result.isInvalid())
5242 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005243 // Record usage of conversion in an implicit cast.
5244 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5245 CK_UserDefinedConversion,
5246 Result.get(), 0,
5247 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005249
Douglas Gregorc30614b2010-06-29 23:17:37 +00005250 // We'll complain below about a non-integral condition type.
5251 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005252
Douglas Gregorc30614b2010-06-29 23:17:37 +00005253 case 1: {
5254 // Apply this conversion.
5255 DeclAccessPair Found = ViableConversions[0];
5256 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005257
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005258 CXXConversionDecl *Conversion
5259 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5260 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005261 = Conversion->getConversionType().getNonReferenceType();
Richard Smith097e0a22013-05-21 19:05:48 +00005262 if (!Converter.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005263 if (isSFINAEContext())
5264 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005265
Richard Smith097e0a22013-05-21 19:05:48 +00005266 Converter.diagnoseConversion(*this, Loc, T, ConvTy)
Douglas Gregorab41fe92012-05-04 22:38:52 +00005267 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005269
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005270 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5271 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005272 if (Result.isInvalid())
5273 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005274 // Record usage of conversion in an implicit cast.
5275 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5276 CK_UserDefinedConversion,
5277 Result.get(), 0,
5278 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005279 break;
5280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005281
Douglas Gregorc30614b2010-06-29 23:17:37 +00005282 default:
Richard Smith097e0a22013-05-21 19:05:48 +00005283 if (Converter.Suppress)
Douglas Gregorab41fe92012-05-04 22:38:52 +00005284 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005285
Richard Smith097e0a22013-05-21 19:05:48 +00005286 Converter.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005287 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5288 CXXConversionDecl *Conv
5289 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5290 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Richard Smith097e0a22013-05-21 19:05:48 +00005291 Converter.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005292 }
John McCall9ae2f072010-08-23 23:25:46 +00005293 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005295
Richard Smith097e0a22013-05-21 19:05:48 +00005296 if (!Converter.match(From->getType()) && !Converter.Suppress)
5297 Converter.diagnoseNoMatch(*this, Loc, From->getType())
Douglas Gregorab41fe92012-05-04 22:38:52 +00005298 << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005299
Eli Friedmanceccab92012-01-26 00:26:18 +00005300 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005301}
5302
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005303/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005304/// candidate functions, using the given function call arguments. If
5305/// @p SuppressUserConversions, then don't allow user-defined
5306/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005307///
James Dennett699c9042012-06-15 07:13:21 +00005308/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005309/// based on an incomplete set of function arguments. This feature is used by
5310/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005311void
5312Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005313 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005314 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005315 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005316 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005317 bool PartialOverloading,
5318 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005319 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005320 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005321 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005322 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005323 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005324
Douglas Gregor88a35142008-12-22 05:46:06 +00005325 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005326 if (!isa<CXXConstructorDecl>(Method)) {
5327 // If we get here, it's because we're calling a member function
5328 // that is named without a member access expression (e.g.,
5329 // "this->f") that was either written explicitly or created
5330 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005331 // function, e.g., X::f(). We use an empty type for the implied
5332 // object argument (C++ [over.call.func]p3), and the acting context
5333 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005334 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005335 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005337 return;
5338 }
5339 // We treat a constructor like a non-member function, since its object
5340 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005341 }
5342
Douglas Gregorfd476482009-11-13 23:59:09 +00005343 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005344 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005345
Douglas Gregor7edfb692009-11-23 12:27:39 +00005346 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005347 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005348
Douglas Gregor66724ea2009-11-14 01:20:54 +00005349 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5350 // C++ [class.copy]p3:
5351 // A member function template is never instantiated to perform the copy
5352 // of a class object to an object of its class type.
5353 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005354 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005355 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005356 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5357 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005358 return;
5359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005360
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005361 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005362 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005363 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005364 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005365 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005366 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005367 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005368 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005370 unsigned NumArgsInProto = Proto->getNumArgs();
5371
5372 // (C++ 13.3.2p2): A candidate function having fewer than m
5373 // parameters is viable only if it has an ellipsis in its parameter
5374 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005375 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005376 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005377 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005378 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005379 return;
5380 }
5381
5382 // (C++ 13.3.2p2): A candidate function having more than m parameters
5383 // is viable only if the (m+1)st parameter has a default argument
5384 // (8.3.6). For the purposes of overload resolution, the
5385 // parameter list is truncated on the right, so that there are
5386 // exactly m parameters.
5387 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005388 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005389 // Not enough arguments.
5390 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005391 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005392 return;
5393 }
5394
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005395 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005396 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005397 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5398 if (CheckCUDATarget(Caller, Function)) {
5399 Candidate.Viable = false;
5400 Candidate.FailureKind = ovl_fail_bad_target;
5401 return;
5402 }
5403
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005404 // Determine the implicit conversion sequences for each of the
5405 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005406 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005407 if (ArgIdx < NumArgsInProto) {
5408 // (C++ 13.3.2p3): for F to be a viable function, there shall
5409 // exist for each argument an implicit conversion sequence
5410 // (13.3.3.1) that converts that argument to the corresponding
5411 // parameter of F.
5412 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005413 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005414 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005415 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005416 /*InOverloadResolution=*/true,
5417 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005418 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005419 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005420 if (Candidate.Conversions[ArgIdx].isBad()) {
5421 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005422 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005423 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005424 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005425 } else {
5426 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5427 // argument for which there is no corresponding parameter is
5428 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005429 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005430 }
5431 }
5432}
5433
Douglas Gregor063daf62009-03-13 18:40:31 +00005434/// \brief Add all of the function declarations in the given function set to
5435/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005436void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005437 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005438 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005439 bool SuppressUserConversions,
5440 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005441 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005442 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005445 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005446 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005447 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005448 Args.slice(1), CandidateSet,
5449 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005450 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005451 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005452 SuppressUserConversions);
5453 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005454 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005455 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5456 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005457 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005458 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005459 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005460 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005461 Args[0]->Classify(Context), Args.slice(1),
5462 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005463 else
John McCall9aa472c2010-03-19 07:35:19 +00005464 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005465 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005466 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005467 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005468 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005469}
5470
John McCall314be4e2009-11-17 07:50:12 +00005471/// AddMethodCandidate - Adds a named decl (which is some kind of
5472/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005473void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005474 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005475 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005476 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005477 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005478 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005479 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005481
5482 if (isa<UsingShadowDecl>(Decl))
5483 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005484
John McCall314be4e2009-11-17 07:50:12 +00005485 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5486 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5487 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005488 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5489 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005490 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005491 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005492 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005493 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005494 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005496 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005497 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005498 }
5499}
5500
Douglas Gregor96176b32008-11-18 23:14:02 +00005501/// AddMethodCandidate - Adds the given C++ member function to the set
5502/// of candidate functions, using the given function call arguments
5503/// and the object argument (@c Object). For example, in a call
5504/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5505/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5506/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005507/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005508void
John McCall9aa472c2010-03-19 07:35:19 +00005509Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005510 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005511 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005512 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005513 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005514 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005515 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005516 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005517 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005518 assert(!isa<CXXConstructorDecl>(Method) &&
5519 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005520
Douglas Gregor3f396022009-09-28 04:47:19 +00005521 if (!CandidateSet.isNewCandidate(Method))
5522 return;
5523
Douglas Gregor7edfb692009-11-23 12:27:39 +00005524 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005525 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005526
Douglas Gregor96176b32008-11-18 23:14:02 +00005527 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005528 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005529 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005530 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005531 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005532 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005533 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005534
5535 unsigned NumArgsInProto = Proto->getNumArgs();
5536
5537 // (C++ 13.3.2p2): A candidate function having fewer than m
5538 // parameters is viable only if it has an ellipsis in its parameter
5539 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005540 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005541 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005542 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005543 return;
5544 }
5545
5546 // (C++ 13.3.2p2): A candidate function having more than m parameters
5547 // is viable only if the (m+1)st parameter has a default argument
5548 // (8.3.6). For the purposes of overload resolution, the
5549 // parameter list is truncated on the right, so that there are
5550 // exactly m parameters.
5551 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005552 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005553 // Not enough arguments.
5554 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005555 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005556 return;
5557 }
5558
5559 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005560
John McCall701c89e2009-12-03 04:06:58 +00005561 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005562 // The implicit object argument is ignored.
5563 Candidate.IgnoreObjectArgument = true;
5564 else {
5565 // Determine the implicit conversion sequence for the object
5566 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005567 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005568 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5569 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005570 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005571 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005572 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005573 return;
5574 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005575 }
5576
5577 // Determine the implicit conversion sequences for each of the
5578 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005579 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005580 if (ArgIdx < NumArgsInProto) {
5581 // (C++ 13.3.2p3): for F to be a viable function, there shall
5582 // exist for each argument an implicit conversion sequence
5583 // (13.3.3.1) that converts that argument to the corresponding
5584 // parameter of F.
5585 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005586 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005587 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005589 /*InOverloadResolution=*/true,
5590 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005591 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005592 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005593 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005594 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005595 break;
5596 }
5597 } else {
5598 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5599 // argument for which there is no corresponding parameter is
5600 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005601 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005602 }
5603 }
5604}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605
Douglas Gregor6b906862009-08-21 00:16:32 +00005606/// \brief Add a C++ member function template as a candidate to the candidate
5607/// set, using template argument deduction to produce an appropriate member
5608/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005609void
Douglas Gregor6b906862009-08-21 00:16:32 +00005610Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005611 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005612 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005613 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005614 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005615 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005616 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005617 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005618 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005619 if (!CandidateSet.isNewCandidate(MethodTmpl))
5620 return;
5621
Douglas Gregor6b906862009-08-21 00:16:32 +00005622 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005623 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005624 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005625 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005626 // candidate functions in the usual way.113) A given name can refer to one
5627 // or more function templates and also to a set of overloaded non-template
5628 // functions. In such a case, the candidate functions generated from each
5629 // function template are combined with the set of non-template candidate
5630 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005631 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005632 FunctionDecl *Specialization = 0;
5633 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005634 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5635 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005636 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005637 Candidate.FoundDecl = FoundDecl;
5638 Candidate.Function = MethodTmpl->getTemplatedDecl();
5639 Candidate.Viable = false;
5640 Candidate.FailureKind = ovl_fail_bad_deduction;
5641 Candidate.IsSurrogate = false;
5642 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005643 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005645 Info);
5646 return;
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Douglas Gregor6b906862009-08-21 00:16:32 +00005649 // Add the function template specialization produced by template argument
5650 // deduction as a candidate.
5651 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005652 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005653 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005654 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005655 ActingContext, ObjectType, ObjectClassification, Args,
5656 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005657}
5658
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005659/// \brief Add a C++ function template specialization as a candidate
5660/// in the candidate set, using template argument deduction to produce
5661/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005662void
Douglas Gregore53060f2009-06-25 22:08:12 +00005663Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005664 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005665 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005666 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005667 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005668 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005669 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5670 return;
5671
Douglas Gregore53060f2009-06-25 22:08:12 +00005672 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005673 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005674 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005675 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005676 // candidate functions in the usual way.113) A given name can refer to one
5677 // or more function templates and also to a set of overloaded non-template
5678 // functions. In such a case, the candidate functions generated from each
5679 // function template are combined with the set of non-template candidate
5680 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005681 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005682 FunctionDecl *Specialization = 0;
5683 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005684 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5685 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005686 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005687 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005688 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5689 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005690 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005691 Candidate.IsSurrogate = false;
5692 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005693 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005694 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005695 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005696 return;
5697 }
Mike Stump1eb44332009-09-09 15:08:12 +00005698
Douglas Gregore53060f2009-06-25 22:08:12 +00005699 // Add the function template specialization produced by template argument
5700 // deduction as a candidate.
5701 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005702 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005703 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005704}
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005706/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005707/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005708/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005709/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005710/// (which may or may not be the same type as the type that the
5711/// conversion function produces).
5712void
5713Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005714 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005715 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005716 Expr *From, QualType ToType,
5717 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005718 assert(!Conversion->getDescribedFunctionTemplate() &&
5719 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005720 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005721 if (!CandidateSet.isNewCandidate(Conversion))
5722 return;
5723
Richard Smith60e141e2013-05-04 07:00:32 +00005724 // If the conversion function has an undeduced return type, trigger its
5725 // deduction now.
5726 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5727 if (DeduceReturnType(Conversion, From->getExprLoc()))
5728 return;
5729 ConvType = Conversion->getConversionType().getNonReferenceType();
5730 }
5731
Douglas Gregor7edfb692009-11-23 12:27:39 +00005732 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005733 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005734
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005735 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005736 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005737 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005738 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005739 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005740 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005741 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005742 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005743 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005744 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005745 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005746
Douglas Gregorbca39322010-08-19 15:37:02 +00005747 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005748 // For conversion functions, the function is considered to be a member of
5749 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005750 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005751 //
5752 // Determine the implicit conversion sequence for the implicit
5753 // object parameter.
5754 QualType ImplicitParamType = From->getType();
5755 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5756 ImplicitParamType = FromPtrType->getPointeeType();
5757 CXXRecordDecl *ConversionContext
5758 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005759
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005760 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761 = TryObjectArgumentInitialization(*this, From->getType(),
5762 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005763 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005764
John McCall1d318332010-01-12 00:44:57 +00005765 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005766 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005767 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005768 return;
5769 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005770
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005772 // derived to base as such conversions are given Conversion Rank. They only
5773 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5774 QualType FromCanon
5775 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5776 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5777 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5778 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005779 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005780 return;
5781 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005782
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005783 // To determine what the conversion from the result of calling the
5784 // conversion function to the type we're eventually trying to
5785 // convert to (ToType), we need to synthesize a call to the
5786 // conversion function and attempt copy initialization from it. This
5787 // makes sure that we get the right semantics with respect to
5788 // lvalues/rvalues and the type. Fortunately, we can allocate this
5789 // call on the stack and we don't need its arguments to be
5790 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005791 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005792 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005793 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5794 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005795 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005796 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005797
Richard Smith87c1f1f2011-07-13 22:53:21 +00005798 QualType ConversionType = Conversion->getConversionType();
5799 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005800 Candidate.Viable = false;
5801 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5802 return;
5803 }
5804
Richard Smith87c1f1f2011-07-13 22:53:21 +00005805 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005806
Mike Stump1eb44332009-09-09 15:08:12 +00005807 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005808 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5809 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005810 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005811 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005812 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005813 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005814 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005815 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005816 /*InOverloadResolution=*/false,
5817 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005818
John McCall1d318332010-01-12 00:44:57 +00005819 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005820 case ImplicitConversionSequence::StandardConversion:
5821 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005822
Douglas Gregorc520c842010-04-12 23:42:09 +00005823 // C++ [over.ics.user]p3:
5824 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005825 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005826 // shall have exact match rank.
5827 if (Conversion->getPrimaryTemplate() &&
5828 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5829 Candidate.Viable = false;
5830 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5831 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005832
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005833 // C++0x [dcl.init.ref]p5:
5834 // In the second case, if the reference is an rvalue reference and
5835 // the second standard conversion sequence of the user-defined
5836 // conversion sequence includes an lvalue-to-rvalue conversion, the
5837 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005838 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005839 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5840 Candidate.Viable = false;
5841 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5842 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005843 break;
5844
5845 case ImplicitConversionSequence::BadConversion:
5846 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005847 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005848 break;
5849
5850 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005851 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005852 "Can only end up with a standard conversion sequence or failure");
5853 }
5854}
5855
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005856/// \brief Adds a conversion function template specialization
5857/// candidate to the overload set, using template argument deduction
5858/// to deduce the template arguments of the conversion function
5859/// template from the type that we are converting to (C++
5860/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005861void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005862Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005863 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005864 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005865 Expr *From, QualType ToType,
5866 OverloadCandidateSet &CandidateSet) {
5867 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5868 "Only conversion function templates permitted here");
5869
Douglas Gregor3f396022009-09-28 04:47:19 +00005870 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5871 return;
5872
Craig Topper93e45992012-09-19 02:26:47 +00005873 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005874 CXXConversionDecl *Specialization = 0;
5875 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005876 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005877 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005878 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005879 Candidate.FoundDecl = FoundDecl;
5880 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5881 Candidate.Viable = false;
5882 Candidate.FailureKind = ovl_fail_bad_deduction;
5883 Candidate.IsSurrogate = false;
5884 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005885 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005887 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005888 return;
5889 }
Mike Stump1eb44332009-09-09 15:08:12 +00005890
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005891 // Add the conversion function template specialization produced by
5892 // template argument deduction as a candidate.
5893 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005894 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005895 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005896}
5897
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005898/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5899/// converts the given @c Object to a function pointer via the
5900/// conversion function @c Conversion, and then attempts to call it
5901/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5902/// the type of function that we'll eventually be calling.
5903void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005904 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005905 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005906 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005907 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005908 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005909 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005910 if (!CandidateSet.isNewCandidate(Conversion))
5911 return;
5912
Douglas Gregor7edfb692009-11-23 12:27:39 +00005913 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005914 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005915
Ahmed Charles13a140c2012-02-25 11:00:22 +00005916 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005917 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005918 Candidate.Function = 0;
5919 Candidate.Surrogate = Conversion;
5920 Candidate.Viable = true;
5921 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005922 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005923 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005924
5925 // Determine the implicit conversion sequence for the implicit
5926 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005927 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005928 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005929 Object->Classify(Context),
5930 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005931 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005932 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005933 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005934 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005935 return;
5936 }
5937
5938 // The first conversion is actually a user-defined conversion whose
5939 // first conversion is ObjectInit's standard conversion (which is
5940 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005941 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005942 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005943 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005944 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005945 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005946 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005947 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005948 = Candidate.Conversions[0].UserDefined.Before;
5949 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5950
Mike Stump1eb44332009-09-09 15:08:12 +00005951 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005952 unsigned NumArgsInProto = Proto->getNumArgs();
5953
5954 // (C++ 13.3.2p2): A candidate function having fewer than m
5955 // parameters is viable only if it has an ellipsis in its parameter
5956 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005957 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005958 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005959 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005960 return;
5961 }
5962
5963 // Function types don't have any default arguments, so just check if
5964 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005965 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005966 // Not enough arguments.
5967 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005968 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005969 return;
5970 }
5971
5972 // Determine the implicit conversion sequences for each of the
5973 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00005974 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005975 if (ArgIdx < NumArgsInProto) {
5976 // (C++ 13.3.2p3): for F to be a viable function, there shall
5977 // exist for each argument an implicit conversion sequence
5978 // (13.3.3.1) that converts that argument to the corresponding
5979 // parameter of F.
5980 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005981 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005982 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005983 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005984 /*InOverloadResolution=*/false,
5985 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005986 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005987 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005988 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005989 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005990 break;
5991 }
5992 } else {
5993 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5994 // argument for which there is no corresponding parameter is
5995 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005996 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005997 }
5998 }
5999}
6000
Douglas Gregor063daf62009-03-13 18:40:31 +00006001/// \brief Add overload candidates for overloaded operators that are
6002/// member functions.
6003///
6004/// Add the overloaded operator candidates that are member functions
6005/// for the operator Op that was used in an operator expression such
6006/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6007/// CandidateSet will store the added overload candidates. (C++
6008/// [over.match.oper]).
6009void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6010 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006011 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006012 OverloadCandidateSet& CandidateSet,
6013 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006014 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6015
6016 // C++ [over.match.oper]p3:
6017 // For a unary operator @ with an operand of a type whose
6018 // cv-unqualified version is T1, and for a binary operator @ with
6019 // a left operand of a type whose cv-unqualified version is T1 and
6020 // a right operand of a type whose cv-unqualified version is T2,
6021 // three sets of candidate functions, designated member
6022 // candidates, non-member candidates and built-in candidates, are
6023 // constructed as follows:
6024 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006025
Richard Smithe410be92013-04-20 12:41:22 +00006026 // -- If T1 is a complete class type or a class currently being
6027 // defined, the set of member candidates is the result of the
6028 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6029 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006030 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006031 // Complete the type if it can be completed.
6032 RequireCompleteType(OpLoc, T1, 0);
6033 // If the type is neither complete nor being defined, bail out now.
6034 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006035 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006036
John McCalla24dc2e2009-11-17 02:14:36 +00006037 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6038 LookupQualifiedName(Operators, T1Rec->getDecl());
6039 Operators.suppressDiagnostics();
6040
Mike Stump1eb44332009-09-09 15:08:12 +00006041 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006042 OperEnd = Operators.end();
6043 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006044 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006045 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006046 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006047 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006048 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006049 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006050 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006051}
6052
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006053/// AddBuiltinCandidate - Add a candidate for a built-in
6054/// operator. ResultTy and ParamTys are the result and parameter types
6055/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006056/// arguments being passed to the candidate. IsAssignmentOperator
6057/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006058/// operator. NumContextualBoolArguments is the number of arguments
6059/// (at the beginning of the argument list) that will be contextually
6060/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006061void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006062 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006063 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006064 bool IsAssignmentOperator,
6065 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006066 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006067 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006068
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006069 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006070 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006071 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006073 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006074 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006075 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006076 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006077 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6078
6079 // Determine the implicit conversion sequences for each of the
6080 // arguments.
6081 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006082 Candidate.ExplicitCallArguments = Args.size();
6083 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006084 // C++ [over.match.oper]p4:
6085 // For the built-in assignment operators, conversions of the
6086 // left operand are restricted as follows:
6087 // -- no temporaries are introduced to hold the left operand, and
6088 // -- no user-defined conversions are applied to the left
6089 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006090 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006091 //
6092 // We block these conversions by turning off user-defined
6093 // conversions, since that is the only way that initialization of
6094 // a reference to a non-class type can occur from something that
6095 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006096 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006097 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006098 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006099 Candidate.Conversions[ArgIdx]
6100 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006101 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006102 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006103 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006104 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006105 /*InOverloadResolution=*/false,
6106 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006107 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006108 }
John McCall1d318332010-01-12 00:44:57 +00006109 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006110 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006111 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006112 break;
6113 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006114 }
6115}
6116
6117/// BuiltinCandidateTypeSet - A set of types that will be used for the
6118/// candidate operator functions for built-in operators (C++
6119/// [over.built]). The types are separated into pointer types and
6120/// enumeration types.
6121class BuiltinCandidateTypeSet {
6122 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006123 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006124
6125 /// PointerTypes - The set of pointer types that will be used in the
6126 /// built-in candidates.
6127 TypeSet PointerTypes;
6128
Sebastian Redl78eb8742009-04-19 21:53:20 +00006129 /// MemberPointerTypes - The set of member pointer types that will be
6130 /// used in the built-in candidates.
6131 TypeSet MemberPointerTypes;
6132
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006133 /// EnumerationTypes - The set of enumeration types that will be
6134 /// used in the built-in candidates.
6135 TypeSet EnumerationTypes;
6136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006137 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006138 /// candidates.
6139 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006140
6141 /// \brief A flag indicating non-record types are viable candidates
6142 bool HasNonRecordTypes;
6143
6144 /// \brief A flag indicating whether either arithmetic or enumeration types
6145 /// were present in the candidate set.
6146 bool HasArithmeticOrEnumeralTypes;
6147
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006148 /// \brief A flag indicating whether the nullptr type was present in the
6149 /// candidate set.
6150 bool HasNullPtrType;
6151
Douglas Gregor5842ba92009-08-24 15:23:48 +00006152 /// Sema - The semantic analysis instance where we are building the
6153 /// candidate type set.
6154 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006155
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006156 /// Context - The AST context in which we will build the type sets.
6157 ASTContext &Context;
6158
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006159 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6160 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006161 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006162
6163public:
6164 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006165 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006166
Mike Stump1eb44332009-09-09 15:08:12 +00006167 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006168 : HasNonRecordTypes(false),
6169 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006170 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006171 SemaRef(SemaRef),
6172 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006173
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006174 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006175 SourceLocation Loc,
6176 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006177 bool AllowExplicitConversions,
6178 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006179
6180 /// pointer_begin - First pointer type found;
6181 iterator pointer_begin() { return PointerTypes.begin(); }
6182
Sebastian Redl78eb8742009-04-19 21:53:20 +00006183 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006184 iterator pointer_end() { return PointerTypes.end(); }
6185
Sebastian Redl78eb8742009-04-19 21:53:20 +00006186 /// member_pointer_begin - First member pointer type found;
6187 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6188
6189 /// member_pointer_end - Past the last member pointer type found;
6190 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6191
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006192 /// enumeration_begin - First enumeration type found;
6193 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6194
Sebastian Redl78eb8742009-04-19 21:53:20 +00006195 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006196 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006197
Douglas Gregor26bcf672010-05-19 03:21:00 +00006198 iterator vector_begin() { return VectorTypes.begin(); }
6199 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006200
6201 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6202 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006203 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006204};
6205
Sebastian Redl78eb8742009-04-19 21:53:20 +00006206/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006207/// the set of pointer types along with any more-qualified variants of
6208/// that type. For example, if @p Ty is "int const *", this routine
6209/// will add "int const *", "int const volatile *", "int const
6210/// restrict *", and "int const volatile restrict *" to the set of
6211/// pointer types. Returns true if the add of @p Ty itself succeeded,
6212/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006213///
6214/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006215bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006216BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6217 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006218
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006219 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006220 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006221 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006222
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006223 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006224 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006225 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006226 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006227 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6228 PointeeTy = PTy->getPointeeType();
6229 buildObjCPtr = true;
6230 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006231 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006232 }
6233
Sebastian Redla9efada2009-11-18 20:39:26 +00006234 // Don't add qualified variants of arrays. For one, they're not allowed
6235 // (the qualifier would sink to the element type), and for another, the
6236 // only overload situation where it matters is subscript or pointer +- int,
6237 // and those shouldn't have qualifier variants anyway.
6238 if (PointeeTy->isArrayType())
6239 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006240
John McCall0953e762009-09-24 19:53:00 +00006241 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006242 bool hasVolatile = VisibleQuals.hasVolatile();
6243 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006244
John McCall0953e762009-09-24 19:53:00 +00006245 // Iterate through all strict supersets of BaseCVR.
6246 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6247 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006248 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006249 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006250
6251 // Skip over restrict if no restrict found anywhere in the types, or if
6252 // the type cannot be restrict-qualified.
6253 if ((CVR & Qualifiers::Restrict) &&
6254 (!hasRestrict ||
6255 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6256 continue;
6257
6258 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006259 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006260
6261 // Build qualified pointer type.
6262 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006263 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006264 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006265 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006266 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6267
6268 // Insert qualified pointer type.
6269 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006270 }
6271
6272 return true;
6273}
6274
Sebastian Redl78eb8742009-04-19 21:53:20 +00006275/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6276/// to the set of pointer types along with any more-qualified variants of
6277/// that type. For example, if @p Ty is "int const *", this routine
6278/// will add "int const *", "int const volatile *", "int const
6279/// restrict *", and "int const volatile restrict *" to the set of
6280/// pointer types. Returns true if the add of @p Ty itself succeeded,
6281/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006282///
6283/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006284bool
6285BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6286 QualType Ty) {
6287 // Insert this type.
6288 if (!MemberPointerTypes.insert(Ty))
6289 return false;
6290
John McCall0953e762009-09-24 19:53:00 +00006291 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6292 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006293
John McCall0953e762009-09-24 19:53:00 +00006294 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006295 // Don't add qualified variants of arrays. For one, they're not allowed
6296 // (the qualifier would sink to the element type), and for another, the
6297 // only overload situation where it matters is subscript or pointer +- int,
6298 // and those shouldn't have qualifier variants anyway.
6299 if (PointeeTy->isArrayType())
6300 return true;
John McCall0953e762009-09-24 19:53:00 +00006301 const Type *ClassTy = PointerTy->getClass();
6302
6303 // Iterate through all strict supersets of the pointee type's CVR
6304 // qualifiers.
6305 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6306 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6307 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006308
John McCall0953e762009-09-24 19:53:00 +00006309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006310 MemberPointerTypes.insert(
6311 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006312 }
6313
6314 return true;
6315}
6316
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006317/// AddTypesConvertedFrom - Add each of the types to which the type @p
6318/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006319/// primarily interested in pointer types and enumeration types. We also
6320/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006321/// AllowUserConversions is true if we should look at the conversion
6322/// functions of a class type, and AllowExplicitConversions if we
6323/// should also include the explicit conversion functions of a class
6324/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006325void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006326BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006327 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006328 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006329 bool AllowExplicitConversions,
6330 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006331 // Only deal with canonical types.
6332 Ty = Context.getCanonicalType(Ty);
6333
6334 // Look through reference types; they aren't part of the type of an
6335 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006336 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006337 Ty = RefTy->getPointeeType();
6338
John McCall3b657512011-01-19 10:06:00 +00006339 // If we're dealing with an array type, decay to the pointer.
6340 if (Ty->isArrayType())
6341 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6342
6343 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006344 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006345
Chandler Carruth6a577462010-12-13 01:44:01 +00006346 // Flag if we ever add a non-record type.
6347 const RecordType *TyRec = Ty->getAs<RecordType>();
6348 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6349
Chandler Carruth6a577462010-12-13 01:44:01 +00006350 // Flag if we encounter an arithmetic type.
6351 HasArithmeticOrEnumeralTypes =
6352 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6353
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006354 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6355 PointerTypes.insert(Ty);
6356 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006357 // Insert our type, and its more-qualified variants, into the set
6358 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006359 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006360 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006361 } else if (Ty->isMemberPointerType()) {
6362 // Member pointers are far easier, since the pointee can't be converted.
6363 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6364 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006365 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006366 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006367 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006368 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006369 // We treat vector types as arithmetic types in many contexts as an
6370 // extension.
6371 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006372 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006373 } else if (Ty->isNullPtrType()) {
6374 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006375 } else if (AllowUserConversions && TyRec) {
6376 // No conversion functions in incomplete types.
6377 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6378 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006379
Chandler Carruth6a577462010-12-13 01:44:01 +00006380 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006381 std::pair<CXXRecordDecl::conversion_iterator,
6382 CXXRecordDecl::conversion_iterator>
6383 Conversions = ClassDecl->getVisibleConversionFunctions();
6384 for (CXXRecordDecl::conversion_iterator
6385 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006386 NamedDecl *D = I.getDecl();
6387 if (isa<UsingShadowDecl>(D))
6388 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006389
Chandler Carruth6a577462010-12-13 01:44:01 +00006390 // Skip conversion function templates; they don't tell us anything
6391 // about which builtin types we can convert to.
6392 if (isa<FunctionTemplateDecl>(D))
6393 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006394
Chandler Carruth6a577462010-12-13 01:44:01 +00006395 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6396 if (AllowExplicitConversions || !Conv->isExplicit()) {
6397 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6398 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006399 }
6400 }
6401 }
6402}
6403
Douglas Gregor19b7b152009-08-24 13:43:27 +00006404/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6405/// the volatile- and non-volatile-qualified assignment operators for the
6406/// given type to the candidate set.
6407static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6408 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006409 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006410 OverloadCandidateSet &CandidateSet) {
6411 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006412
Douglas Gregor19b7b152009-08-24 13:43:27 +00006413 // T& operator=(T&, T)
6414 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6415 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006416 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006417 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006418
Douglas Gregor19b7b152009-08-24 13:43:27 +00006419 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6420 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006421 ParamTypes[0]
6422 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006423 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006424 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006425 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006426 }
6427}
Mike Stump1eb44332009-09-09 15:08:12 +00006428
Sebastian Redl9994a342009-10-25 17:03:50 +00006429/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6430/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006431static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6432 Qualifiers VRQuals;
6433 const RecordType *TyRec;
6434 if (const MemberPointerType *RHSMPType =
6435 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006436 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006437 else
6438 TyRec = ArgExpr->getType()->getAs<RecordType>();
6439 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006440 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006441 VRQuals.addVolatile();
6442 VRQuals.addRestrict();
6443 return VRQuals;
6444 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006445
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006446 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006447 if (!ClassDecl->hasDefinition())
6448 return VRQuals;
6449
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006450 std::pair<CXXRecordDecl::conversion_iterator,
6451 CXXRecordDecl::conversion_iterator>
6452 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006453
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006454 for (CXXRecordDecl::conversion_iterator
6455 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006456 NamedDecl *D = I.getDecl();
6457 if (isa<UsingShadowDecl>(D))
6458 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6459 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006460 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6461 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6462 CanTy = ResTypeRef->getPointeeType();
6463 // Need to go down the pointer/mempointer chain and add qualifiers
6464 // as see them.
6465 bool done = false;
6466 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006467 if (CanTy.isRestrictQualified())
6468 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006469 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6470 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006471 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006472 CanTy->getAs<MemberPointerType>())
6473 CanTy = ResTypeMPtr->getPointeeType();
6474 else
6475 done = true;
6476 if (CanTy.isVolatileQualified())
6477 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006478 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6479 return VRQuals;
6480 }
6481 }
6482 }
6483 return VRQuals;
6484}
John McCall00071ec2010-11-13 05:51:15 +00006485
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006486namespace {
John McCall00071ec2010-11-13 05:51:15 +00006487
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006488/// \brief Helper class to manage the addition of builtin operator overload
6489/// candidates. It provides shared state and utility methods used throughout
6490/// the process, as well as a helper method to add each group of builtin
6491/// operator overloads from the standard to a candidate set.
6492class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006493 // Common instance state available to all overload candidate addition methods.
6494 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006495 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006496 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006497 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006498 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006499 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006500
Chandler Carruth6d695582010-12-12 10:35:00 +00006501 // Define some constants used to index and iterate over the arithemetic types
6502 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006503 // The "promoted arithmetic types" are the arithmetic
6504 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006505 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006506 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006507 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006508 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006509 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006510 LastPromotedArithmeticType = 11;
6511 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006512
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 /// \brief Get the canonical type for a given arithmetic type index.
6514 CanQualType getArithmeticType(unsigned index) {
6515 assert(index < NumArithmeticTypes);
6516 static CanQualType ASTContext::* const
6517 ArithmeticTypes[NumArithmeticTypes] = {
6518 // Start of promoted types.
6519 &ASTContext::FloatTy,
6520 &ASTContext::DoubleTy,
6521 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006522
Chandler Carruth6d695582010-12-12 10:35:00 +00006523 // Start of integral types.
6524 &ASTContext::IntTy,
6525 &ASTContext::LongTy,
6526 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006527 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006528 &ASTContext::UnsignedIntTy,
6529 &ASTContext::UnsignedLongTy,
6530 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006531 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006532 // End of promoted types.
6533
6534 &ASTContext::BoolTy,
6535 &ASTContext::CharTy,
6536 &ASTContext::WCharTy,
6537 &ASTContext::Char16Ty,
6538 &ASTContext::Char32Ty,
6539 &ASTContext::SignedCharTy,
6540 &ASTContext::ShortTy,
6541 &ASTContext::UnsignedCharTy,
6542 &ASTContext::UnsignedShortTy,
6543 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006544 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006545 };
6546 return S.Context.*ArithmeticTypes[index];
6547 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006548
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006549 /// \brief Gets the canonical type resulting from the usual arithemetic
6550 /// converions for the given arithmetic types.
6551 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6552 // Accelerator table for performing the usual arithmetic conversions.
6553 // The rules are basically:
6554 // - if either is floating-point, use the wider floating-point
6555 // - if same signedness, use the higher rank
6556 // - if same size, use unsigned of the higher rank
6557 // - use the larger type
6558 // These rules, together with the axiom that higher ranks are
6559 // never smaller, are sufficient to precompute all of these results
6560 // *except* when dealing with signed types of higher rank.
6561 // (we could precompute SLL x UI for all known platforms, but it's
6562 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006563 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006564 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006565 Dep=-1,
6566 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006567 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006568 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006569 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006570/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6571/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6572/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6573/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6574/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6575/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6576/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6577/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6578/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6579/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6580/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006581 };
6582
6583 assert(L < LastPromotedArithmeticType);
6584 assert(R < LastPromotedArithmeticType);
6585 int Idx = ConversionsTable[L][R];
6586
6587 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006588 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006589
6590 // Slow path: we need to compare widths.
6591 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006592 CanQualType LT = getArithmeticType(L),
6593 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006594 unsigned LW = S.Context.getIntWidth(LT),
6595 RW = S.Context.getIntWidth(RT);
6596
6597 // If they're different widths, use the signed type.
6598 if (LW > RW) return LT;
6599 else if (LW < RW) return RT;
6600
6601 // Otherwise, use the unsigned type of the signed type's rank.
6602 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6603 assert(L == SLL || R == SLL);
6604 return S.Context.UnsignedLongLongTy;
6605 }
6606
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006607 /// \brief Helper method to factor out the common pattern of adding overloads
6608 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006609 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006610 bool HasVolatile,
6611 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006612 QualType ParamTypes[2] = {
6613 S.Context.getLValueReferenceType(CandidateTy),
6614 S.Context.IntTy
6615 };
6616
6617 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006618 if (Args.size() == 1)
6619 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006620 else
Richard Smith958ba642013-05-05 15:51:06 +00006621 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006622
6623 // Use a heuristic to reduce number of builtin candidates in the set:
6624 // add volatile version only if there are conversions to a volatile type.
6625 if (HasVolatile) {
6626 ParamTypes[0] =
6627 S.Context.getLValueReferenceType(
6628 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006629 if (Args.size() == 1)
6630 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006631 else
Richard Smith958ba642013-05-05 15:51:06 +00006632 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006633 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006634
6635 // Add restrict version only if there are conversions to a restrict type
6636 // and our candidate type is a non-restrict-qualified pointer.
6637 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6638 !CandidateTy.isRestrictQualified()) {
6639 ParamTypes[0]
6640 = S.Context.getLValueReferenceType(
6641 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006642 if (Args.size() == 1)
6643 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006644 else
Richard Smith958ba642013-05-05 15:51:06 +00006645 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006646
6647 if (HasVolatile) {
6648 ParamTypes[0]
6649 = S.Context.getLValueReferenceType(
6650 S.Context.getCVRQualifiedType(CandidateTy,
6651 (Qualifiers::Volatile |
6652 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006653 if (Args.size() == 1)
6654 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006655 else
Richard Smith958ba642013-05-05 15:51:06 +00006656 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006657 }
6658 }
6659
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006660 }
6661
6662public:
6663 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006664 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006665 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006666 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006667 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006668 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006669 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006670 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006671 HasArithmeticOrEnumeralCandidateType(
6672 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006673 CandidateTypes(CandidateTypes),
6674 CandidateSet(CandidateSet) {
6675 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006676 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006677 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006678 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006679 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006680 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006681 assert(getArithmeticType(FirstPromotedArithmeticType)
6682 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006683 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006684 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006685 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006686 "Invalid last promoted arithmetic type");
6687 }
6688
6689 // C++ [over.built]p3:
6690 //
6691 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6692 // is either volatile or empty, there exist candidate operator
6693 // functions of the form
6694 //
6695 // VQ T& operator++(VQ T&);
6696 // T operator++(VQ T&, int);
6697 //
6698 // C++ [over.built]p4:
6699 //
6700 // For every pair (T, VQ), where T is an arithmetic type other
6701 // than bool, and VQ is either volatile or empty, there exist
6702 // candidate operator functions of the form
6703 //
6704 // VQ T& operator--(VQ T&);
6705 // T operator--(VQ T&, int);
6706 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006707 if (!HasArithmeticOrEnumeralCandidateType)
6708 return;
6709
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006710 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6711 Arith < NumArithmeticTypes; ++Arith) {
6712 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006713 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006714 VisibleTypeConversionsQuals.hasVolatile(),
6715 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006716 }
6717 }
6718
6719 // C++ [over.built]p5:
6720 //
6721 // For every pair (T, VQ), where T is a cv-qualified or
6722 // cv-unqualified object type, and VQ is either volatile or
6723 // empty, there exist candidate operator functions of the form
6724 //
6725 // T*VQ& operator++(T*VQ&);
6726 // T*VQ& operator--(T*VQ&);
6727 // T* operator++(T*VQ&, int);
6728 // T* operator--(T*VQ&, int);
6729 void addPlusPlusMinusMinusPointerOverloads() {
6730 for (BuiltinCandidateTypeSet::iterator
6731 Ptr = CandidateTypes[0].pointer_begin(),
6732 PtrEnd = CandidateTypes[0].pointer_end();
6733 Ptr != PtrEnd; ++Ptr) {
6734 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006735 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006736 continue;
6737
6738 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006739 (!(*Ptr).isVolatileQualified() &&
6740 VisibleTypeConversionsQuals.hasVolatile()),
6741 (!(*Ptr).isRestrictQualified() &&
6742 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006743 }
6744 }
6745
6746 // C++ [over.built]p6:
6747 // For every cv-qualified or cv-unqualified object type T, there
6748 // exist candidate operator functions of the form
6749 //
6750 // T& operator*(T*);
6751 //
6752 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006753 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006754 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006755 // T& operator*(T*);
6756 void addUnaryStarPointerOverloads() {
6757 for (BuiltinCandidateTypeSet::iterator
6758 Ptr = CandidateTypes[0].pointer_begin(),
6759 PtrEnd = CandidateTypes[0].pointer_end();
6760 Ptr != PtrEnd; ++Ptr) {
6761 QualType ParamTy = *Ptr;
6762 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006763 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6764 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006765
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006766 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6767 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6768 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006769
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006770 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006771 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006772 }
6773 }
6774
6775 // C++ [over.built]p9:
6776 // For every promoted arithmetic type T, there exist candidate
6777 // operator functions of the form
6778 //
6779 // T operator+(T);
6780 // T operator-(T);
6781 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006782 if (!HasArithmeticOrEnumeralCandidateType)
6783 return;
6784
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006785 for (unsigned Arith = FirstPromotedArithmeticType;
6786 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006787 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006788 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006789 }
6790
6791 // Extension: We also add these operators for vector types.
6792 for (BuiltinCandidateTypeSet::iterator
6793 Vec = CandidateTypes[0].vector_begin(),
6794 VecEnd = CandidateTypes[0].vector_end();
6795 Vec != VecEnd; ++Vec) {
6796 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006797 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006798 }
6799 }
6800
6801 // C++ [over.built]p8:
6802 // For every type T, there exist candidate operator functions of
6803 // the form
6804 //
6805 // T* operator+(T*);
6806 void addUnaryPlusPointerOverloads() {
6807 for (BuiltinCandidateTypeSet::iterator
6808 Ptr = CandidateTypes[0].pointer_begin(),
6809 PtrEnd = CandidateTypes[0].pointer_end();
6810 Ptr != PtrEnd; ++Ptr) {
6811 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006812 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006813 }
6814 }
6815
6816 // C++ [over.built]p10:
6817 // For every promoted integral type T, there exist candidate
6818 // operator functions of the form
6819 //
6820 // T operator~(T);
6821 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006822 if (!HasArithmeticOrEnumeralCandidateType)
6823 return;
6824
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006825 for (unsigned Int = FirstPromotedIntegralType;
6826 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006827 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006828 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006829 }
6830
6831 // Extension: We also add this operator for vector types.
6832 for (BuiltinCandidateTypeSet::iterator
6833 Vec = CandidateTypes[0].vector_begin(),
6834 VecEnd = CandidateTypes[0].vector_end();
6835 Vec != VecEnd; ++Vec) {
6836 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006837 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006838 }
6839 }
6840
6841 // C++ [over.match.oper]p16:
6842 // For every pointer to member type T, there exist candidate operator
6843 // functions of the form
6844 //
6845 // bool operator==(T,T);
6846 // bool operator!=(T,T);
6847 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6848 /// Set of (canonical) types that we've already handled.
6849 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6850
Richard Smith958ba642013-05-05 15:51:06 +00006851 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006852 for (BuiltinCandidateTypeSet::iterator
6853 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6854 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6855 MemPtr != MemPtrEnd;
6856 ++MemPtr) {
6857 // Don't add the same builtin candidate twice.
6858 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6859 continue;
6860
6861 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006862 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006863 }
6864 }
6865 }
6866
6867 // C++ [over.built]p15:
6868 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006869 // For every T, where T is an enumeration type, a pointer type, or
6870 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006871 //
6872 // bool operator<(T, T);
6873 // bool operator>(T, T);
6874 // bool operator<=(T, T);
6875 // bool operator>=(T, T);
6876 // bool operator==(T, T);
6877 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006878 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006879 // C++ [over.match.oper]p3:
6880 // [...]the built-in candidates include all of the candidate operator
6881 // functions defined in 13.6 that, compared to the given operator, [...]
6882 // do not have the same parameter-type-list as any non-template non-member
6883 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006884 //
Eli Friedman97c67392012-09-18 21:52:24 +00006885 // Note that in practice, this only affects enumeration types because there
6886 // aren't any built-in candidates of record type, and a user-defined operator
6887 // must have an operand of record or enumeration type. Also, the only other
6888 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006889 // cannot be overloaded for enumeration types, so this is the only place
6890 // where we must suppress candidates like this.
6891 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6892 UserDefinedBinaryOperators;
6893
Richard Smith958ba642013-05-05 15:51:06 +00006894 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006895 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6896 CandidateTypes[ArgIdx].enumeration_end()) {
6897 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6898 CEnd = CandidateSet.end();
6899 C != CEnd; ++C) {
6900 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6901 continue;
6902
Eli Friedman97c67392012-09-18 21:52:24 +00006903 if (C->Function->isFunctionTemplateSpecialization())
6904 continue;
6905
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006906 QualType FirstParamType =
6907 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6908 QualType SecondParamType =
6909 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6910
6911 // Skip if either parameter isn't of enumeral type.
6912 if (!FirstParamType->isEnumeralType() ||
6913 !SecondParamType->isEnumeralType())
6914 continue;
6915
6916 // Add this operator to the set of known user-defined operators.
6917 UserDefinedBinaryOperators.insert(
6918 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6919 S.Context.getCanonicalType(SecondParamType)));
6920 }
6921 }
6922 }
6923
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006924 /// Set of (canonical) types that we've already handled.
6925 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6926
Richard Smith958ba642013-05-05 15:51:06 +00006927 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006928 for (BuiltinCandidateTypeSet::iterator
6929 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6930 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6931 Ptr != PtrEnd; ++Ptr) {
6932 // Don't add the same builtin candidate twice.
6933 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6934 continue;
6935
6936 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00006937 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006938 }
6939 for (BuiltinCandidateTypeSet::iterator
6940 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6941 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6942 Enum != EnumEnd; ++Enum) {
6943 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6944
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006945 // Don't add the same builtin candidate twice, or if a user defined
6946 // candidate exists.
6947 if (!AddedTypes.insert(CanonType) ||
6948 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6949 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 continue;
6951
6952 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00006953 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006954 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006955
6956 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6957 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6958 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00006959 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006960 NullPtrTy))) {
6961 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00006962 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006963 CandidateSet);
6964 }
6965 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006966 }
6967 }
6968
6969 // C++ [over.built]p13:
6970 //
6971 // For every cv-qualified or cv-unqualified object type T
6972 // there exist candidate operator functions of the form
6973 //
6974 // T* operator+(T*, ptrdiff_t);
6975 // T& operator[](T*, ptrdiff_t); [BELOW]
6976 // T* operator-(T*, ptrdiff_t);
6977 // T* operator+(ptrdiff_t, T*);
6978 // T& operator[](ptrdiff_t, T*); [BELOW]
6979 //
6980 // C++ [over.built]p14:
6981 //
6982 // For every T, where T is a pointer to object type, there
6983 // exist candidate operator functions of the form
6984 //
6985 // ptrdiff_t operator-(T, T);
6986 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6987 /// Set of (canonical) types that we've already handled.
6988 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6989
6990 for (int Arg = 0; Arg < 2; ++Arg) {
6991 QualType AsymetricParamTypes[2] = {
6992 S.Context.getPointerDiffType(),
6993 S.Context.getPointerDiffType(),
6994 };
6995 for (BuiltinCandidateTypeSet::iterator
6996 Ptr = CandidateTypes[Arg].pointer_begin(),
6997 PtrEnd = CandidateTypes[Arg].pointer_end();
6998 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006999 QualType PointeeTy = (*Ptr)->getPointeeType();
7000 if (!PointeeTy->isObjectType())
7001 continue;
7002
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007003 AsymetricParamTypes[Arg] = *Ptr;
7004 if (Arg == 0 || Op == OO_Plus) {
7005 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7006 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007007 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007008 }
7009 if (Op == OO_Minus) {
7010 // ptrdiff_t operator-(T, T);
7011 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7012 continue;
7013
7014 QualType ParamTypes[2] = { *Ptr, *Ptr };
7015 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007016 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007017 }
7018 }
7019 }
7020 }
7021
7022 // C++ [over.built]p12:
7023 //
7024 // For every pair of promoted arithmetic types L and R, there
7025 // exist candidate operator functions of the form
7026 //
7027 // LR operator*(L, R);
7028 // LR operator/(L, R);
7029 // LR operator+(L, R);
7030 // LR operator-(L, R);
7031 // bool operator<(L, R);
7032 // bool operator>(L, R);
7033 // bool operator<=(L, R);
7034 // bool operator>=(L, R);
7035 // bool operator==(L, R);
7036 // bool operator!=(L, R);
7037 //
7038 // where LR is the result of the usual arithmetic conversions
7039 // between types L and R.
7040 //
7041 // C++ [over.built]p24:
7042 //
7043 // For every pair of promoted arithmetic types L and R, there exist
7044 // candidate operator functions of the form
7045 //
7046 // LR operator?(bool, L, R);
7047 //
7048 // where LR is the result of the usual arithmetic conversions
7049 // between types L and R.
7050 // Our candidates ignore the first parameter.
7051 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007052 if (!HasArithmeticOrEnumeralCandidateType)
7053 return;
7054
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007055 for (unsigned Left = FirstPromotedArithmeticType;
7056 Left < LastPromotedArithmeticType; ++Left) {
7057 for (unsigned Right = FirstPromotedArithmeticType;
7058 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007059 QualType LandR[2] = { getArithmeticType(Left),
7060 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007061 QualType Result =
7062 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007063 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007064 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007065 }
7066 }
7067
7068 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7069 // conditional operator for vector types.
7070 for (BuiltinCandidateTypeSet::iterator
7071 Vec1 = CandidateTypes[0].vector_begin(),
7072 Vec1End = CandidateTypes[0].vector_end();
7073 Vec1 != Vec1End; ++Vec1) {
7074 for (BuiltinCandidateTypeSet::iterator
7075 Vec2 = CandidateTypes[1].vector_begin(),
7076 Vec2End = CandidateTypes[1].vector_end();
7077 Vec2 != Vec2End; ++Vec2) {
7078 QualType LandR[2] = { *Vec1, *Vec2 };
7079 QualType Result = S.Context.BoolTy;
7080 if (!isComparison) {
7081 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7082 Result = *Vec1;
7083 else
7084 Result = *Vec2;
7085 }
7086
Richard Smith958ba642013-05-05 15:51:06 +00007087 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007088 }
7089 }
7090 }
7091
7092 // C++ [over.built]p17:
7093 //
7094 // For every pair of promoted integral types L and R, there
7095 // exist candidate operator functions of the form
7096 //
7097 // LR operator%(L, R);
7098 // LR operator&(L, R);
7099 // LR operator^(L, R);
7100 // LR operator|(L, R);
7101 // L operator<<(L, R);
7102 // L operator>>(L, R);
7103 //
7104 // where LR is the result of the usual arithmetic conversions
7105 // between types L and R.
7106 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007107 if (!HasArithmeticOrEnumeralCandidateType)
7108 return;
7109
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007110 for (unsigned Left = FirstPromotedIntegralType;
7111 Left < LastPromotedIntegralType; ++Left) {
7112 for (unsigned Right = FirstPromotedIntegralType;
7113 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007114 QualType LandR[2] = { getArithmeticType(Left),
7115 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007116 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7117 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007118 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007119 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007120 }
7121 }
7122 }
7123
7124 // C++ [over.built]p20:
7125 //
7126 // For every pair (T, VQ), where T is an enumeration or
7127 // pointer to member type and VQ is either volatile or
7128 // empty, there exist candidate operator functions of the form
7129 //
7130 // VQ T& operator=(VQ T&, T);
7131 void addAssignmentMemberPointerOrEnumeralOverloads() {
7132 /// Set of (canonical) types that we've already handled.
7133 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7134
7135 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7136 for (BuiltinCandidateTypeSet::iterator
7137 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7138 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7139 Enum != EnumEnd; ++Enum) {
7140 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7141 continue;
7142
Richard Smith958ba642013-05-05 15:51:06 +00007143 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007144 }
7145
7146 for (BuiltinCandidateTypeSet::iterator
7147 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7148 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7149 MemPtr != MemPtrEnd; ++MemPtr) {
7150 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7151 continue;
7152
Richard Smith958ba642013-05-05 15:51:06 +00007153 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007154 }
7155 }
7156 }
7157
7158 // C++ [over.built]p19:
7159 //
7160 // For every pair (T, VQ), where T is any type and VQ is either
7161 // volatile or empty, there exist candidate operator functions
7162 // of the form
7163 //
7164 // T*VQ& operator=(T*VQ&, T*);
7165 //
7166 // C++ [over.built]p21:
7167 //
7168 // For every pair (T, VQ), where T is a cv-qualified or
7169 // cv-unqualified object type and VQ is either volatile or
7170 // empty, there exist candidate operator functions of the form
7171 //
7172 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7173 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7174 void addAssignmentPointerOverloads(bool isEqualOp) {
7175 /// Set of (canonical) types that we've already handled.
7176 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7177
7178 for (BuiltinCandidateTypeSet::iterator
7179 Ptr = CandidateTypes[0].pointer_begin(),
7180 PtrEnd = CandidateTypes[0].pointer_end();
7181 Ptr != PtrEnd; ++Ptr) {
7182 // If this is operator=, keep track of the builtin candidates we added.
7183 if (isEqualOp)
7184 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007185 else if (!(*Ptr)->getPointeeType()->isObjectType())
7186 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007187
7188 // non-volatile version
7189 QualType ParamTypes[2] = {
7190 S.Context.getLValueReferenceType(*Ptr),
7191 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7192 };
Richard Smith958ba642013-05-05 15:51:06 +00007193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007194 /*IsAssigmentOperator=*/ isEqualOp);
7195
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007196 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7197 VisibleTypeConversionsQuals.hasVolatile();
7198 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007199 // volatile version
7200 ParamTypes[0] =
7201 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007203 /*IsAssigmentOperator=*/isEqualOp);
7204 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007205
7206 if (!(*Ptr).isRestrictQualified() &&
7207 VisibleTypeConversionsQuals.hasRestrict()) {
7208 // restrict version
7209 ParamTypes[0]
7210 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007211 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007212 /*IsAssigmentOperator=*/isEqualOp);
7213
7214 if (NeedVolatile) {
7215 // volatile restrict version
7216 ParamTypes[0]
7217 = S.Context.getLValueReferenceType(
7218 S.Context.getCVRQualifiedType(*Ptr,
7219 (Qualifiers::Volatile |
7220 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007222 /*IsAssigmentOperator=*/isEqualOp);
7223 }
7224 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 }
7226
7227 if (isEqualOp) {
7228 for (BuiltinCandidateTypeSet::iterator
7229 Ptr = CandidateTypes[1].pointer_begin(),
7230 PtrEnd = CandidateTypes[1].pointer_end();
7231 Ptr != PtrEnd; ++Ptr) {
7232 // Make sure we don't add the same candidate twice.
7233 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7234 continue;
7235
Chandler Carruth6df868e2010-12-12 08:17:55 +00007236 QualType ParamTypes[2] = {
7237 S.Context.getLValueReferenceType(*Ptr),
7238 *Ptr,
7239 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007240
7241 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007242 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 /*IsAssigmentOperator=*/true);
7244
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007245 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7246 VisibleTypeConversionsQuals.hasVolatile();
7247 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007248 // volatile version
7249 ParamTypes[0] =
7250 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007251 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7252 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007253 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007254
7255 if (!(*Ptr).isRestrictQualified() &&
7256 VisibleTypeConversionsQuals.hasRestrict()) {
7257 // restrict version
7258 ParamTypes[0]
7259 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7261 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007262
7263 if (NeedVolatile) {
7264 // volatile restrict version
7265 ParamTypes[0]
7266 = S.Context.getLValueReferenceType(
7267 S.Context.getCVRQualifiedType(*Ptr,
7268 (Qualifiers::Volatile |
7269 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7271 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007272 }
7273 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007274 }
7275 }
7276 }
7277
7278 // C++ [over.built]p18:
7279 //
7280 // For every triple (L, VQ, R), where L is an arithmetic type,
7281 // VQ is either volatile or empty, and R is a promoted
7282 // arithmetic type, there exist candidate operator functions of
7283 // the form
7284 //
7285 // VQ L& operator=(VQ L&, R);
7286 // VQ L& operator*=(VQ L&, R);
7287 // VQ L& operator/=(VQ L&, R);
7288 // VQ L& operator+=(VQ L&, R);
7289 // VQ L& operator-=(VQ L&, R);
7290 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007291 if (!HasArithmeticOrEnumeralCandidateType)
7292 return;
7293
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007294 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7295 for (unsigned Right = FirstPromotedArithmeticType;
7296 Right < LastPromotedArithmeticType; ++Right) {
7297 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007298 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007299
7300 // Add this built-in operator as a candidate (VQ is empty).
7301 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007302 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007303 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007304 /*IsAssigmentOperator=*/isEqualOp);
7305
7306 // Add this built-in operator as a candidate (VQ is 'volatile').
7307 if (VisibleTypeConversionsQuals.hasVolatile()) {
7308 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007309 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007310 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007312 /*IsAssigmentOperator=*/isEqualOp);
7313 }
7314 }
7315 }
7316
7317 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7318 for (BuiltinCandidateTypeSet::iterator
7319 Vec1 = CandidateTypes[0].vector_begin(),
7320 Vec1End = CandidateTypes[0].vector_end();
7321 Vec1 != Vec1End; ++Vec1) {
7322 for (BuiltinCandidateTypeSet::iterator
7323 Vec2 = CandidateTypes[1].vector_begin(),
7324 Vec2End = CandidateTypes[1].vector_end();
7325 Vec2 != Vec2End; ++Vec2) {
7326 QualType ParamTypes[2];
7327 ParamTypes[1] = *Vec2;
7328 // Add this built-in operator as a candidate (VQ is empty).
7329 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007331 /*IsAssigmentOperator=*/isEqualOp);
7332
7333 // Add this built-in operator as a candidate (VQ is 'volatile').
7334 if (VisibleTypeConversionsQuals.hasVolatile()) {
7335 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7336 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007337 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007338 /*IsAssigmentOperator=*/isEqualOp);
7339 }
7340 }
7341 }
7342 }
7343
7344 // C++ [over.built]p22:
7345 //
7346 // For every triple (L, VQ, R), where L is an integral type, VQ
7347 // is either volatile or empty, and R is a promoted integral
7348 // type, there exist candidate operator functions of the form
7349 //
7350 // VQ L& operator%=(VQ L&, R);
7351 // VQ L& operator<<=(VQ L&, R);
7352 // VQ L& operator>>=(VQ L&, R);
7353 // VQ L& operator&=(VQ L&, R);
7354 // VQ L& operator^=(VQ L&, R);
7355 // VQ L& operator|=(VQ L&, R);
7356 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007357 if (!HasArithmeticOrEnumeralCandidateType)
7358 return;
7359
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007360 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7361 for (unsigned Right = FirstPromotedIntegralType;
7362 Right < LastPromotedIntegralType; ++Right) {
7363 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007364 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007365
7366 // Add this built-in operator as a candidate (VQ is empty).
7367 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007368 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370 if (VisibleTypeConversionsQuals.hasVolatile()) {
7371 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007372 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007373 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007376 }
7377 }
7378 }
7379 }
7380
7381 // C++ [over.operator]p23:
7382 //
7383 // There also exist candidate operator functions of the form
7384 //
7385 // bool operator!(bool);
7386 // bool operator&&(bool, bool);
7387 // bool operator||(bool, bool);
7388 void addExclaimOverload() {
7389 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007390 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007391 /*IsAssignmentOperator=*/false,
7392 /*NumContextualBoolArguments=*/1);
7393 }
7394 void addAmpAmpOrPipePipeOverload() {
7395 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007396 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397 /*IsAssignmentOperator=*/false,
7398 /*NumContextualBoolArguments=*/2);
7399 }
7400
7401 // C++ [over.built]p13:
7402 //
7403 // For every cv-qualified or cv-unqualified object type T there
7404 // exist candidate operator functions of the form
7405 //
7406 // T* operator+(T*, ptrdiff_t); [ABOVE]
7407 // T& operator[](T*, ptrdiff_t);
7408 // T* operator-(T*, ptrdiff_t); [ABOVE]
7409 // T* operator+(ptrdiff_t, T*); [ABOVE]
7410 // T& operator[](ptrdiff_t, T*);
7411 void addSubscriptOverloads() {
7412 for (BuiltinCandidateTypeSet::iterator
7413 Ptr = CandidateTypes[0].pointer_begin(),
7414 PtrEnd = CandidateTypes[0].pointer_end();
7415 Ptr != PtrEnd; ++Ptr) {
7416 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7417 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007418 if (!PointeeType->isObjectType())
7419 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007420
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007421 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7422
7423 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007424 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007425 }
7426
7427 for (BuiltinCandidateTypeSet::iterator
7428 Ptr = CandidateTypes[1].pointer_begin(),
7429 PtrEnd = CandidateTypes[1].pointer_end();
7430 Ptr != PtrEnd; ++Ptr) {
7431 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7432 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007433 if (!PointeeType->isObjectType())
7434 continue;
7435
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007436 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7437
7438 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007439 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007440 }
7441 }
7442
7443 // C++ [over.built]p11:
7444 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7445 // C1 is the same type as C2 or is a derived class of C2, T is an object
7446 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7447 // there exist candidate operator functions of the form
7448 //
7449 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7450 //
7451 // where CV12 is the union of CV1 and CV2.
7452 void addArrowStarOverloads() {
7453 for (BuiltinCandidateTypeSet::iterator
7454 Ptr = CandidateTypes[0].pointer_begin(),
7455 PtrEnd = CandidateTypes[0].pointer_end();
7456 Ptr != PtrEnd; ++Ptr) {
7457 QualType C1Ty = (*Ptr);
7458 QualType C1;
7459 QualifierCollector Q1;
7460 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7461 if (!isa<RecordType>(C1))
7462 continue;
7463 // heuristic to reduce number of builtin candidates in the set.
7464 // Add volatile/restrict version only if there are conversions to a
7465 // volatile/restrict type.
7466 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7467 continue;
7468 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7469 continue;
7470 for (BuiltinCandidateTypeSet::iterator
7471 MemPtr = CandidateTypes[1].member_pointer_begin(),
7472 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7473 MemPtr != MemPtrEnd; ++MemPtr) {
7474 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7475 QualType C2 = QualType(mptr->getClass(), 0);
7476 C2 = C2.getUnqualifiedType();
7477 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7478 break;
7479 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7480 // build CV12 T&
7481 QualType T = mptr->getPointeeType();
7482 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7483 T.isVolatileQualified())
7484 continue;
7485 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7486 T.isRestrictQualified())
7487 continue;
7488 T = Q1.apply(S.Context, T);
7489 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007490 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007491 }
7492 }
7493 }
7494
7495 // Note that we don't consider the first argument, since it has been
7496 // contextually converted to bool long ago. The candidates below are
7497 // therefore added as binary.
7498 //
7499 // C++ [over.built]p25:
7500 // For every type T, where T is a pointer, pointer-to-member, or scoped
7501 // enumeration type, there exist candidate operator functions of the form
7502 //
7503 // T operator?(bool, T, T);
7504 //
7505 void addConditionalOperatorOverloads() {
7506 /// Set of (canonical) types that we've already handled.
7507 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7508
7509 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7510 for (BuiltinCandidateTypeSet::iterator
7511 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7512 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7513 Ptr != PtrEnd; ++Ptr) {
7514 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7515 continue;
7516
7517 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007518 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007519 }
7520
7521 for (BuiltinCandidateTypeSet::iterator
7522 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7523 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7524 MemPtr != MemPtrEnd; ++MemPtr) {
7525 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7526 continue;
7527
7528 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007529 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007530 }
7531
Richard Smith80ad52f2013-01-02 11:42:31 +00007532 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007533 for (BuiltinCandidateTypeSet::iterator
7534 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7535 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7536 Enum != EnumEnd; ++Enum) {
7537 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7538 continue;
7539
7540 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7541 continue;
7542
7543 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007544 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007545 }
7546 }
7547 }
7548 }
7549};
7550
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007551} // end anonymous namespace
7552
7553/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7554/// operator overloads to the candidate set (C++ [over.built]), based
7555/// on the operator @p Op and the arguments given. For example, if the
7556/// operator is a binary '+', this routine might add "int
7557/// operator+(int, int)" to cover integer addition.
7558void
7559Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7560 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007561 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007563 // Find all of the types that the arguments can convert to, but only
7564 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007565 // that make use of these types. Also record whether we encounter non-record
7566 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007567 Qualifiers VisibleTypeConversionsQuals;
7568 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007569 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007570 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007571
7572 bool HasNonRecordCandidateType = false;
7573 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007574 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007575 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007576 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7577 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7578 OpLoc,
7579 true,
7580 (Op == OO_Exclaim ||
7581 Op == OO_AmpAmp ||
7582 Op == OO_PipePipe),
7583 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007584 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7585 CandidateTypes[ArgIdx].hasNonRecordTypes();
7586 HasArithmeticOrEnumeralCandidateType =
7587 HasArithmeticOrEnumeralCandidateType ||
7588 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007589 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007590
Chandler Carruth6a577462010-12-13 01:44:01 +00007591 // Exit early when no non-record types have been added to the candidate set
7592 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007593 //
7594 // We can't exit early for !, ||, or &&, since there we have always have
7595 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007596 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007597 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007598 return;
7599
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007600 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007601 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007602 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007603 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007604 CandidateTypes, CandidateSet);
7605
7606 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007607 switch (Op) {
7608 case OO_None:
7609 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007610 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007611
Chandler Carruthabb71842010-12-12 08:51:33 +00007612 case OO_New:
7613 case OO_Delete:
7614 case OO_Array_New:
7615 case OO_Array_Delete:
7616 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007617 llvm_unreachable(
7618 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007619
7620 case OO_Comma:
7621 case OO_Arrow:
7622 // C++ [over.match.oper]p3:
7623 // -- For the operator ',', the unary operator '&', or the
7624 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007625 break;
7626
7627 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007628 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007629 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007630 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007631
7632 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007633 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007634 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007635 } else {
7636 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7637 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7638 }
Douglas Gregor74253732008-11-19 15:42:04 +00007639 break;
7640
Chandler Carruthabb71842010-12-12 08:51:33 +00007641 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007642 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007643 OpBuilder.addUnaryStarPointerOverloads();
7644 else
7645 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7646 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007647
Chandler Carruthabb71842010-12-12 08:51:33 +00007648 case OO_Slash:
7649 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007650 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007651
7652 case OO_PlusPlus:
7653 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007654 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7655 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007656 break;
7657
Douglas Gregor19b7b152009-08-24 13:43:27 +00007658 case OO_EqualEqual:
7659 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007661 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007662
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007663 case OO_Less:
7664 case OO_Greater:
7665 case OO_LessEqual:
7666 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007667 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007668 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7669 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007670
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007671 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007672 case OO_Caret:
7673 case OO_Pipe:
7674 case OO_LessLess:
7675 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007676 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007677 break;
7678
Chandler Carruthabb71842010-12-12 08:51:33 +00007679 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007680 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007681 // C++ [over.match.oper]p3:
7682 // -- For the operator ',', the unary operator '&', or the
7683 // operator '->', the built-in candidates set is empty.
7684 break;
7685
7686 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7687 break;
7688
7689 case OO_Tilde:
7690 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7691 break;
7692
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007693 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007694 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007695 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007696
7697 case OO_PlusEqual:
7698 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007699 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007700 // Fall through.
7701
7702 case OO_StarEqual:
7703 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007704 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007705 break;
7706
7707 case OO_PercentEqual:
7708 case OO_LessLessEqual:
7709 case OO_GreaterGreaterEqual:
7710 case OO_AmpEqual:
7711 case OO_CaretEqual:
7712 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007713 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007714 break;
7715
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007716 case OO_Exclaim:
7717 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007718 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007719
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007720 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007721 case OO_PipePipe:
7722 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007723 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007724
7725 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007726 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007727 break;
7728
7729 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007730 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007731 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007732
7733 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007734 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7736 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007737 }
7738}
7739
Douglas Gregorfa047642009-02-04 00:32:51 +00007740/// \brief Add function candidates found via argument-dependent lookup
7741/// to the set of overloading candidates.
7742///
7743/// This routine performs argument-dependent name lookup based on the
7744/// given function name (which may also be an operator name) and adds
7745/// all of the overload candidates found by ADL to the overload
7746/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007747void
Douglas Gregorfa047642009-02-04 00:32:51 +00007748Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007749 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007750 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007751 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007752 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007753 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007754 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007755
John McCalla113e722010-01-26 06:04:06 +00007756 // FIXME: This approach for uniquing ADL results (and removing
7757 // redundant candidates from the set) relies on pointer-equality,
7758 // which means we need to key off the canonical decl. However,
7759 // always going back to the canonical decl might not get us the
7760 // right set of default arguments. What default arguments are
7761 // we supposed to consider on ADL candidates, anyway?
7762
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007763 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007764 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007765
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007766 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007767 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7768 CandEnd = CandidateSet.end();
7769 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007770 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007771 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007772 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007773 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007774 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007775
7776 // For each of the ADL candidates we found, add it to the overload
7777 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007778 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007779 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007781 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007782 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007783
Ahmed Charles13a140c2012-02-25 11:00:22 +00007784 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7785 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007786 } else
John McCall6e266892010-01-26 03:27:55 +00007787 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007788 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007789 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007790 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007791}
7792
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007793/// isBetterOverloadCandidate - Determines whether the first overload
7794/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007795bool
John McCall120d63c2010-08-24 20:38:10 +00007796isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007797 const OverloadCandidate &Cand1,
7798 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007799 SourceLocation Loc,
7800 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007801 // Define viable functions to be better candidates than non-viable
7802 // functions.
7803 if (!Cand2.Viable)
7804 return Cand1.Viable;
7805 else if (!Cand1.Viable)
7806 return false;
7807
Douglas Gregor88a35142008-12-22 05:46:06 +00007808 // C++ [over.match.best]p1:
7809 //
7810 // -- if F is a static member function, ICS1(F) is defined such
7811 // that ICS1(F) is neither better nor worse than ICS1(G) for
7812 // any function G, and, symmetrically, ICS1(G) is neither
7813 // better nor worse than ICS1(F).
7814 unsigned StartArg = 0;
7815 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7816 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007817
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007818 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007819 // A viable function F1 is defined to be a better function than another
7820 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007821 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007822 unsigned NumArgs = Cand1.NumConversions;
7823 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007824 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007825 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007826 switch (CompareImplicitConversionSequences(S,
7827 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007828 Cand2.Conversions[ArgIdx])) {
7829 case ImplicitConversionSequence::Better:
7830 // Cand1 has a better conversion sequence.
7831 HasBetterConversion = true;
7832 break;
7833
7834 case ImplicitConversionSequence::Worse:
7835 // Cand1 can't be better than Cand2.
7836 return false;
7837
7838 case ImplicitConversionSequence::Indistinguishable:
7839 // Do nothing.
7840 break;
7841 }
7842 }
7843
Mike Stump1eb44332009-09-09 15:08:12 +00007844 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007845 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007846 if (HasBetterConversion)
7847 return true;
7848
Mike Stump1eb44332009-09-09 15:08:12 +00007849 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007850 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007851 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007852 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7853 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007854
7855 // -- F1 and F2 are function template specializations, and the function
7856 // template for F1 is more specialized than the template for F2
7857 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007858 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007859 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007860 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007861 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007862 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7863 Cand2.Function->getPrimaryTemplate(),
7864 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007865 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007866 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007867 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007868 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007870
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007871 // -- the context is an initialization by user-defined conversion
7872 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7873 // from the return type of F1 to the destination type (i.e.,
7874 // the type of the entity being initialized) is a better
7875 // conversion sequence than the standard conversion sequence
7876 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007877 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007878 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007879 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007880 // First check whether we prefer one of the conversion functions over the
7881 // other. This only distinguishes the results in non-standard, extension
7882 // cases such as the conversion from a lambda closure type to a function
7883 // pointer or block.
7884 ImplicitConversionSequence::CompareKind FuncResult
7885 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7886 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7887 return FuncResult;
7888
John McCall120d63c2010-08-24 20:38:10 +00007889 switch (CompareStandardConversionSequences(S,
7890 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007891 Cand2.FinalConversion)) {
7892 case ImplicitConversionSequence::Better:
7893 // Cand1 has a better conversion sequence.
7894 return true;
7895
7896 case ImplicitConversionSequence::Worse:
7897 // Cand1 can't be better than Cand2.
7898 return false;
7899
7900 case ImplicitConversionSequence::Indistinguishable:
7901 // Do nothing
7902 break;
7903 }
7904 }
7905
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007906 return false;
7907}
7908
Mike Stump1eb44332009-09-09 15:08:12 +00007909/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007910/// within an overload candidate set.
7911///
James Dennettefce31f2012-06-22 08:10:18 +00007912/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007913/// which overload resolution occurs.
7914///
James Dennettefce31f2012-06-22 08:10:18 +00007915/// \param Best If overload resolution was successful or found a deleted
7916/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007917///
7918/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007919OverloadingResult
7920OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007921 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007922 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007923 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007924 Best = end();
7925 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7926 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007927 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007928 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007929 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007930 }
7931
7932 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007933 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007934 return OR_No_Viable_Function;
7935
7936 // Make sure that this function is better than every other viable
7937 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007938 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007939 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007940 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007941 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007942 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007943 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007944 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007945 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007946 }
Mike Stump1eb44332009-09-09 15:08:12 +00007947
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007948 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007949 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007950 (Best->Function->isDeleted() ||
7951 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007952 return OR_Deleted;
7953
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007954 return OR_Success;
7955}
7956
John McCall3c80f572010-01-12 02:15:36 +00007957namespace {
7958
7959enum OverloadCandidateKind {
7960 oc_function,
7961 oc_method,
7962 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007963 oc_function_template,
7964 oc_method_template,
7965 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007966 oc_implicit_default_constructor,
7967 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007968 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007969 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007970 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007971 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007972};
7973
John McCall220ccbf2010-01-13 00:25:19 +00007974OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7975 FunctionDecl *Fn,
7976 std::string &Description) {
7977 bool isTemplate = false;
7978
7979 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7980 isTemplate = true;
7981 Description = S.getTemplateArgumentBindingsText(
7982 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7983 }
John McCallb1622a12010-01-06 09:43:14 +00007984
7985 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007986 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007987 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007988
Sebastian Redlf677ea32011-02-05 19:23:19 +00007989 if (Ctor->getInheritedConstructor())
7990 return oc_implicit_inherited_constructor;
7991
Sean Hunt82713172011-05-25 23:16:36 +00007992 if (Ctor->isDefaultConstructor())
7993 return oc_implicit_default_constructor;
7994
7995 if (Ctor->isMoveConstructor())
7996 return oc_implicit_move_constructor;
7997
7998 assert(Ctor->isCopyConstructor() &&
7999 "unexpected sort of implicit constructor");
8000 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008001 }
8002
8003 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8004 // This actually gets spelled 'candidate function' for now, but
8005 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008006 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008007 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008008
Sean Hunt82713172011-05-25 23:16:36 +00008009 if (Meth->isMoveAssignmentOperator())
8010 return oc_implicit_move_assignment;
8011
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008012 if (Meth->isCopyAssignmentOperator())
8013 return oc_implicit_copy_assignment;
8014
8015 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8016 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008017 }
8018
John McCall220ccbf2010-01-13 00:25:19 +00008019 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008020}
8021
Sebastian Redlf677ea32011-02-05 19:23:19 +00008022void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8023 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8024 if (!Ctor) return;
8025
8026 Ctor = Ctor->getInheritedConstructor();
8027 if (!Ctor) return;
8028
8029 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8030}
8031
John McCall3c80f572010-01-12 02:15:36 +00008032} // end anonymous namespace
8033
8034// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008035void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008036 std::string FnDesc;
8037 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008038 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8039 << (unsigned) K << FnDesc;
8040 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8041 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008042 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008043}
8044
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008045//Notes the location of all overload candidates designated through
8046// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008047void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008048 assert(OverloadedExpr->getType() == Context.OverloadTy);
8049
8050 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8051 OverloadExpr *OvlExpr = Ovl.Expression;
8052
8053 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8054 IEnd = OvlExpr->decls_end();
8055 I != IEnd; ++I) {
8056 if (FunctionTemplateDecl *FunTmpl =
8057 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008058 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008059 } else if (FunctionDecl *Fun
8060 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008061 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008062 }
8063 }
8064}
8065
John McCall1d318332010-01-12 00:44:57 +00008066/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8067/// "lead" diagnostic; it will be given two arguments, the source and
8068/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008069void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8070 Sema &S,
8071 SourceLocation CaretLoc,
8072 const PartialDiagnostic &PDiag) const {
8073 S.Diag(CaretLoc, PDiag)
8074 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008075 // FIXME: The note limiting machinery is borrowed from
8076 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8077 // refactoring here.
8078 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8079 unsigned CandsShown = 0;
8080 AmbiguousConversionSequence::const_iterator I, E;
8081 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8082 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8083 break;
8084 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008085 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008086 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008087 if (I != E)
8088 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008089}
8090
John McCall1d318332010-01-12 00:44:57 +00008091namespace {
8092
John McCalladbb8f82010-01-13 09:16:55 +00008093void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8094 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8095 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008096 assert(Cand->Function && "for now, candidate must be a function");
8097 FunctionDecl *Fn = Cand->Function;
8098
8099 // There's a conversion slot for the object argument if this is a
8100 // non-constructor method. Note that 'I' corresponds the
8101 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008102 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008103 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008104 if (I == 0)
8105 isObjectArgument = true;
8106 else
8107 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008108 }
8109
John McCall220ccbf2010-01-13 00:25:19 +00008110 std::string FnDesc;
8111 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8112
John McCalladbb8f82010-01-13 09:16:55 +00008113 Expr *FromExpr = Conv.Bad.FromExpr;
8114 QualType FromTy = Conv.Bad.getFromType();
8115 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008116
John McCall5920dbb2010-02-02 02:42:52 +00008117 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008118 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008119 Expr *E = FromExpr->IgnoreParens();
8120 if (isa<UnaryOperator>(E))
8121 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008122 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008123
8124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8125 << (unsigned) FnKind << FnDesc
8126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8127 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008128 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008129 return;
8130 }
8131
John McCall258b2032010-01-23 08:10:49 +00008132 // Do some hand-waving analysis to see if the non-viability is due
8133 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008134 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8135 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8136 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8137 CToTy = RT->getPointeeType();
8138 else {
8139 // TODO: detect and diagnose the full richness of const mismatches.
8140 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8141 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8142 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8143 }
8144
8145 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8146 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008147 Qualifiers FromQs = CFromTy.getQualifiers();
8148 Qualifiers ToQs = CToTy.getQualifiers();
8149
8150 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8152 << (unsigned) FnKind << FnDesc
8153 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8154 << FromTy
8155 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8156 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008157 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008158 return;
8159 }
8160
John McCallf85e1932011-06-15 23:02:42 +00008161 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008163 << (unsigned) FnKind << FnDesc
8164 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8165 << FromTy
8166 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8167 << (unsigned) isObjectArgument << I+1;
8168 MaybeEmitInheritedConstructorNote(S, Fn);
8169 return;
8170 }
8171
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008172 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8174 << (unsigned) FnKind << FnDesc
8175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8176 << FromTy
8177 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8178 << (unsigned) isObjectArgument << I+1;
8179 MaybeEmitInheritedConstructorNote(S, Fn);
8180 return;
8181 }
8182
John McCall651f3ee2010-01-14 03:28:57 +00008183 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8184 assert(CVR && "unexpected qualifiers mismatch");
8185
8186 if (isObjectArgument) {
8187 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8188 << (unsigned) FnKind << FnDesc
8189 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8190 << FromTy << (CVR - 1);
8191 } else {
8192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8193 << (unsigned) FnKind << FnDesc
8194 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8195 << FromTy << (CVR - 1) << I+1;
8196 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008197 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008198 return;
8199 }
8200
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008201 // Special diagnostic for failure to convert an initializer list, since
8202 // telling the user that it has type void is not useful.
8203 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8204 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8205 << (unsigned) FnKind << FnDesc
8206 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8207 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8208 MaybeEmitInheritedConstructorNote(S, Fn);
8209 return;
8210 }
8211
John McCall258b2032010-01-23 08:10:49 +00008212 // Diagnose references or pointers to incomplete types differently,
8213 // since it's far from impossible that the incompleteness triggered
8214 // the failure.
8215 QualType TempFromTy = FromTy.getNonReferenceType();
8216 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8217 TempFromTy = PTy->getPointeeType();
8218 if (TempFromTy->isIncompleteType()) {
8219 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8220 << (unsigned) FnKind << FnDesc
8221 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8222 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008223 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008224 return;
8225 }
8226
Douglas Gregor85789812010-06-30 23:01:39 +00008227 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008228 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008229 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8230 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8231 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8232 FromPtrTy->getPointeeType()) &&
8233 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8234 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008235 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008236 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008237 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008238 }
8239 } else if (const ObjCObjectPointerType *FromPtrTy
8240 = FromTy->getAs<ObjCObjectPointerType>()) {
8241 if (const ObjCObjectPointerType *ToPtrTy
8242 = ToTy->getAs<ObjCObjectPointerType>())
8243 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8244 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8245 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8246 FromPtrTy->getPointeeType()) &&
8247 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008248 BaseToDerivedConversion = 2;
8249 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008250 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8251 !FromTy->isIncompleteType() &&
8252 !ToRefTy->getPointeeType()->isIncompleteType() &&
8253 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8254 BaseToDerivedConversion = 3;
8255 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8256 ToTy.getNonReferenceType().getCanonicalType() ==
8257 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008258 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8259 << (unsigned) FnKind << FnDesc
8260 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8261 << (unsigned) isObjectArgument << I + 1;
8262 MaybeEmitInheritedConstructorNote(S, Fn);
8263 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008264 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008266
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008267 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008268 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008269 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008270 << (unsigned) FnKind << FnDesc
8271 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008272 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008273 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008274 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008275 return;
8276 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008277
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008278 if (isa<ObjCObjectPointerType>(CFromTy) &&
8279 isa<PointerType>(CToTy)) {
8280 Qualifiers FromQs = CFromTy.getQualifiers();
8281 Qualifiers ToQs = CToTy.getQualifiers();
8282 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8283 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8284 << (unsigned) FnKind << FnDesc
8285 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8286 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8287 MaybeEmitInheritedConstructorNote(S, Fn);
8288 return;
8289 }
8290 }
8291
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008292 // Emit the generic diagnostic and, optionally, add the hints to it.
8293 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8294 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008295 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008296 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8297 << (unsigned) (Cand->Fix.Kind);
8298
8299 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008300 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8301 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008302 FDiag << *HI;
8303 S.Diag(Fn->getLocation(), FDiag);
8304
Sebastian Redlf677ea32011-02-05 19:23:19 +00008305 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008306}
8307
8308void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8309 unsigned NumFormalArgs) {
8310 // TODO: treat calls to a missing default constructor as a special case
8311
8312 FunctionDecl *Fn = Cand->Function;
8313 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8314
8315 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008316
Douglas Gregor439d3c32011-05-05 00:13:13 +00008317 // With invalid overloaded operators, it's possible that we think we
8318 // have an arity mismatch when it fact it looks like we have the
8319 // right number of arguments, because only overloaded operators have
8320 // the weird behavior of overloading member and non-member functions.
8321 // Just don't report anything.
8322 if (Fn->isInvalidDecl() &&
8323 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8324 return;
8325
John McCalladbb8f82010-01-13 09:16:55 +00008326 // at least / at most / exactly
8327 unsigned mode, modeCount;
8328 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008329 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8330 (Cand->FailureKind == ovl_fail_bad_deduction &&
8331 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008332 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008333 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008334 mode = 0; // "at least"
8335 else
8336 mode = 2; // "exactly"
8337 modeCount = MinParams;
8338 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008339 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8340 (Cand->FailureKind == ovl_fail_bad_deduction &&
8341 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008342 if (MinParams != FnTy->getNumArgs())
8343 mode = 1; // "at most"
8344 else
8345 mode = 2; // "exactly"
8346 modeCount = FnTy->getNumArgs();
8347 }
8348
8349 std::string Description;
8350 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8351
Richard Smithf7b80562012-05-11 05:16:41 +00008352 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8354 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8355 << Fn->getParamDecl(0) << NumFormalArgs;
8356 else
8357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8358 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8359 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008360 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008361}
8362
John McCall342fec42010-02-01 18:53:26 +00008363/// Diagnose a failed template-argument deduction.
8364void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008365 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008366 FunctionDecl *Fn = Cand->Function; // pattern
8367
Douglas Gregora9333192010-05-08 17:41:32 +00008368 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008369 NamedDecl *ParamD;
8370 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8371 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8372 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008373 switch (Cand->DeductionFailure.Result) {
8374 case Sema::TDK_Success:
8375 llvm_unreachable("TDK_success while diagnosing bad deduction");
8376
8377 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008378 assert(ParamD && "no parameter found for incomplete deduction result");
8379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8380 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008381 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008382 return;
8383 }
8384
John McCall57e97782010-08-05 09:05:08 +00008385 case Sema::TDK_Underqualified: {
8386 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8387 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8388
8389 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8390
8391 // Param will have been canonicalized, but it should just be a
8392 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008393 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008394 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008395 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008396 assert(S.Context.hasSameType(Param, NonCanonParam));
8397
8398 // Arg has also been canonicalized, but there's nothing we can do
8399 // about that. It also doesn't matter as much, because it won't
8400 // have any template parameters in it (because deduction isn't
8401 // done on dependent types).
8402 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8403
8404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8405 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008406 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008407 return;
8408 }
8409
8410 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008411 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008412 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008413 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008414 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008415 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008416 which = 1;
8417 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008418 which = 2;
8419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008420
Douglas Gregora9333192010-05-08 17:41:32 +00008421 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008422 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008423 << *Cand->DeductionFailure.getFirstArg()
8424 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008425 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008426 return;
8427 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008428
Douglas Gregorf1a84452010-05-08 19:15:54 +00008429 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008430 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008431 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008432 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008433 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8434 << ParamD->getDeclName();
8435 else {
8436 int index = 0;
8437 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8438 index = TTP->getIndex();
8439 else if (NonTypeTemplateParmDecl *NTTP
8440 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8441 index = NTTP->getIndex();
8442 else
8443 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008444 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008445 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8446 << (index + 1);
8447 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008448 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008449 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008450
Douglas Gregora18592e2010-05-08 18:13:28 +00008451 case Sema::TDK_TooManyArguments:
8452 case Sema::TDK_TooFewArguments:
8453 DiagnoseArityMismatch(S, Cand, NumArgs);
8454 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008455
8456 case Sema::TDK_InstantiationDepth:
8457 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008458 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008459 return;
8460
8461 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008462 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008463 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008464 if (TemplateArgumentList *Args =
8465 Cand->DeductionFailure.getTemplateArgumentList()) {
8466 TemplateArgString = " ";
8467 TemplateArgString += S.getTemplateArgumentBindingsText(
8468 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8469 }
8470
Richard Smith4493c0a2012-05-09 05:17:00 +00008471 // If this candidate was disabled by enable_if, say so.
8472 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8473 if (PDiag && PDiag->second.getDiagID() ==
8474 diag::err_typename_nested_not_found_enable_if) {
8475 // FIXME: Use the source range of the condition, and the fully-qualified
8476 // name of the enable_if template. These are both present in PDiag.
8477 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8478 << "'enable_if'" << TemplateArgString;
8479 return;
8480 }
8481
Richard Smithb8590f32012-05-07 09:03:25 +00008482 // Format the SFINAE diagnostic into the argument string.
8483 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8484 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008485 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008486 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008487 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008488 SFINAEArgString = ": ";
8489 R = SourceRange(PDiag->first, PDiag->first);
8490 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8491 }
8492
Douglas Gregorec20f462010-05-08 20:07:26 +00008493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008494 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008495 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008496 return;
8497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008498
Richard Smith0efa62f2013-01-31 04:03:12 +00008499 case Sema::TDK_FailedOverloadResolution: {
8500 OverloadExpr::FindResult R =
8501 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8502 S.Diag(Fn->getLocation(),
8503 diag::note_ovl_candidate_failed_overload_resolution)
8504 << R.Expression->getName();
8505 return;
8506 }
8507
Richard Trieueef35f82013-04-08 21:11:40 +00008508 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008509 // FIXME: Provide a source location to indicate what we couldn't match.
Richard Trieueef35f82013-04-08 21:11:40 +00008510 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8511 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8512 if (FirstTA.getKind() == TemplateArgument::Template &&
8513 SecondTA.getKind() == TemplateArgument::Template) {
8514 TemplateName FirstTN = FirstTA.getAsTemplate();
8515 TemplateName SecondTN = SecondTA.getAsTemplate();
8516 if (FirstTN.getKind() == TemplateName::Template &&
8517 SecondTN.getKind() == TemplateName::Template) {
8518 if (FirstTN.getAsTemplateDecl()->getName() ==
8519 SecondTN.getAsTemplateDecl()->getName()) {
8520 // FIXME: This fixes a bad diagnostic where both templates are named
8521 // the same. This particular case is a bit difficult since:
8522 // 1) It is passed as a string to the diagnostic printer.
8523 // 2) The diagnostic printer only attempts to find a better
8524 // name for types, not decls.
8525 // Ideally, this should folded into the diagnostic printer.
8526 S.Diag(Fn->getLocation(),
8527 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8528 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8529 return;
8530 }
8531 }
8532 }
Richard Smith29805ca2013-01-31 05:19:49 +00008533 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
Richard Trieueef35f82013-04-08 21:11:40 +00008534 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008535 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008536 }
John McCall342fec42010-02-01 18:53:26 +00008537 // TODO: diagnose these individually, then kill off
8538 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008539 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008541 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008542 return;
8543 }
8544}
8545
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008546/// CUDA: diagnose an invalid call across targets.
8547void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8548 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8549 FunctionDecl *Callee = Cand->Function;
8550
8551 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8552 CalleeTarget = S.IdentifyCUDATarget(Callee);
8553
8554 std::string FnDesc;
8555 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8556
8557 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8558 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8559}
8560
John McCall342fec42010-02-01 18:53:26 +00008561/// Generates a 'note' diagnostic for an overload candidate. We've
8562/// already generated a primary error at the call site.
8563///
8564/// It really does need to be a single diagnostic with its caret
8565/// pointed at the candidate declaration. Yes, this creates some
8566/// major challenges of technical writing. Yes, this makes pointing
8567/// out problems with specific arguments quite awkward. It's still
8568/// better than generating twenty screens of text for every failed
8569/// overload.
8570///
8571/// It would be great to be able to express per-candidate problems
8572/// more richly for those diagnostic clients that cared, but we'd
8573/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008574void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008575 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008576 FunctionDecl *Fn = Cand->Function;
8577
John McCall81201622010-01-08 04:41:39 +00008578 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008579 if (Cand->Viable && (Fn->isDeleted() ||
8580 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008581 std::string FnDesc;
8582 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008583
8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008585 << FnKind << FnDesc
8586 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008587 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008588 return;
John McCall81201622010-01-08 04:41:39 +00008589 }
8590
John McCall220ccbf2010-01-13 00:25:19 +00008591 // We don't really have anything else to say about viable candidates.
8592 if (Cand->Viable) {
8593 S.NoteOverloadCandidate(Fn);
8594 return;
8595 }
John McCall1d318332010-01-12 00:44:57 +00008596
John McCalladbb8f82010-01-13 09:16:55 +00008597 switch (Cand->FailureKind) {
8598 case ovl_fail_too_many_arguments:
8599 case ovl_fail_too_few_arguments:
8600 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008601
John McCalladbb8f82010-01-13 09:16:55 +00008602 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008603 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008604
John McCall717e8912010-01-23 05:17:32 +00008605 case ovl_fail_trivial_conversion:
8606 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008607 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008608 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008609
John McCallb1bdc622010-02-25 01:37:24 +00008610 case ovl_fail_bad_conversion: {
8611 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008612 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008613 if (Cand->Conversions[I].isBad())
8614 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008615
John McCalladbb8f82010-01-13 09:16:55 +00008616 // FIXME: this currently happens when we're called from SemaInit
8617 // when user-conversion overload fails. Figure out how to handle
8618 // those conditions and diagnose them well.
8619 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008620 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008621
8622 case ovl_fail_bad_target:
8623 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008624 }
John McCalla1d7d622010-01-08 00:58:21 +00008625}
8626
8627void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8628 // Desugar the type of the surrogate down to a function type,
8629 // retaining as many typedefs as possible while still showing
8630 // the function type (and, therefore, its parameter types).
8631 QualType FnType = Cand->Surrogate->getConversionType();
8632 bool isLValueReference = false;
8633 bool isRValueReference = false;
8634 bool isPointer = false;
8635 if (const LValueReferenceType *FnTypeRef =
8636 FnType->getAs<LValueReferenceType>()) {
8637 FnType = FnTypeRef->getPointeeType();
8638 isLValueReference = true;
8639 } else if (const RValueReferenceType *FnTypeRef =
8640 FnType->getAs<RValueReferenceType>()) {
8641 FnType = FnTypeRef->getPointeeType();
8642 isRValueReference = true;
8643 }
8644 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8645 FnType = FnTypePtr->getPointeeType();
8646 isPointer = true;
8647 }
8648 // Desugar down to a function type.
8649 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8650 // Reconstruct the pointer/reference as appropriate.
8651 if (isPointer) FnType = S.Context.getPointerType(FnType);
8652 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8653 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8654
8655 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8656 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008657 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008658}
8659
8660void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008661 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008662 SourceLocation OpLoc,
8663 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008664 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008665 std::string TypeStr("operator");
8666 TypeStr += Opc;
8667 TypeStr += "(";
8668 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008669 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008670 TypeStr += ")";
8671 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8672 } else {
8673 TypeStr += ", ";
8674 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8675 TypeStr += ")";
8676 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8677 }
8678}
8679
8680void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8681 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008682 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008683 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8684 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008685 if (ICS.isBad()) break; // all meaningless after first invalid
8686 if (!ICS.isAmbiguous()) continue;
8687
John McCall120d63c2010-08-24 20:38:10 +00008688 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008689 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008690 }
8691}
8692
John McCall1b77e732010-01-15 23:32:50 +00008693SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8694 if (Cand->Function)
8695 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008696 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008697 return Cand->Surrogate->getLocation();
8698 return SourceLocation();
8699}
8700
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008701static unsigned
8702RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008703 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008704 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008705 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008706
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008707 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008708 case Sema::TDK_Incomplete:
8709 return 1;
8710
8711 case Sema::TDK_Underqualified:
8712 case Sema::TDK_Inconsistent:
8713 return 2;
8714
8715 case Sema::TDK_SubstitutionFailure:
8716 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008717 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008718 return 3;
8719
8720 case Sema::TDK_InstantiationDepth:
8721 case Sema::TDK_FailedOverloadResolution:
8722 return 4;
8723
8724 case Sema::TDK_InvalidExplicitArguments:
8725 return 5;
8726
8727 case Sema::TDK_TooManyArguments:
8728 case Sema::TDK_TooFewArguments:
8729 return 6;
8730 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008731 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008732}
8733
John McCallbf65c0b2010-01-12 00:48:53 +00008734struct CompareOverloadCandidatesForDisplay {
8735 Sema &S;
8736 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008737
8738 bool operator()(const OverloadCandidate *L,
8739 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008740 // Fast-path this check.
8741 if (L == R) return false;
8742
John McCall81201622010-01-08 04:41:39 +00008743 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008744 if (L->Viable) {
8745 if (!R->Viable) return true;
8746
8747 // TODO: introduce a tri-valued comparison for overload
8748 // candidates. Would be more worthwhile if we had a sort
8749 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008750 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8751 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008752 } else if (R->Viable)
8753 return false;
John McCall81201622010-01-08 04:41:39 +00008754
John McCall1b77e732010-01-15 23:32:50 +00008755 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008756
John McCall1b77e732010-01-15 23:32:50 +00008757 // Criteria by which we can sort non-viable candidates:
8758 if (!L->Viable) {
8759 // 1. Arity mismatches come after other candidates.
8760 if (L->FailureKind == ovl_fail_too_many_arguments ||
8761 L->FailureKind == ovl_fail_too_few_arguments)
8762 return false;
8763 if (R->FailureKind == ovl_fail_too_many_arguments ||
8764 R->FailureKind == ovl_fail_too_few_arguments)
8765 return true;
John McCall81201622010-01-08 04:41:39 +00008766
John McCall717e8912010-01-23 05:17:32 +00008767 // 2. Bad conversions come first and are ordered by the number
8768 // of bad conversions and quality of good conversions.
8769 if (L->FailureKind == ovl_fail_bad_conversion) {
8770 if (R->FailureKind != ovl_fail_bad_conversion)
8771 return true;
8772
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008773 // The conversion that can be fixed with a smaller number of changes,
8774 // comes first.
8775 unsigned numLFixes = L->Fix.NumConversionsFixed;
8776 unsigned numRFixes = R->Fix.NumConversionsFixed;
8777 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8778 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008779 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008780 if (numLFixes < numRFixes)
8781 return true;
8782 else
8783 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008784 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008785
John McCall717e8912010-01-23 05:17:32 +00008786 // If there's any ordering between the defined conversions...
8787 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008788 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008789
8790 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008791 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008792 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008793 switch (CompareImplicitConversionSequences(S,
8794 L->Conversions[I],
8795 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008796 case ImplicitConversionSequence::Better:
8797 leftBetter++;
8798 break;
8799
8800 case ImplicitConversionSequence::Worse:
8801 leftBetter--;
8802 break;
8803
8804 case ImplicitConversionSequence::Indistinguishable:
8805 break;
8806 }
8807 }
8808 if (leftBetter > 0) return true;
8809 if (leftBetter < 0) return false;
8810
8811 } else if (R->FailureKind == ovl_fail_bad_conversion)
8812 return false;
8813
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008814 if (L->FailureKind == ovl_fail_bad_deduction) {
8815 if (R->FailureKind != ovl_fail_bad_deduction)
8816 return true;
8817
8818 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8819 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008820 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008821 } else if (R->FailureKind == ovl_fail_bad_deduction)
8822 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008823
John McCall1b77e732010-01-15 23:32:50 +00008824 // TODO: others?
8825 }
8826
8827 // Sort everything else by location.
8828 SourceLocation LLoc = GetLocationForCandidate(L);
8829 SourceLocation RLoc = GetLocationForCandidate(R);
8830
8831 // Put candidates without locations (e.g. builtins) at the end.
8832 if (LLoc.isInvalid()) return false;
8833 if (RLoc.isInvalid()) return true;
8834
8835 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008836 }
8837};
8838
John McCall717e8912010-01-23 05:17:32 +00008839/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008840/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008841void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008842 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008843 assert(!Cand->Viable);
8844
8845 // Don't do anything on failures other than bad conversion.
8846 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8847
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008848 // We only want the FixIts if all the arguments can be corrected.
8849 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008850 // Use a implicit copy initialization to check conversion fixes.
8851 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008852
John McCall717e8912010-01-23 05:17:32 +00008853 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008854 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008855 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008856 while (true) {
8857 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8858 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008859 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008860 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008861 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008862 }
John McCall717e8912010-01-23 05:17:32 +00008863 }
8864
8865 if (ConvIdx == ConvCount)
8866 return;
8867
John McCallb1bdc622010-02-25 01:37:24 +00008868 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8869 "remaining conversion is initialized?");
8870
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008871 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008872 // operation somehow.
8873 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008874
8875 const FunctionProtoType* Proto;
8876 unsigned ArgIdx = ConvIdx;
8877
8878 if (Cand->IsSurrogate) {
8879 QualType ConvType
8880 = Cand->Surrogate->getConversionType().getNonReferenceType();
8881 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8882 ConvType = ConvPtrType->getPointeeType();
8883 Proto = ConvType->getAs<FunctionProtoType>();
8884 ArgIdx--;
8885 } else if (Cand->Function) {
8886 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8887 if (isa<CXXMethodDecl>(Cand->Function) &&
8888 !isa<CXXConstructorDecl>(Cand->Function))
8889 ArgIdx--;
8890 } else {
8891 // Builtin binary operator with a bad first conversion.
8892 assert(ConvCount <= 3);
8893 for (; ConvIdx != ConvCount; ++ConvIdx)
8894 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008895 = TryCopyInitialization(S, Args[ConvIdx],
8896 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008897 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008898 /*InOverloadResolution*/ true,
8899 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008900 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008901 return;
8902 }
8903
8904 // Fill in the rest of the conversions.
8905 unsigned NumArgsInProto = Proto->getNumArgs();
8906 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008907 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008908 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008909 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008910 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008911 /*InOverloadResolution=*/true,
8912 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008913 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008914 // Store the FixIt in the candidate if it exists.
8915 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008916 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008917 }
John McCall717e8912010-01-23 05:17:32 +00008918 else
8919 Cand->Conversions[ConvIdx].setEllipsis();
8920 }
8921}
8922
John McCalla1d7d622010-01-08 00:58:21 +00008923} // end anonymous namespace
8924
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008925/// PrintOverloadCandidates - When overload resolution fails, prints
8926/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008927/// set.
John McCall120d63c2010-08-24 20:38:10 +00008928void OverloadCandidateSet::NoteCandidates(Sema &S,
8929 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008930 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008931 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008932 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008933 // Sort the candidates by viability and position. Sorting directly would
8934 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008935 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008936 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8937 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008938 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008939 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008940 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008941 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008942 if (Cand->Function || Cand->IsSurrogate)
8943 Cands.push_back(Cand);
8944 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8945 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008946 }
8947 }
8948
John McCallbf65c0b2010-01-12 00:48:53 +00008949 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008950 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008951
John McCall1d318332010-01-12 00:44:57 +00008952 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008953
Chris Lattner5f9e2722011-07-23 10:55:15 +00008954 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008955 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008956 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008957 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8958 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008959
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008960 // Set an arbitrary limit on the number of candidate functions we'll spam
8961 // the user with. FIXME: This limit should depend on details of the
8962 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008963 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008964 break;
8965 }
8966 ++CandsShown;
8967
John McCalla1d7d622010-01-08 00:58:21 +00008968 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008969 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008970 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008971 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008972 else {
8973 assert(Cand->Viable &&
8974 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008975 // Generally we only see ambiguities including viable builtin
8976 // operators if overload resolution got screwed up by an
8977 // ambiguous user-defined conversion.
8978 //
8979 // FIXME: It's quite possible for different conversions to see
8980 // different ambiguities, though.
8981 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008982 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008983 ReportedAmbiguousConversions = true;
8984 }
John McCalla1d7d622010-01-08 00:58:21 +00008985
John McCall1d318332010-01-12 00:44:57 +00008986 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008987 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008988 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008989 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008990
8991 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008992 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008993}
8994
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008995// [PossiblyAFunctionType] --> [Return]
8996// NonFunctionType --> NonFunctionType
8997// R (A) --> R(A)
8998// R (*)(A) --> R (A)
8999// R (&)(A) --> R (A)
9000// R (S::*)(A) --> R (A)
9001QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9002 QualType Ret = PossiblyAFunctionType;
9003 if (const PointerType *ToTypePtr =
9004 PossiblyAFunctionType->getAs<PointerType>())
9005 Ret = ToTypePtr->getPointeeType();
9006 else if (const ReferenceType *ToTypeRef =
9007 PossiblyAFunctionType->getAs<ReferenceType>())
9008 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009009 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009010 PossiblyAFunctionType->getAs<MemberPointerType>())
9011 Ret = MemTypePtr->getPointeeType();
9012 Ret =
9013 Context.getCanonicalType(Ret).getUnqualifiedType();
9014 return Ret;
9015}
Douglas Gregor904eed32008-11-10 20:40:00 +00009016
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009017// A helper class to help with address of function resolution
9018// - allows us to avoid passing around all those ugly parameters
9019class AddressOfFunctionResolver
9020{
9021 Sema& S;
9022 Expr* SourceExpr;
9023 const QualType& TargetType;
9024 QualType TargetFunctionType; // Extracted function type from target type
9025
9026 bool Complain;
9027 //DeclAccessPair& ResultFunctionAccessPair;
9028 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009029
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009030 bool TargetTypeIsNonStaticMemberFunction;
9031 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009032
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009033 OverloadExpr::FindResult OvlExprInfo;
9034 OverloadExpr *OvlExpr;
9035 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009036 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009037
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009038public:
9039 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9040 const QualType& TargetType, bool Complain)
9041 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9042 Complain(Complain), Context(S.getASTContext()),
9043 TargetTypeIsNonStaticMemberFunction(
9044 !!TargetType->getAs<MemberPointerType>()),
9045 FoundNonTemplateFunction(false),
9046 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9047 OvlExpr(OvlExprInfo.Expression)
9048 {
9049 ExtractUnqualifiedFunctionTypeFromTargetType();
9050
9051 if (!TargetFunctionType->isFunctionType()) {
9052 if (OvlExpr->hasExplicitTemplateArgs()) {
9053 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009054 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009055 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009056
9057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9058 if (!Method->isStatic()) {
9059 // If the target type is a non-function type and the function
9060 // found is a non-static member function, pretend as if that was
9061 // the target, it's the only possible type to end up with.
9062 TargetTypeIsNonStaticMemberFunction = true;
9063
9064 // And skip adding the function if its not in the proper form.
9065 // We'll diagnose this due to an empty set of functions.
9066 if (!OvlExprInfo.HasFormOfMemberPointer)
9067 return;
9068 }
9069 }
9070
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009071 Matches.push_back(std::make_pair(dap,Fn));
9072 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009073 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009074 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009075 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009076
9077 if (OvlExpr->hasExplicitTemplateArgs())
9078 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009079
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009080 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9081 // C++ [over.over]p4:
9082 // If more than one function is selected, [...]
9083 if (Matches.size() > 1) {
9084 if (FoundNonTemplateFunction)
9085 EliminateAllTemplateMatches();
9086 else
9087 EliminateAllExceptMostSpecializedTemplate();
9088 }
9089 }
9090 }
9091
9092private:
9093 bool isTargetTypeAFunction() const {
9094 return TargetFunctionType->isFunctionType();
9095 }
9096
9097 // [ToType] [Return]
9098
9099 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9100 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9101 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9102 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9103 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9104 }
9105
9106 // return true if any matching specializations were found
9107 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9108 const DeclAccessPair& CurAccessFunPair) {
9109 if (CXXMethodDecl *Method
9110 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9111 // Skip non-static function templates when converting to pointer, and
9112 // static when converting to member pointer.
9113 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9114 return false;
9115 }
9116 else if (TargetTypeIsNonStaticMemberFunction)
9117 return false;
9118
9119 // C++ [over.over]p2:
9120 // If the name is a function template, template argument deduction is
9121 // done (14.8.2.2), and if the argument deduction succeeds, the
9122 // resulting template argument list is used to generate a single
9123 // function template specialization, which is added to the set of
9124 // overloaded functions considered.
9125 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009126 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009127 if (Sema::TemplateDeductionResult Result
9128 = S.DeduceTemplateArguments(FunctionTemplate,
9129 &OvlExplicitTemplateArgs,
9130 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009131 Info, /*InOverloadResolution=*/true)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009132 // FIXME: make a note of the failed deduction for diagnostics.
9133 (void)Result;
9134 return false;
9135 }
9136
Douglas Gregor092140a2013-04-17 08:45:07 +00009137 // Template argument deduction ensures that we have an exact match or
9138 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009139 // This function template specicalization works.
9140 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009141 assert(S.isSameOrCompatibleFunctionType(
9142 Context.getCanonicalType(Specialization->getType()),
9143 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9145 return true;
9146 }
9147
9148 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9149 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009150 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009151 // Skip non-static functions when converting to pointer, and static
9152 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009153 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9154 return false;
9155 }
9156 else if (TargetTypeIsNonStaticMemberFunction)
9157 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009158
Chandler Carruthbd647292009-12-29 06:17:27 +00009159 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009160 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009161 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9162 if (S.CheckCUDATarget(Caller, FunDecl))
9163 return false;
9164
Richard Smith60e141e2013-05-04 07:00:32 +00009165 // If any candidate has a placeholder return type, trigger its deduction
9166 // now.
9167 if (S.getLangOpts().CPlusPlus1y &&
9168 FunDecl->getResultType()->isUndeducedType() &&
9169 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9170 return false;
9171
Douglas Gregor43c79c22009-12-09 00:47:37 +00009172 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009173 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9174 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009175 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9176 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009177 Matches.push_back(std::make_pair(CurAccessFunPair,
9178 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009179 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009180 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009181 }
Mike Stump1eb44332009-09-09 15:08:12 +00009182 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009183
9184 return false;
9185 }
9186
9187 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9188 bool Ret = false;
9189
9190 // If the overload expression doesn't have the form of a pointer to
9191 // member, don't try to convert it to a pointer-to-member type.
9192 if (IsInvalidFormOfPointerToMemberFunction())
9193 return false;
9194
9195 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9196 E = OvlExpr->decls_end();
9197 I != E; ++I) {
9198 // Look through any using declarations to find the underlying function.
9199 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9200
9201 // C++ [over.over]p3:
9202 // Non-member functions and static member functions match
9203 // targets of type "pointer-to-function" or "reference-to-function."
9204 // Nonstatic member functions match targets of
9205 // type "pointer-to-member-function."
9206 // Note that according to DR 247, the containing class does not matter.
9207 if (FunctionTemplateDecl *FunctionTemplate
9208 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9209 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9210 Ret = true;
9211 }
9212 // If we have explicit template arguments supplied, skip non-templates.
9213 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9214 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9215 Ret = true;
9216 }
9217 assert(Ret || Matches.empty());
9218 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009219 }
9220
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009221 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009222 // [...] and any given function template specialization F1 is
9223 // eliminated if the set contains a second function template
9224 // specialization whose function template is more specialized
9225 // than the function template of F1 according to the partial
9226 // ordering rules of 14.5.5.2.
9227
9228 // The algorithm specified above is quadratic. We instead use a
9229 // two-pass algorithm (similar to the one used to identify the
9230 // best viable function in an overload set) that identifies the
9231 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009232
9233 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9234 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9235 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009236
John McCallc373d482010-01-27 01:50:18 +00009237 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009238 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9239 TPOC_Other, 0, SourceExpr->getLocStart(),
9240 S.PDiag(),
9241 S.PDiag(diag::err_addr_ovl_ambiguous)
9242 << Matches[0].second->getDeclName(),
9243 S.PDiag(diag::note_ovl_candidate)
9244 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009245 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009246
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009247 if (Result != MatchesCopy.end()) {
9248 // Make it the first and only element
9249 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9250 Matches[0].second = cast<FunctionDecl>(*Result);
9251 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009252 }
9253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009254
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009255 void EliminateAllTemplateMatches() {
9256 // [...] any function template specializations in the set are
9257 // eliminated if the set also contains a non-template function, [...]
9258 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9259 if (Matches[I].second->getPrimaryTemplate() == 0)
9260 ++I;
9261 else {
9262 Matches[I] = Matches[--N];
9263 Matches.set_size(N);
9264 }
9265 }
9266 }
9267
9268public:
9269 void ComplainNoMatchesFound() const {
9270 assert(Matches.empty());
9271 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9272 << OvlExpr->getName() << TargetFunctionType
9273 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009274 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009275 }
9276
9277 bool IsInvalidFormOfPointerToMemberFunction() const {
9278 return TargetTypeIsNonStaticMemberFunction &&
9279 !OvlExprInfo.HasFormOfMemberPointer;
9280 }
9281
9282 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9283 // TODO: Should we condition this on whether any functions might
9284 // have matched, or is it more appropriate to do that in callers?
9285 // TODO: a fixit wouldn't hurt.
9286 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9287 << TargetType << OvlExpr->getSourceRange();
9288 }
9289
9290 void ComplainOfInvalidConversion() const {
9291 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9292 << OvlExpr->getName() << TargetType;
9293 }
9294
9295 void ComplainMultipleMatchesFound() const {
9296 assert(Matches.size() > 1);
9297 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9298 << OvlExpr->getName()
9299 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009300 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009301 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009302
9303 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9304
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009305 int getNumMatches() const { return Matches.size(); }
9306
9307 FunctionDecl* getMatchingFunctionDecl() const {
9308 if (Matches.size() != 1) return 0;
9309 return Matches[0].second;
9310 }
9311
9312 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9313 if (Matches.size() != 1) return 0;
9314 return &Matches[0].first;
9315 }
9316};
9317
9318/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9319/// an overloaded function (C++ [over.over]), where @p From is an
9320/// expression with overloaded function type and @p ToType is the type
9321/// we're trying to resolve to. For example:
9322///
9323/// @code
9324/// int f(double);
9325/// int f(int);
9326///
9327/// int (*pfd)(double) = f; // selects f(double)
9328/// @endcode
9329///
9330/// This routine returns the resulting FunctionDecl if it could be
9331/// resolved, and NULL otherwise. When @p Complain is true, this
9332/// routine will emit diagnostics if there is an error.
9333FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009334Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9335 QualType TargetType,
9336 bool Complain,
9337 DeclAccessPair &FoundResult,
9338 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009339 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009340
9341 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9342 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009343 int NumMatches = Resolver.getNumMatches();
9344 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009345 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009346 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9347 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9348 else
9349 Resolver.ComplainNoMatchesFound();
9350 }
9351 else if (NumMatches > 1 && Complain)
9352 Resolver.ComplainMultipleMatchesFound();
9353 else if (NumMatches == 1) {
9354 Fn = Resolver.getMatchingFunctionDecl();
9355 assert(Fn);
9356 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009357 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009358 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009359 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009360
9361 if (pHadMultipleCandidates)
9362 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009363 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009364}
9365
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009366/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009367/// resolve that overloaded function expression down to a single function.
9368///
9369/// This routine can only resolve template-ids that refer to a single function
9370/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009371/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009372/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009373FunctionDecl *
9374Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9375 bool Complain,
9376 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009377 // C++ [over.over]p1:
9378 // [...] [Note: any redundant set of parentheses surrounding the
9379 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009380 // C++ [over.over]p1:
9381 // [...] The overloaded function name can be preceded by the &
9382 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009383
Douglas Gregor4b52e252009-12-21 23:17:24 +00009384 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009385 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009386 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009387
9388 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009389 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009390
Douglas Gregor4b52e252009-12-21 23:17:24 +00009391 // Look through all of the overloaded functions, searching for one
9392 // whose type matches exactly.
9393 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009394 for (UnresolvedSetIterator I = ovl->decls_begin(),
9395 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009396 // C++0x [temp.arg.explicit]p3:
9397 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009398 // where deduction is not done, if a template argument list is
9399 // specified and it, along with any default template arguments,
9400 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009401 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009402 FunctionTemplateDecl *FunctionTemplate
9403 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009404
Douglas Gregor4b52e252009-12-21 23:17:24 +00009405 // C++ [over.over]p2:
9406 // If the name is a function template, template argument deduction is
9407 // done (14.8.2.2), and if the argument deduction succeeds, the
9408 // resulting template argument list is used to generate a single
9409 // function template specialization, which is added to the set of
9410 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009411 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009412 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009413 if (TemplateDeductionResult Result
9414 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009415 Specialization, Info,
9416 /*InOverloadResolution=*/true)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009417 // FIXME: make a note of the failed deduction for diagnostics.
9418 (void)Result;
9419 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009420 }
9421
John McCall864c0412011-04-26 20:42:42 +00009422 assert(Specialization && "no specialization and no error?");
9423
Douglas Gregor4b52e252009-12-21 23:17:24 +00009424 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009425 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009426 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009427 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9428 << ovl->getName();
9429 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009430 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009431 return 0;
John McCall864c0412011-04-26 20:42:42 +00009432 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009433
John McCall864c0412011-04-26 20:42:42 +00009434 Matched = Specialization;
9435 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009436 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009437
Richard Smith60e141e2013-05-04 07:00:32 +00009438 if (Matched && getLangOpts().CPlusPlus1y &&
9439 Matched->getResultType()->isUndeducedType() &&
9440 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9441 return 0;
9442
Douglas Gregor4b52e252009-12-21 23:17:24 +00009443 return Matched;
9444}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009445
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009446
9447
9448
John McCall6dbba4f2011-10-11 23:14:30 +00009449// Resolve and fix an overloaded expression that can be resolved
9450// because it identifies a single function template specialization.
9451//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009452// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009453//
9454// Return true if it was logically possible to so resolve the
9455// expression, regardless of whether or not it succeeded. Always
9456// returns true if 'complain' is set.
9457bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9458 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9459 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009460 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009461 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009462 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009463
John McCall6dbba4f2011-10-11 23:14:30 +00009464 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009465
John McCall864c0412011-04-26 20:42:42 +00009466 DeclAccessPair found;
9467 ExprResult SingleFunctionExpression;
9468 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9469 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009470 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009471 SrcExpr = ExprError();
9472 return true;
9473 }
John McCall864c0412011-04-26 20:42:42 +00009474
9475 // It is only correct to resolve to an instance method if we're
9476 // resolving a form that's permitted to be a pointer to member.
9477 // Otherwise we'll end up making a bound member expression, which
9478 // is illegal in all the contexts we resolve like this.
9479 if (!ovl.HasFormOfMemberPointer &&
9480 isa<CXXMethodDecl>(fn) &&
9481 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009482 if (!complain) return false;
9483
9484 Diag(ovl.Expression->getExprLoc(),
9485 diag::err_bound_member_function)
9486 << 0 << ovl.Expression->getSourceRange();
9487
9488 // TODO: I believe we only end up here if there's a mix of
9489 // static and non-static candidates (otherwise the expression
9490 // would have 'bound member' type, not 'overload' type).
9491 // Ideally we would note which candidate was chosen and why
9492 // the static candidates were rejected.
9493 SrcExpr = ExprError();
9494 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009495 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009496
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009497 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009498 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009499 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009500
9501 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009502 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009503 SingleFunctionExpression =
9504 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009505 if (SingleFunctionExpression.isInvalid()) {
9506 SrcExpr = ExprError();
9507 return true;
9508 }
9509 }
John McCall864c0412011-04-26 20:42:42 +00009510 }
9511
9512 if (!SingleFunctionExpression.isUsable()) {
9513 if (complain) {
9514 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9515 << ovl.Expression->getName()
9516 << DestTypeForComplaining
9517 << OpRangeForComplaining
9518 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009519 NoteAllOverloadCandidates(SrcExpr.get());
9520
9521 SrcExpr = ExprError();
9522 return true;
9523 }
9524
9525 return false;
John McCall864c0412011-04-26 20:42:42 +00009526 }
9527
John McCall6dbba4f2011-10-11 23:14:30 +00009528 SrcExpr = SingleFunctionExpression;
9529 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009530}
9531
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009532/// \brief Add a single candidate to the overload set.
9533static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009534 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009535 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009536 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009537 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009538 bool PartialOverloading,
9539 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009540 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009541 if (isa<UsingShadowDecl>(Callee))
9542 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9543
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009544 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009545 if (ExplicitTemplateArgs) {
9546 assert(!KnownValid && "Explicit template arguments?");
9547 return;
9548 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009549 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9550 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009551 return;
John McCallba135432009-11-21 08:51:07 +00009552 }
9553
9554 if (FunctionTemplateDecl *FuncTemplate
9555 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009556 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009557 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009558 return;
9559 }
9560
Richard Smith2ced0442011-06-26 22:19:54 +00009561 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009562}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009563
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009564/// \brief Add the overload candidates named by callee and/or found by argument
9565/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009566void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009567 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009568 OverloadCandidateSet &CandidateSet,
9569 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009570
9571#ifndef NDEBUG
9572 // Verify that ArgumentDependentLookup is consistent with the rules
9573 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009574 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009575 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9576 // and let Y be the lookup set produced by argument dependent
9577 // lookup (defined as follows). If X contains
9578 //
9579 // -- a declaration of a class member, or
9580 //
9581 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009582 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009583 //
9584 // -- a declaration that is neither a function or a function
9585 // template
9586 //
9587 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009588
John McCall3b4294e2009-12-16 12:17:52 +00009589 if (ULE->requiresADL()) {
9590 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9591 E = ULE->decls_end(); I != E; ++I) {
9592 assert(!(*I)->getDeclContext()->isRecord());
9593 assert(isa<UsingShadowDecl>(*I) ||
9594 !(*I)->getDeclContext()->isFunctionOrMethod());
9595 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009596 }
9597 }
9598#endif
9599
John McCall3b4294e2009-12-16 12:17:52 +00009600 // It would be nice to avoid this copy.
9601 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009602 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009603 if (ULE->hasExplicitTemplateArgs()) {
9604 ULE->copyTemplateArgumentsInto(TABuffer);
9605 ExplicitTemplateArgs = &TABuffer;
9606 }
9607
9608 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9609 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009610 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9611 CandidateSet, PartialOverloading,
9612 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009613
John McCall3b4294e2009-12-16 12:17:52 +00009614 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009615 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009616 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009617 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009618 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009619}
John McCall578b69b2009-12-16 08:11:27 +00009620
Richard Smithf50e88a2011-06-05 22:42:48 +00009621/// Attempt to recover from an ill-formed use of a non-dependent name in a
9622/// template, where the non-dependent name was declared after the template
9623/// was defined. This is common in code written for a compilers which do not
9624/// correctly implement two-stage name lookup.
9625///
9626/// Returns true if a viable candidate was found and a diagnostic was issued.
9627static bool
9628DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9629 const CXXScopeSpec &SS, LookupResult &R,
9630 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009631 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009632 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9633 return false;
9634
9635 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009636 if (DC->isTransparentContext())
9637 continue;
9638
Richard Smithf50e88a2011-06-05 22:42:48 +00009639 SemaRef.LookupQualifiedName(R, DC);
9640
9641 if (!R.empty()) {
9642 R.suppressDiagnostics();
9643
9644 if (isa<CXXRecordDecl>(DC)) {
9645 // Don't diagnose names we find in classes; we get much better
9646 // diagnostics for these from DiagnoseEmptyLookup.
9647 R.clear();
9648 return false;
9649 }
9650
9651 OverloadCandidateSet Candidates(FnLoc);
9652 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9653 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009654 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009655 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009656
9657 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009658 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009659 // No viable functions. Don't bother the user with notes for functions
9660 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009661 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009662 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009663 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009664
9665 // Find the namespaces where ADL would have looked, and suggest
9666 // declaring the function there instead.
9667 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9668 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009669 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009670 AssociatedNamespaces,
9671 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009672 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009673 DeclContext *Std = SemaRef.getStdNamespace();
9674 for (Sema::AssociatedNamespaceSet::iterator
9675 it = AssociatedNamespaces.begin(),
9676 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009677 // Never suggest declaring a function within namespace 'std'.
9678 if (Std && Std->Encloses(*it))
9679 continue;
9680
9681 // Never suggest declaring a function within a namespace with a reserved
9682 // name, like __gnu_cxx.
9683 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9684 if (NS &&
9685 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9686 continue;
9687
9688 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009689 }
9690
9691 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9692 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009693 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009694 SemaRef.Diag(Best->Function->getLocation(),
9695 diag::note_not_found_by_two_phase_lookup)
9696 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009697 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009698 SemaRef.Diag(Best->Function->getLocation(),
9699 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009700 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009701 } else {
9702 // FIXME: It would be useful to list the associated namespaces here,
9703 // but the diagnostics infrastructure doesn't provide a way to produce
9704 // a localized representation of a list of items.
9705 SemaRef.Diag(Best->Function->getLocation(),
9706 diag::note_not_found_by_two_phase_lookup)
9707 << R.getLookupName() << 2;
9708 }
9709
9710 // Try to recover by calling this function.
9711 return true;
9712 }
9713
9714 R.clear();
9715 }
9716
9717 return false;
9718}
9719
9720/// Attempt to recover from ill-formed use of a non-dependent operator in a
9721/// template, where the non-dependent operator was declared after the template
9722/// was defined.
9723///
9724/// Returns true if a viable candidate was found and a diagnostic was issued.
9725static bool
9726DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9727 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009728 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009729 DeclarationName OpName =
9730 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9731 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9732 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009733 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009734}
9735
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009736namespace {
9737// Callback to limit the allowed keywords and to only accept typo corrections
9738// that are keywords or whose decls refer to functions (or template functions)
9739// that accept the given number of arguments.
9740class RecoveryCallCCC : public CorrectionCandidateCallback {
9741 public:
9742 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9743 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009744 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009745 WantRemainingKeywords = false;
9746 }
9747
9748 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9749 if (!candidate.getCorrectionDecl())
9750 return candidate.isKeyword();
9751
9752 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9753 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9754 FunctionDecl *FD = 0;
9755 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9756 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9757 FD = FTD->getTemplatedDecl();
9758 if (!HasExplicitTemplateArgs && !FD) {
9759 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9760 // If the Decl is neither a function nor a template function,
9761 // determine if it is a pointer or reference to a function. If so,
9762 // check against the number of arguments expected for the pointee.
9763 QualType ValType = cast<ValueDecl>(ND)->getType();
9764 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9765 ValType = ValType->getPointeeType();
9766 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9767 if (FPT->getNumArgs() == NumArgs)
9768 return true;
9769 }
9770 }
9771 if (FD && FD->getNumParams() >= NumArgs &&
9772 FD->getMinRequiredArguments() <= NumArgs)
9773 return true;
9774 }
9775 return false;
9776 }
9777
9778 private:
9779 unsigned NumArgs;
9780 bool HasExplicitTemplateArgs;
9781};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009782
9783// Callback that effectively disabled typo correction
9784class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9785 public:
9786 NoTypoCorrectionCCC() {
9787 WantTypeSpecifiers = false;
9788 WantExpressionKeywords = false;
9789 WantCXXNamedCasts = false;
9790 WantRemainingKeywords = false;
9791 }
9792
9793 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9794 return false;
9795 }
9796};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009797
9798class BuildRecoveryCallExprRAII {
9799 Sema &SemaRef;
9800public:
9801 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9802 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9803 SemaRef.IsBuildingRecoveryCallExpr = true;
9804 }
9805
9806 ~BuildRecoveryCallExprRAII() {
9807 SemaRef.IsBuildingRecoveryCallExpr = false;
9808 }
9809};
9810
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009811}
9812
John McCall578b69b2009-12-16 08:11:27 +00009813/// Attempts to recover from a call where no functions were found.
9814///
9815/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009816static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009817BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009818 UnresolvedLookupExpr *ULE,
9819 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009820 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009821 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009822 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009823 // Do not try to recover if it is already building a recovery call.
9824 // This stops infinite loops for template instantiations like
9825 //
9826 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9827 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9828 //
9829 if (SemaRef.IsBuildingRecoveryCallExpr)
9830 return ExprError();
9831 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009832
9833 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009834 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009835 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009836
John McCall3b4294e2009-12-16 12:17:52 +00009837 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009838 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009839 if (ULE->hasExplicitTemplateArgs()) {
9840 ULE->copyTemplateArgumentsInto(TABuffer);
9841 ExplicitTemplateArgs = &TABuffer;
9842 }
9843
John McCall578b69b2009-12-16 08:11:27 +00009844 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9845 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009846 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009847 NoTypoCorrectionCCC RejectAll;
9848 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9849 (CorrectionCandidateCallback*)&Validator :
9850 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009851 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009852 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009853 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009854 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009855 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009856 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009857
John McCall3b4294e2009-12-16 12:17:52 +00009858 assert(!R.empty() && "lookup results empty despite recovery");
9859
9860 // Build an implicit member call if appropriate. Just drop the
9861 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009862 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009863 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009864 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9865 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009866 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009867 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009868 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009869 else
9870 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9871
9872 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009873 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009874
9875 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009876 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009877 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009878 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009879 MultiExprArg(Args.data(), Args.size()),
9880 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009881}
Douglas Gregord7a95972010-06-08 17:35:15 +00009882
Sam Panzere1715b62012-08-21 00:52:01 +00009883/// \brief Constructs and populates an OverloadedCandidateSet from
9884/// the given function.
9885/// \returns true when an the ExprResult output parameter has been set.
9886bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9887 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009888 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +00009889 SourceLocation RParenLoc,
9890 OverloadCandidateSet *CandidateSet,
9891 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009892#ifndef NDEBUG
9893 if (ULE->requiresADL()) {
9894 // To do ADL, we must have found an unqualified name.
9895 assert(!ULE->getQualifier() && "qualified name with ADL");
9896
9897 // We don't perform ADL for implicit declarations of builtins.
9898 // Verify that this was correctly set up.
9899 FunctionDecl *F;
9900 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9901 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9902 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009903 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009904
John McCall3b4294e2009-12-16 12:17:52 +00009905 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009906 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009907 }
John McCall3b4294e2009-12-16 12:17:52 +00009908#endif
9909
John McCall5acb0c92011-10-17 18:40:02 +00009910 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009911 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +00009912 *Result = ExprError();
9913 return true;
9914 }
Douglas Gregor17330012009-02-04 15:01:18 +00009915
John McCall3b4294e2009-12-16 12:17:52 +00009916 // Add the functions denoted by the callee to the set of candidate
9917 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009918 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009919
9920 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009921 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9922 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009923 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009924 // In Microsoft mode, if we are inside a template class member function then
9925 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009926 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009927 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009928 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009929 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009930 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009931 Context.DependentTy, VK_RValue,
9932 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009933 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009934 *Result = Owned(CE);
9935 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009936 }
Sam Panzere1715b62012-08-21 00:52:01 +00009937 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009938 }
John McCall578b69b2009-12-16 08:11:27 +00009939
John McCall5acb0c92011-10-17 18:40:02 +00009940 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009941 return false;
9942}
John McCall5acb0c92011-10-17 18:40:02 +00009943
Sam Panzere1715b62012-08-21 00:52:01 +00009944/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9945/// the completed call expression. If overload resolution fails, emits
9946/// diagnostics and returns ExprError()
9947static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9948 UnresolvedLookupExpr *ULE,
9949 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009950 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +00009951 SourceLocation RParenLoc,
9952 Expr *ExecConfig,
9953 OverloadCandidateSet *CandidateSet,
9954 OverloadCandidateSet::iterator *Best,
9955 OverloadingResult OverloadResult,
9956 bool AllowTypoCorrection) {
9957 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009958 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +00009959 RParenLoc, /*EmptyLookup=*/true,
9960 AllowTypoCorrection);
9961
9962 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009963 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009964 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +00009965 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00009966 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
9967 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +00009968 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009969 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
9970 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009971 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009972
Richard Smithf50e88a2011-06-05 22:42:48 +00009973 case OR_No_Viable_Function: {
9974 // Try to recover by looking for viable functions which the user might
9975 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009976 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009977 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009978 /*EmptyLookup=*/false,
9979 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009980 if (!Recovery.isInvalid())
9981 return Recovery;
9982
Sam Panzere1715b62012-08-21 00:52:01 +00009983 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009984 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009985 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009986 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009987 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009988 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009989
9990 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009991 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009992 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009993 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009994 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009995
Sam Panzere1715b62012-08-21 00:52:01 +00009996 case OR_Deleted: {
9997 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9998 << (*Best)->Function->isDeleted()
9999 << ULE->getName()
10000 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10001 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010002 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010003
Sam Panzere1715b62012-08-21 00:52:01 +000010004 // We emitted an error for the unvailable/deleted function call but keep
10005 // the call in the AST.
10006 FunctionDecl *FDecl = (*Best)->Function;
10007 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010008 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10009 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010010 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010011 }
10012
Douglas Gregorff331c12010-07-25 18:17:45 +000010013 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010014 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010015}
10016
Sam Panzere1715b62012-08-21 00:52:01 +000010017/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10018/// (which eventually refers to the declaration Func) and the call
10019/// arguments Args/NumArgs, attempt to resolve the function call down
10020/// to a specific function. If overload resolution succeeds, returns
10021/// the call expression produced by overload resolution.
10022/// Otherwise, emits diagnostics and returns ExprError.
10023ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10024 UnresolvedLookupExpr *ULE,
10025 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010026 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010027 SourceLocation RParenLoc,
10028 Expr *ExecConfig,
10029 bool AllowTypoCorrection) {
10030 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10031 ExprResult result;
10032
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010033 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10034 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010035 return result;
10036
10037 OverloadCandidateSet::iterator Best;
10038 OverloadingResult OverloadResult =
10039 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10040
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010041 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010042 RParenLoc, ExecConfig, &CandidateSet,
10043 &Best, OverloadResult,
10044 AllowTypoCorrection);
10045}
10046
John McCall6e266892010-01-26 03:27:55 +000010047static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010048 return Functions.size() > 1 ||
10049 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10050}
10051
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010052/// \brief Create a unary operation that may resolve to an overloaded
10053/// operator.
10054///
10055/// \param OpLoc The location of the operator itself (e.g., '*').
10056///
10057/// \param OpcIn The UnaryOperator::Opcode that describes this
10058/// operator.
10059///
James Dennett40ae6662012-06-22 08:52:37 +000010060/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010061/// considered by overload resolution. The caller needs to build this
10062/// set based on the context using, e.g.,
10063/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10064/// set should not contain any member functions; those will be added
10065/// by CreateOverloadedUnaryOp().
10066///
James Dennett8da16872012-06-22 10:32:46 +000010067/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010068ExprResult
John McCall6e266892010-01-26 03:27:55 +000010069Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10070 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010071 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010072 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010073
10074 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10075 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10076 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010077 // TODO: provide better source location info.
10078 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010079
John McCall5acb0c92011-10-17 18:40:02 +000010080 if (checkPlaceholderForOverload(*this, Input))
10081 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010082
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010083 Expr *Args[2] = { Input, 0 };
10084 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010085
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010086 // For post-increment and post-decrement, add the implicit '0' as
10087 // the second argument, so that we know this is a post-increment or
10088 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010089 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010090 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010091 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10092 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010093 NumArgs = 2;
10094 }
10095
Richard Smith958ba642013-05-05 15:51:06 +000010096 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10097
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010098 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010099 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010100 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010101 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010102 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010103 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010104 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010105
John McCallc373d482010-01-27 01:50:18 +000010106 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010107 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010108 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010109 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010110 /*ADL*/ true, IsOverloaded(Fns),
10111 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010112 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010113 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010114 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010115 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010116 }
10117
10118 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010119 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010120
10121 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010122 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010123
10124 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010125 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010126
John McCall6e266892010-01-26 03:27:55 +000010127 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010128 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10129 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010130 CandidateSet);
10131
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010132 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010133 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010134
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010135 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10136
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010137 // Perform overload resolution.
10138 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010139 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010140 case OR_Success: {
10141 // We found a built-in operator or an overloaded operator.
10142 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010143
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010144 if (FnDecl) {
10145 // We matched an overloaded operator. Build a call to that
10146 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010147
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010148 // Convert the arguments.
10149 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010150 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010151
John Wiegley429bb272011-04-08 18:41:53 +000010152 ExprResult InputRes =
10153 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10154 Best->FoundDecl, Method);
10155 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010156 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010157 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010158 } else {
10159 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010160 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010161 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010162 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010163 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010164 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010165 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010166 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010167 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010168 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010169 }
10170
John McCallf89e55a2010-11-18 06:31:45 +000010171 // Determine the result type.
10172 QualType ResultTy = FnDecl->getResultType();
10173 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10174 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010175
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010176 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010177 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010178 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010179 if (FnExpr.isInvalid())
10180 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010181
Eli Friedman4c3b8962009-11-18 03:58:17 +000010182 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010183 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010184 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010185 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010186
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010187 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010188 FnDecl))
10189 return ExprError();
10190
John McCall9ae2f072010-08-23 23:25:46 +000010191 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010192 } else {
10193 // We matched a built-in operator. Convert the arguments, then
10194 // break out so that we will build the appropriate built-in
10195 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010196 ExprResult InputRes =
10197 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10198 Best->Conversions[0], AA_Passing);
10199 if (InputRes.isInvalid())
10200 return ExprError();
10201 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010202 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010203 }
John Wiegley429bb272011-04-08 18:41:53 +000010204 }
10205
10206 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010207 // This is an erroneous use of an operator which can be overloaded by
10208 // a non-member function. Check for non-member operators which were
10209 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010210 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010211 // FIXME: Recover by calling the found function.
10212 return ExprError();
10213
John Wiegley429bb272011-04-08 18:41:53 +000010214 // No viable function; fall through to handling this as a
10215 // built-in operator, which will produce an error message for us.
10216 break;
10217
10218 case OR_Ambiguous:
10219 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10220 << UnaryOperator::getOpcodeStr(Opc)
10221 << Input->getType()
10222 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010224 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10225 return ExprError();
10226
10227 case OR_Deleted:
10228 Diag(OpLoc, diag::err_ovl_deleted_oper)
10229 << Best->Function->isDeleted()
10230 << UnaryOperator::getOpcodeStr(Opc)
10231 << getDeletedOrUnavailableSuffix(Best->Function)
10232 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010234 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010235 return ExprError();
10236 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010237
10238 // Either we found no viable overloaded operator or we matched a
10239 // built-in operator. In either case, fall through to trying to
10240 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010241 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010242}
10243
Douglas Gregor063daf62009-03-13 18:40:31 +000010244/// \brief Create a binary operation that may resolve to an overloaded
10245/// operator.
10246///
10247/// \param OpLoc The location of the operator itself (e.g., '+').
10248///
10249/// \param OpcIn The BinaryOperator::Opcode that describes this
10250/// operator.
10251///
James Dennett40ae6662012-06-22 08:52:37 +000010252/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010253/// considered by overload resolution. The caller needs to build this
10254/// set based on the context using, e.g.,
10255/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10256/// set should not contain any member functions; those will be added
10257/// by CreateOverloadedBinOp().
10258///
10259/// \param LHS Left-hand argument.
10260/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010261ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010262Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010263 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010264 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010265 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010266 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010267 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010268
10269 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10270 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10271 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10272
10273 // If either side is type-dependent, create an appropriate dependent
10274 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010275 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010276 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010277 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010278 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010279 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010280 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010281 Context.DependentTy,
10282 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010283 OpLoc,
10284 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010285
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010286 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10287 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010288 VK_LValue,
10289 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010290 Context.DependentTy,
10291 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010292 OpLoc,
10293 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010294 }
John McCall6e266892010-01-26 03:27:55 +000010295
10296 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010297 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010298 // TODO: provide better source location info in DNLoc component.
10299 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010300 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010301 = UnresolvedLookupExpr::Create(Context, NamingClass,
10302 NestedNameSpecifierLoc(), OpNameInfo,
10303 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010304 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010305 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10306 Context.DependentTy, VK_RValue,
10307 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010308 }
10309
John McCall5acb0c92011-10-17 18:40:02 +000010310 // Always do placeholder-like conversions on the RHS.
10311 if (checkPlaceholderForOverload(*this, Args[1]))
10312 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010313
John McCall3c3b7f92011-10-25 17:37:35 +000010314 // Do placeholder-like conversion on the LHS; note that we should
10315 // not get here with a PseudoObject LHS.
10316 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010317 if (checkPlaceholderForOverload(*this, Args[0]))
10318 return ExprError();
10319
Sebastian Redl275c2b42009-11-18 23:10:33 +000010320 // If this is the assignment operator, we only perform overload resolution
10321 // if the left-hand side is a class or enumeration type. This is actually
10322 // a hack. The standard requires that we do overload resolution between the
10323 // various built-in candidates, but as DR507 points out, this can lead to
10324 // problems. So we do it this way, which pretty much follows what GCC does.
10325 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010326 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010327 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010328
John McCall0e800c92010-12-04 08:14:53 +000010329 // If this is the .* operator, which is not overloadable, just
10330 // create a built-in binary operator.
10331 if (Opc == BO_PtrMemD)
10332 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10333
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010334 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010335 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010336
10337 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010338 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010339
10340 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010341 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010342
John McCall6e266892010-01-26 03:27:55 +000010343 // Add candidates from ADL.
10344 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010345 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010346 /*ExplicitTemplateArgs*/ 0,
10347 CandidateSet);
10348
Douglas Gregor063daf62009-03-13 18:40:31 +000010349 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010350 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010351
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010352 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10353
Douglas Gregor063daf62009-03-13 18:40:31 +000010354 // Perform overload resolution.
10355 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010356 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010357 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010358 // We found a built-in operator or an overloaded operator.
10359 FunctionDecl *FnDecl = Best->Function;
10360
10361 if (FnDecl) {
10362 // We matched an overloaded operator. Build a call to that
10363 // operator.
10364
10365 // Convert the arguments.
10366 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010367 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010368 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010369
Chandler Carruth6df868e2010-12-12 08:17:55 +000010370 ExprResult Arg1 =
10371 PerformCopyInitialization(
10372 InitializedEntity::InitializeParameter(Context,
10373 FnDecl->getParamDecl(0)),
10374 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010375 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010376 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010377
John Wiegley429bb272011-04-08 18:41:53 +000010378 ExprResult Arg0 =
10379 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10380 Best->FoundDecl, Method);
10381 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010382 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010383 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010384 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010385 } else {
10386 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010387 ExprResult Arg0 = PerformCopyInitialization(
10388 InitializedEntity::InitializeParameter(Context,
10389 FnDecl->getParamDecl(0)),
10390 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010391 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010392 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010393
Chandler Carruth6df868e2010-12-12 08:17:55 +000010394 ExprResult Arg1 =
10395 PerformCopyInitialization(
10396 InitializedEntity::InitializeParameter(Context,
10397 FnDecl->getParamDecl(1)),
10398 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010399 if (Arg1.isInvalid())
10400 return ExprError();
10401 Args[0] = LHS = Arg0.takeAs<Expr>();
10402 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010403 }
10404
John McCallf89e55a2010-11-18 06:31:45 +000010405 // Determine the result type.
10406 QualType ResultTy = FnDecl->getResultType();
10407 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10408 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010409
10410 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010411 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010412 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010413 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010414 if (FnExpr.isInvalid())
10415 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010416
John McCall9ae2f072010-08-23 23:25:46 +000010417 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010418 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010419 Args, ResultTy, VK, OpLoc,
10420 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010421
10422 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010423 FnDecl))
10424 return ExprError();
10425
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010426 ArrayRef<const Expr *> ArgsArray(Args, 2);
10427 // Cut off the implicit 'this'.
10428 if (isa<CXXMethodDecl>(FnDecl))
10429 ArgsArray = ArgsArray.slice(1);
10430 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10431 TheCall->getSourceRange(), VariadicDoesNotApply);
10432
John McCall9ae2f072010-08-23 23:25:46 +000010433 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010434 } else {
10435 // We matched a built-in operator. Convert the arguments, then
10436 // break out so that we will build the appropriate built-in
10437 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010438 ExprResult ArgsRes0 =
10439 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10440 Best->Conversions[0], AA_Passing);
10441 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010442 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010443 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010444
John Wiegley429bb272011-04-08 18:41:53 +000010445 ExprResult ArgsRes1 =
10446 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10447 Best->Conversions[1], AA_Passing);
10448 if (ArgsRes1.isInvalid())
10449 return ExprError();
10450 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010451 break;
10452 }
10453 }
10454
Douglas Gregor33074752009-09-30 21:46:01 +000010455 case OR_No_Viable_Function: {
10456 // C++ [over.match.oper]p9:
10457 // If the operator is the operator , [...] and there are no
10458 // viable functions, then the operator is assumed to be the
10459 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010460 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010461 break;
10462
Chandler Carruth6df868e2010-12-12 08:17:55 +000010463 // For class as left operand for assignment or compound assigment
10464 // operator do not fall through to handling in built-in, but report that
10465 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010466 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010467 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010468 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010469 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10470 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010471 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010472 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010473 // This is an erroneous use of an operator which can be overloaded by
10474 // a non-member function. Check for non-member operators which were
10475 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010476 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010477 // FIXME: Recover by calling the found function.
10478 return ExprError();
10479
Douglas Gregor33074752009-09-30 21:46:01 +000010480 // No viable function; try to create a built-in operation, which will
10481 // produce an error. Then, show the non-viable candidates.
10482 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010484 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010485 "C++ binary operator overloading is missing candidates!");
10486 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010487 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010488 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010489 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010490 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010491
10492 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010493 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010494 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010495 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010496 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010497 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010498 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010499 return ExprError();
10500
10501 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010502 if (isImplicitlyDeleted(Best->Function)) {
10503 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10504 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010505 << Context.getRecordType(Method->getParent())
10506 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010507
Richard Smith0f46e642012-12-28 12:23:24 +000010508 // The user probably meant to call this special member. Just
10509 // explain why it's deleted.
10510 NoteDeletedFunction(Method);
10511 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010512 } else {
10513 Diag(OpLoc, diag::err_ovl_deleted_oper)
10514 << Best->Function->isDeleted()
10515 << BinaryOperator::getOpcodeStr(Opc)
10516 << getDeletedOrUnavailableSuffix(Best->Function)
10517 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10518 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010519 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010520 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010521 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010522 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010523
Douglas Gregor33074752009-09-30 21:46:01 +000010524 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010525 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010526}
10527
John McCall60d7b3a2010-08-24 06:29:42 +000010528ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010529Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10530 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010531 Expr *Base, Expr *Idx) {
10532 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010533 DeclarationName OpName =
10534 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10535
10536 // If either side is type-dependent, create an appropriate dependent
10537 // expression.
10538 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10539
John McCallc373d482010-01-27 01:50:18 +000010540 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010541 // CHECKME: no 'operator' keyword?
10542 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10543 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010544 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010545 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010546 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010547 /*ADL*/ true, /*Overloaded*/ false,
10548 UnresolvedSetIterator(),
10549 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010550 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010551
Sebastian Redlf322ed62009-10-29 20:17:01 +000010552 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010553 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010554 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010555 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010556 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010557 }
10558
John McCall5acb0c92011-10-17 18:40:02 +000010559 // Handle placeholders on both operands.
10560 if (checkPlaceholderForOverload(*this, Args[0]))
10561 return ExprError();
10562 if (checkPlaceholderForOverload(*this, Args[1]))
10563 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010564
Sebastian Redlf322ed62009-10-29 20:17:01 +000010565 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010566 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010567
10568 // Subscript can only be overloaded as a member function.
10569
10570 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010571 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010572
10573 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010574 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010575
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010576 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10577
Sebastian Redlf322ed62009-10-29 20:17:01 +000010578 // Perform overload resolution.
10579 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010580 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010581 case OR_Success: {
10582 // We found a built-in operator or an overloaded operator.
10583 FunctionDecl *FnDecl = Best->Function;
10584
10585 if (FnDecl) {
10586 // We matched an overloaded operator. Build a call to that
10587 // operator.
10588
John McCall9aa472c2010-03-19 07:35:19 +000010589 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010590
Sebastian Redlf322ed62009-10-29 20:17:01 +000010591 // Convert the arguments.
10592 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010593 ExprResult Arg0 =
10594 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10595 Best->FoundDecl, Method);
10596 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010597 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010598 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010599
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010600 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010601 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010602 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010603 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010604 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010605 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010606 Owned(Args[1]));
10607 if (InputInit.isInvalid())
10608 return ExprError();
10609
10610 Args[1] = InputInit.takeAs<Expr>();
10611
Sebastian Redlf322ed62009-10-29 20:17:01 +000010612 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010613 QualType ResultTy = FnDecl->getResultType();
10614 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10615 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010616
10617 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010618 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10619 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010620 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010621 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010622 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010623 OpLocInfo.getLoc(),
10624 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010625 if (FnExpr.isInvalid())
10626 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010627
John McCall9ae2f072010-08-23 23:25:46 +000010628 CXXOperatorCallExpr *TheCall =
10629 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010630 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010631 ResultTy, VK, RLoc,
10632 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010633
John McCall9ae2f072010-08-23 23:25:46 +000010634 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010635 FnDecl))
10636 return ExprError();
10637
John McCall9ae2f072010-08-23 23:25:46 +000010638 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010639 } else {
10640 // We matched a built-in operator. Convert the arguments, then
10641 // break out so that we will build the appropriate built-in
10642 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010643 ExprResult ArgsRes0 =
10644 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10645 Best->Conversions[0], AA_Passing);
10646 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010647 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010648 Args[0] = ArgsRes0.take();
10649
10650 ExprResult ArgsRes1 =
10651 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10652 Best->Conversions[1], AA_Passing);
10653 if (ArgsRes1.isInvalid())
10654 return ExprError();
10655 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010656
10657 break;
10658 }
10659 }
10660
10661 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010662 if (CandidateSet.empty())
10663 Diag(LLoc, diag::err_ovl_no_oper)
10664 << Args[0]->getType() << /*subscript*/ 0
10665 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10666 else
10667 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10668 << Args[0]->getType()
10669 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010670 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010671 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010672 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010673 }
10674
10675 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010676 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010677 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010678 << Args[0]->getType() << Args[1]->getType()
10679 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010680 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010681 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010682 return ExprError();
10683
10684 case OR_Deleted:
10685 Diag(LLoc, diag::err_ovl_deleted_oper)
10686 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010687 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010688 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010689 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010690 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010691 return ExprError();
10692 }
10693
10694 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010695 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010696}
10697
Douglas Gregor88a35142008-12-22 05:46:06 +000010698/// BuildCallToMemberFunction - Build a call to a member
10699/// function. MemExpr is the expression that refers to the member
10700/// function (and includes the object parameter), Args/NumArgs are the
10701/// arguments to the function call (not including the object
10702/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010703/// expression refers to a non-static member function or an overloaded
10704/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010705ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010706Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010707 SourceLocation LParenLoc,
10708 MultiExprArg Args,
10709 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010710 assert(MemExprE->getType() == Context.BoundMemberTy ||
10711 MemExprE->getType() == Context.OverloadTy);
10712
Douglas Gregor88a35142008-12-22 05:46:06 +000010713 // Dig out the member expression. This holds both the object
10714 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010715 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010716
John McCall864c0412011-04-26 20:42:42 +000010717 // Determine whether this is a call to a pointer-to-member function.
10718 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10719 assert(op->getType() == Context.BoundMemberTy);
10720 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10721
10722 QualType fnType =
10723 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10724
10725 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10726 QualType resultType = proto->getCallResultType(Context);
10727 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10728
10729 // Check that the object type isn't more qualified than the
10730 // member function we're calling.
10731 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10732
10733 QualType objectType = op->getLHS()->getType();
10734 if (op->getOpcode() == BO_PtrMemI)
10735 objectType = objectType->castAs<PointerType>()->getPointeeType();
10736 Qualifiers objectQuals = objectType.getQualifiers();
10737
10738 Qualifiers difference = objectQuals - funcQuals;
10739 difference.removeObjCGCAttr();
10740 difference.removeAddressSpace();
10741 if (difference) {
10742 std::string qualsString = difference.getAsString();
10743 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10744 << fnType.getUnqualifiedType()
10745 << qualsString
10746 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10747 }
10748
10749 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010750 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010751 resultType, valueKind, RParenLoc);
10752
10753 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010754 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010755 call, 0))
10756 return ExprError();
10757
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010758 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000010759 return ExprError();
10760
10761 return MaybeBindToTemporary(call);
10762 }
10763
John McCall5acb0c92011-10-17 18:40:02 +000010764 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010765 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010766 return ExprError();
10767
John McCall129e2df2009-11-30 22:42:35 +000010768 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010769 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010770 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010771 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010772 if (isa<MemberExpr>(NakedMemExpr)) {
10773 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010774 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010775 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010776 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010777 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010778 } else {
10779 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010780 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010781
John McCall701c89e2009-12-03 04:06:58 +000010782 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010783 Expr::Classification ObjectClassification
10784 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10785 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010786
Douglas Gregor88a35142008-12-22 05:46:06 +000010787 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010788 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010789
John McCallaa81e162009-12-01 22:10:20 +000010790 // FIXME: avoid copy.
10791 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10792 if (UnresExpr->hasExplicitTemplateArgs()) {
10793 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10794 TemplateArgs = &TemplateArgsBuffer;
10795 }
10796
John McCall129e2df2009-11-30 22:42:35 +000010797 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10798 E = UnresExpr->decls_end(); I != E; ++I) {
10799
John McCall701c89e2009-12-03 04:06:58 +000010800 NamedDecl *Func = *I;
10801 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10802 if (isa<UsingShadowDecl>(Func))
10803 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10804
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010805
Francois Pichetdbee3412011-01-18 05:04:39 +000010806 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010807 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010808 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010809 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010810 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010811 // If explicit template arguments were provided, we can't call a
10812 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010813 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010814 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010815
John McCall9aa472c2010-03-19 07:35:19 +000010816 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010817 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010818 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010819 } else {
John McCall129e2df2009-11-30 22:42:35 +000010820 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010821 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010822 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010823 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010824 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010825 }
Douglas Gregordec06662009-08-21 18:42:58 +000010826 }
Mike Stump1eb44332009-09-09 15:08:12 +000010827
John McCall129e2df2009-11-30 22:42:35 +000010828 DeclarationName DeclName = UnresExpr->getMemberName();
10829
John McCall5acb0c92011-10-17 18:40:02 +000010830 UnbridgedCasts.restore();
10831
Douglas Gregor88a35142008-12-22 05:46:06 +000010832 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010833 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010834 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010835 case OR_Success:
10836 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010837 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010838 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010839 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10840 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010841 break;
10842
10843 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010844 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010845 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010846 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010847 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010848 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010849 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010850
10851 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010852 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010853 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010855 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010856 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010857
10858 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010859 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010860 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010861 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010862 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010863 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010864 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010865 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010866 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010867 }
10868
John McCall6bb80172010-03-30 21:47:33 +000010869 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010870
John McCallaa81e162009-12-01 22:10:20 +000010871 // If overload resolution picked a static member, build a
10872 // non-member call based on that function.
10873 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010874 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
10875 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000010876 }
10877
John McCall129e2df2009-11-30 22:42:35 +000010878 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010879 }
10880
John McCallf89e55a2010-11-18 06:31:45 +000010881 QualType ResultType = Method->getResultType();
10882 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10883 ResultType = ResultType.getNonLValueExprType(Context);
10884
Douglas Gregor88a35142008-12-22 05:46:06 +000010885 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010886 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010887 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000010888 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010889
Anders Carlssoneed3e692009-10-10 00:06:20 +000010890 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010891 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010892 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010893 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010894
Douglas Gregor88a35142008-12-22 05:46:06 +000010895 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010896 // We only need to do this if there was actually an overload; otherwise
10897 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010898 if (!Method->isStatic()) {
10899 ExprResult ObjectArg =
10900 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10901 FoundDecl, Method);
10902 if (ObjectArg.isInvalid())
10903 return ExprError();
10904 MemExpr->setBase(ObjectArg.take());
10905 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010906
10907 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010908 const FunctionProtoType *Proto =
10909 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010910 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000010911 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010912 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010913
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010914 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000010915
Richard Smith831421f2012-06-25 20:30:08 +000010916 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010917 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010918
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010919 if ((isa<CXXConstructorDecl>(CurContext) ||
10920 isa<CXXDestructorDecl>(CurContext)) &&
10921 TheCall->getMethodDecl()->isPure()) {
10922 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10923
Chandler Carruthae198062011-06-27 08:31:58 +000010924 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010925 Diag(MemExpr->getLocStart(),
10926 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10927 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10928 << MD->getParent()->getDeclName();
10929
10930 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010931 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010932 }
John McCall9ae2f072010-08-23 23:25:46 +000010933 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010934}
10935
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010936/// BuildCallToObjectOfClassType - Build a call to an object of class
10937/// type (C++ [over.call.object]), which can end up invoking an
10938/// overloaded function call operator (@c operator()) or performing a
10939/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010940ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010941Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010942 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000010943 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010944 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010945 if (checkPlaceholderForOverload(*this, Obj))
10946 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010947 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010948
10949 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000010950 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010951 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010952
John Wiegley429bb272011-04-08 18:41:53 +000010953 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10954 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010955
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010956 // C++ [over.call.object]p1:
10957 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010958 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010959 // candidate functions includes at least the function call
10960 // operators of T. The function call operators of T are obtained by
10961 // ordinary lookup of the name operator() in the context of
10962 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010963 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010964 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010965
John Wiegley429bb272011-04-08 18:41:53 +000010966 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010967 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010968 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010969
John McCalla24dc2e2009-11-17 02:14:36 +000010970 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10971 LookupQualifiedName(R, Record->getDecl());
10972 R.suppressDiagnostics();
10973
Douglas Gregor593564b2009-11-15 07:48:03 +000010974 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010975 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010976 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000010977 Object.get()->Classify(Context),
10978 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010979 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010981
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010982 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010983 // In addition, for each (non-explicit in C++0x) conversion function
10984 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010985 //
10986 // operator conversion-type-id () cv-qualifier;
10987 //
10988 // where cv-qualifier is the same cv-qualification as, or a
10989 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010990 // denotes the type "pointer to function of (P1,...,Pn) returning
10991 // R", or the type "reference to pointer to function of
10992 // (P1,...,Pn) returning R", or the type "reference to function
10993 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010994 // is also considered as a candidate function. Similarly,
10995 // surrogate call functions are added to the set of candidate
10996 // functions for each conversion function declared in an
10997 // accessible base class provided the function is not hidden
10998 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010999 std::pair<CXXRecordDecl::conversion_iterator,
11000 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011001 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011002 for (CXXRecordDecl::conversion_iterator
11003 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011004 NamedDecl *D = *I;
11005 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11006 if (isa<UsingShadowDecl>(D))
11007 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011008
Douglas Gregor4a27d702009-10-21 06:18:39 +000011009 // Skip over templated conversion functions; they aren't
11010 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011011 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011012 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011013
John McCall701c89e2009-12-03 04:06:58 +000011014 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011015 if (!Conv->isExplicit()) {
11016 // Strip the reference type (if any) and then the pointer type (if
11017 // any) to get down to what might be a function type.
11018 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11019 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11020 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011021
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011022 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11023 {
11024 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011025 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011026 }
11027 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011028 }
Mike Stump1eb44332009-09-09 15:08:12 +000011029
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011030 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11031
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011032 // Perform overload resolution.
11033 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011034 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011035 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011036 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011037 // Overload resolution succeeded; we'll build the appropriate call
11038 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011039 break;
11040
11041 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011042 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011043 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011044 << Object.get()->getType() << /*call*/ 1
11045 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011046 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011047 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011048 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011049 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011050 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011051 break;
11052
11053 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011054 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011055 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011056 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011057 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011058 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011059
11060 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011061 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011062 diag::err_ovl_deleted_object_call)
11063 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011064 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011065 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011066 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011067 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011068 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011069 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011070
Douglas Gregorff331c12010-07-25 18:17:45 +000011071 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011072 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011073
John McCall5acb0c92011-10-17 18:40:02 +000011074 UnbridgedCasts.restore();
11075
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011076 if (Best->Function == 0) {
11077 // Since there is no function declaration, this is one of the
11078 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011079 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011080 = cast<CXXConversionDecl>(
11081 Best->Conversions[0].UserDefined.ConversionFunction);
11082
John Wiegley429bb272011-04-08 18:41:53 +000011083 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011084 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11085 return ExprError();
John McCall41d89032010-01-28 01:54:34 +000011086
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011087 // We selected one of the surrogate functions that converts the
11088 // object parameter to a function pointer. Perform the conversion
11089 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011090
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011091 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011092 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011093 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11094 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011095 if (Call.isInvalid())
11096 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011097 // Record usage of conversion in an implicit cast.
11098 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11099 CK_UserDefinedConversion,
11100 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011101
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011102 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011103 }
11104
John Wiegley429bb272011-04-08 18:41:53 +000011105 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011106
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011107 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11108 // that calls this method, using Object for the implicit object
11109 // parameter and passing along the remaining arguments.
11110 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011111
11112 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011113 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011114 return ExprError();
11115
Chandler Carruth6df868e2010-12-12 08:17:55 +000011116 const FunctionProtoType *Proto =
11117 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011118
11119 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011120 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011121
11122 // Build the full argument list for the method call (the
11123 // implicit object parameter is placed at the beginning of the
11124 // list).
11125 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011126 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011127 NumArgsToCheck = NumArgsInProto;
11128 MethodArgs = new Expr*[NumArgsInProto + 1];
11129 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011130 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011131 }
John Wiegley429bb272011-04-08 18:41:53 +000011132 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011133 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011134 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011135
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011136 DeclarationNameInfo OpLocInfo(
11137 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11138 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011139 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011140 HadMultipleCandidates,
11141 OpLocInfo.getLoc(),
11142 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011143 if (NewFn.isInvalid())
11144 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011145
11146 // Once we've built TheCall, all of the expressions are properly
11147 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011148 QualType ResultTy = Method->getResultType();
11149 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11150 ResultTy = ResultTy.getNonLValueExprType(Context);
11151
John McCall9ae2f072010-08-23 23:25:46 +000011152 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011153 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011154 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011155 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011156 delete [] MethodArgs;
11157
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011158 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011159 Method))
11160 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011161
Douglas Gregor518fda12009-01-13 05:10:00 +000011162 // We may have default arguments. If so, we need to allocate more
11163 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011164 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011165 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011166 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011167 NumArgsToCheck = NumArgsInProto;
11168
Chris Lattner312531a2009-04-12 08:11:20 +000011169 bool IsError = false;
11170
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011171 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011172 ExprResult ObjRes =
11173 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11174 Best->FoundDecl, Method);
11175 if (ObjRes.isInvalid())
11176 IsError = true;
11177 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011178 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011179 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011180
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011181 // Check the argument types.
11182 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011183 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011184 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011185 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011186
Douglas Gregor518fda12009-01-13 05:10:00 +000011187 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011188
John McCall60d7b3a2010-08-24 06:29:42 +000011189 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011190 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011191 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011192 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011193 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011194
Anders Carlsson3faa4862010-01-29 18:43:53 +000011195 IsError |= InputInit.isInvalid();
11196 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011197 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011198 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011199 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11200 if (DefArg.isInvalid()) {
11201 IsError = true;
11202 break;
11203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011204
Douglas Gregord47c47d2009-11-09 19:27:57 +000011205 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011206 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011207
11208 TheCall->setArg(i + 1, Arg);
11209 }
11210
11211 // If this is a variadic call, handle args passed through "...".
11212 if (Proto->isVariadic()) {
11213 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011214 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011215 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11216 IsError |= Arg.isInvalid();
11217 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011218 }
11219 }
11220
Chris Lattner312531a2009-04-12 08:11:20 +000011221 if (IsError) return true;
11222
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011223 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011224
Richard Smith831421f2012-06-25 20:30:08 +000011225 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011226 return true;
11227
John McCall182f7092010-08-24 06:09:16 +000011228 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011229}
11230
Douglas Gregor8ba10742008-11-20 16:27:02 +000011231/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011232/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011233/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011234ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011235Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011236 assert(Base->getType()->isRecordType() &&
11237 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011238
John McCall5acb0c92011-10-17 18:40:02 +000011239 if (checkPlaceholderForOverload(*this, Base))
11240 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011241
John McCall5769d612010-02-08 23:07:23 +000011242 SourceLocation Loc = Base->getExprLoc();
11243
Douglas Gregor8ba10742008-11-20 16:27:02 +000011244 // C++ [over.ref]p1:
11245 //
11246 // [...] An expression x->m is interpreted as (x.operator->())->m
11247 // for a class object x of type T if T::operator->() exists and if
11248 // the operator is selected as the best match function by the
11249 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011250 DeclarationName OpName =
11251 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011252 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011253 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011254
John McCall5769d612010-02-08 23:07:23 +000011255 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011256 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011257 return ExprError();
11258
John McCalla24dc2e2009-11-17 02:14:36 +000011259 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11260 LookupQualifiedName(R, BaseRecord->getDecl());
11261 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011262
11263 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011264 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011265 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011266 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011267 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011268
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011269 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11270
Douglas Gregor8ba10742008-11-20 16:27:02 +000011271 // Perform overload resolution.
11272 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011273 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011274 case OR_Success:
11275 // Overload resolution succeeded; we'll build the call below.
11276 break;
11277
11278 case OR_No_Viable_Function:
11279 if (CandidateSet.empty())
11280 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011281 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011282 else
11283 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011284 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011285 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011286 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011287
11288 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011289 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11290 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011291 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011292 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011293
11294 case OR_Deleted:
11295 Diag(OpLoc, diag::err_ovl_deleted_oper)
11296 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011297 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011298 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011299 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011300 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011301 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011302 }
11303
John McCall9aa472c2010-03-19 07:35:19 +000011304 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11305
Douglas Gregor8ba10742008-11-20 16:27:02 +000011306 // Convert the object parameter.
11307 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011308 ExprResult BaseResult =
11309 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11310 Best->FoundDecl, Method);
11311 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011312 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011313 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011314
Douglas Gregor8ba10742008-11-20 16:27:02 +000011315 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011316 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011317 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011318 if (FnExpr.isInvalid())
11319 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011320
John McCallf89e55a2010-11-18 06:31:45 +000011321 QualType ResultTy = Method->getResultType();
11322 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11323 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011324 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011325 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011326 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011327
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011328 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011329 Method))
11330 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011331
11332 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011333}
11334
Richard Smith36f5cfe2012-03-09 08:00:36 +000011335/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11336/// a literal operator described by the provided lookup results.
11337ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11338 DeclarationNameInfo &SuffixInfo,
11339 ArrayRef<Expr*> Args,
11340 SourceLocation LitEndLoc,
11341 TemplateArgumentListInfo *TemplateArgs) {
11342 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011343
Richard Smith36f5cfe2012-03-09 08:00:36 +000011344 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11345 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11346 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011347
Richard Smith36f5cfe2012-03-09 08:00:36 +000011348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11349
Richard Smith36f5cfe2012-03-09 08:00:36 +000011350 // Perform overload resolution. This will usually be trivial, but might need
11351 // to perform substitutions for a literal operator template.
11352 OverloadCandidateSet::iterator Best;
11353 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11354 case OR_Success:
11355 case OR_Deleted:
11356 break;
11357
11358 case OR_No_Viable_Function:
11359 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11360 << R.getLookupName();
11361 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11362 return ExprError();
11363
11364 case OR_Ambiguous:
11365 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11366 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11367 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011368 }
11369
Richard Smith36f5cfe2012-03-09 08:00:36 +000011370 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011371 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11372 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011373 SuffixInfo.getLoc(),
11374 SuffixInfo.getInfo());
11375 if (Fn.isInvalid())
11376 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011377
11378 // Check the argument types. This should almost always be a no-op, except
11379 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011380 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011381 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011382 ExprResult InputInit = PerformCopyInitialization(
11383 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11384 SourceLocation(), Args[ArgIdx]);
11385 if (InputInit.isInvalid())
11386 return true;
11387 ConvArgs[ArgIdx] = InputInit.take();
11388 }
11389
Richard Smith9fcce652012-03-07 08:35:16 +000011390 QualType ResultTy = FD->getResultType();
11391 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11392 ResultTy = ResultTy.getNonLValueExprType(Context);
11393
Richard Smith9fcce652012-03-07 08:35:16 +000011394 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011395 new (Context) UserDefinedLiteral(Context, Fn.take(),
11396 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011397 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11398
11399 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11400 return ExprError();
11401
Richard Smith831421f2012-06-25 20:30:08 +000011402 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011403 return ExprError();
11404
11405 return MaybeBindToTemporary(UDL);
11406}
11407
Sam Panzere1715b62012-08-21 00:52:01 +000011408/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11409/// given LookupResult is non-empty, it is assumed to describe a member which
11410/// will be invoked. Otherwise, the function will be found via argument
11411/// dependent lookup.
11412/// CallExpr is set to a valid expression and FRS_Success returned on success,
11413/// otherwise CallExpr is set to ExprError() and some non-success value
11414/// is returned.
11415Sema::ForRangeStatus
11416Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11417 SourceLocation RangeLoc, VarDecl *Decl,
11418 BeginEndFunction BEF,
11419 const DeclarationNameInfo &NameInfo,
11420 LookupResult &MemberLookup,
11421 OverloadCandidateSet *CandidateSet,
11422 Expr *Range, ExprResult *CallExpr) {
11423 CandidateSet->clear();
11424 if (!MemberLookup.empty()) {
11425 ExprResult MemberRef =
11426 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11427 /*IsPtr=*/false, CXXScopeSpec(),
11428 /*TemplateKWLoc=*/SourceLocation(),
11429 /*FirstQualifierInScope=*/0,
11430 MemberLookup,
11431 /*TemplateArgs=*/0);
11432 if (MemberRef.isInvalid()) {
11433 *CallExpr = ExprError();
11434 Diag(Range->getLocStart(), diag::note_in_for_range)
11435 << RangeLoc << BEF << Range->getType();
11436 return FRS_DiagnosticIssued;
11437 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011438 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011439 if (CallExpr->isInvalid()) {
11440 *CallExpr = ExprError();
11441 Diag(Range->getLocStart(), diag::note_in_for_range)
11442 << RangeLoc << BEF << Range->getType();
11443 return FRS_DiagnosticIssued;
11444 }
11445 } else {
11446 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011447 UnresolvedLookupExpr *Fn =
11448 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11449 NestedNameSpecifierLoc(), NameInfo,
11450 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011451 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011452
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011453 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011454 CandidateSet, CallExpr);
11455 if (CandidateSet->empty() || CandidateSetError) {
11456 *CallExpr = ExprError();
11457 return FRS_NoViableFunction;
11458 }
11459 OverloadCandidateSet::iterator Best;
11460 OverloadingResult OverloadResult =
11461 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11462
11463 if (OverloadResult == OR_No_Viable_Function) {
11464 *CallExpr = ExprError();
11465 return FRS_NoViableFunction;
11466 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011467 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011468 Loc, 0, CandidateSet, &Best,
11469 OverloadResult,
11470 /*AllowTypoCorrection=*/false);
11471 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11472 *CallExpr = ExprError();
11473 Diag(Range->getLocStart(), diag::note_in_for_range)
11474 << RangeLoc << BEF << Range->getType();
11475 return FRS_DiagnosticIssued;
11476 }
11477 }
11478 return FRS_Success;
11479}
11480
11481
Douglas Gregor904eed32008-11-10 20:40:00 +000011482/// FixOverloadedFunctionReference - E is an expression that refers to
11483/// a C++ overloaded function (possibly with some parentheses and
11484/// perhaps a '&' around it). We have resolved the overloaded function
11485/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011486/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011487Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011488 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011489 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011490 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11491 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011492 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011493 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011494
Douglas Gregor699ee522009-11-20 19:42:02 +000011495 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011496 }
11497
Douglas Gregor699ee522009-11-20 19:42:02 +000011498 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011499 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11500 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011501 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011502 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011503 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011504 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011505 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011506 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011507
11508 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011509 ICE->getCastKind(),
11510 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011511 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011512 }
11513
Douglas Gregor699ee522009-11-20 19:42:02 +000011514 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011515 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011516 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011517 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11518 if (Method->isStatic()) {
11519 // Do nothing: static member functions aren't any different
11520 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011521 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011522 // Fix the sub expression, which really has to be an
11523 // UnresolvedLookupExpr holding an overloaded member function
11524 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011525 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11526 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011527 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011528 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011529
John McCallba135432009-11-21 08:51:07 +000011530 assert(isa<DeclRefExpr>(SubExpr)
11531 && "fixed to something other than a decl ref");
11532 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11533 && "fixed to a member ref with no nested name qualifier");
11534
11535 // We have taken the address of a pointer to member
11536 // function. Perform the computation here so that we get the
11537 // appropriate pointer to member type.
11538 QualType ClassType
11539 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11540 QualType MemPtrType
11541 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11542
John McCallf89e55a2010-11-18 06:31:45 +000011543 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11544 VK_RValue, OK_Ordinary,
11545 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011546 }
11547 }
John McCall6bb80172010-03-30 21:47:33 +000011548 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11549 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011550 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011551 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011552
John McCall2de56d12010-08-25 11:45:40 +000011553 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011554 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011555 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011556 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011557 }
John McCallba135432009-11-21 08:51:07 +000011558
11559 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011560 // FIXME: avoid copy.
11561 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011562 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011563 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11564 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011565 }
11566
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011567 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11568 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011569 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011570 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011571 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011572 ULE->getNameLoc(),
11573 Fn->getType(),
11574 VK_LValue,
11575 Found.getDecl(),
11576 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011577 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011578 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11579 return DRE;
John McCallba135432009-11-21 08:51:07 +000011580 }
11581
John McCall129e2df2009-11-30 22:42:35 +000011582 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011583 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011584 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11585 if (MemExpr->hasExplicitTemplateArgs()) {
11586 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11587 TemplateArgs = &TemplateArgsBuffer;
11588 }
John McCalld5532b62009-11-23 01:53:49 +000011589
John McCallaa81e162009-12-01 22:10:20 +000011590 Expr *Base;
11591
John McCallf89e55a2010-11-18 06:31:45 +000011592 // If we're filling in a static method where we used to have an
11593 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011594 if (MemExpr->isImplicitAccess()) {
11595 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011596 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11597 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011598 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011599 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011600 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011601 MemExpr->getMemberLoc(),
11602 Fn->getType(),
11603 VK_LValue,
11604 Found.getDecl(),
11605 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011606 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011607 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11608 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011609 } else {
11610 SourceLocation Loc = MemExpr->getMemberLoc();
11611 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011612 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011613 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011614 Base = new (Context) CXXThisExpr(Loc,
11615 MemExpr->getBaseType(),
11616 /*isImplicit=*/true);
11617 }
John McCallaa81e162009-12-01 22:10:20 +000011618 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011619 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011620
John McCallf5307512011-04-27 00:36:17 +000011621 ExprValueKind valueKind;
11622 QualType type;
11623 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11624 valueKind = VK_LValue;
11625 type = Fn->getType();
11626 } else {
11627 valueKind = VK_RValue;
11628 type = Context.BoundMemberTy;
11629 }
11630
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011631 MemberExpr *ME = MemberExpr::Create(Context, Base,
11632 MemExpr->isArrow(),
11633 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011634 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011635 Fn,
11636 Found,
11637 MemExpr->getMemberNameInfo(),
11638 TemplateArgs,
11639 type, valueKind, OK_Ordinary);
11640 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011641 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011642 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011644
John McCall3fa5cae2010-10-26 07:05:15 +000011645 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011646}
11647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011648ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011649 DeclAccessPair Found,
11650 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011651 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011652}
11653
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011654} // end namespace clang