blob: 084e25a1cbbfebf45133bc9b59c1ee7213562489 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-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 Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000133 ICR_Writeback_Conversion,
134 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
135 // it was omitted by the patch that added
136 // ICK_Zero_Event_Conversion
137 ICR_C_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000138 };
139 return Rank[(int)Kind];
140}
141
142/// GetImplicitConversionName - Return the name of this kind of
143/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000144static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000145 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000146 "No conversion",
147 "Lvalue-to-rvalue",
148 "Array-to-pointer",
149 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000150 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Qualification",
152 "Integral promotion",
153 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000154 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "Integral conversion",
156 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000157 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "Floating-integral conversion",
159 "Pointer conversion",
160 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000161 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000162 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000163 "Derived-to-base conversion",
164 "Vector conversion",
165 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000166 "Complex-real conversion",
167 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000168 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000169 "Writeback conversion",
170 "OpenCL Zero Event Conversion",
171 "C specific type conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000172 };
173 return Name[Kind];
174}
175
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000176/// StandardConversionSequence - Set the standard conversion
177/// sequence to the identity conversion.
178void StandardConversionSequence::setAsIdentityConversion() {
179 First = ICK_Identity;
180 Second = ICK_Identity;
181 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000182 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000183 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000190 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000191 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000192}
193
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194/// getRank - Retrieve the rank of this standard conversion sequence
195/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
196/// implicit conversions.
197ImplicitConversionRank StandardConversionSequence::getRank() const {
198 ImplicitConversionRank Rank = ICR_Exact_Match;
199 if (GetConversionRank(First) > Rank)
200 Rank = GetConversionRank(First);
201 if (GetConversionRank(Second) > Rank)
202 Rank = GetConversionRank(Second);
203 if (GetConversionRank(Third) > Rank)
204 Rank = GetConversionRank(Third);
205 return Rank;
206}
207
208/// isPointerConversionToBool - Determines whether this conversion is
209/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000210/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000212bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 // Note that FromType has not necessarily been transformed by the
214 // array-to-pointer or function-to-pointer implicit conversions, so
215 // check for their presence as well as checking whether FromType is
216 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000217 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000218 (getFromType()->isPointerType() ||
219 getFromType()->isObjCObjectPointerType() ||
220 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000221 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
223 return true;
224
225 return false;
226}
227
Douglas Gregor5c407d92008-10-23 00:40:37 +0000228/// isPointerConversionToVoidPointer - Determines whether this
229/// conversion is a conversion of a pointer to a void pointer. This is
230/// used as part of the ranking of standard conversion sequences (C++
231/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000232bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000233StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000234isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000235 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000236 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000237
238 // Note that FromType has not necessarily been transformed by the
239 // array-to-pointer implicit conversion, so check for its presence
240 // and redo the conversion to get a pointer.
241 if (First == ICK_Array_To_Pointer)
242 FromType = Context.getArrayDecayedType(FromType);
243
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000244 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000245 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000246 return ToPtrType->getPointeeType()->isVoidType();
247
248 return false;
249}
250
Richard Smith66e05fe2012-01-18 05:21:49 +0000251/// Skip any implicit casts which could be either part of a narrowing conversion
252/// or after one in an implicit conversion.
253static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
254 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
255 switch (ICE->getCastKind()) {
256 case CK_NoOp:
257 case CK_IntegralCast:
258 case CK_IntegralToBoolean:
259 case CK_IntegralToFloating:
260 case CK_FloatingToIntegral:
261 case CK_FloatingToBoolean:
262 case CK_FloatingCast:
263 Converted = ICE->getSubExpr();
264 continue;
265
266 default:
267 return Converted;
268 }
269 }
270
271 return Converted;
272}
273
274/// Check if this standard conversion sequence represents a narrowing
275/// conversion, according to C++11 [dcl.init.list]p7.
276///
277/// \param Ctx The AST context.
278/// \param Converted The result of applying this standard conversion sequence.
279/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
280/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000281/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
282/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000283NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000284StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
285 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000286 APValue &ConstantValue,
287 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000289
290 // C++11 [dcl.init.list]p7:
291 // A narrowing conversion is an implicit conversion ...
292 QualType FromType = getToType(0);
293 QualType ToType = getToType(1);
294 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000295 // 'bool' is an integral type; dispatch to the right place to handle it.
296 case ICK_Boolean_Conversion:
297 if (FromType->isRealFloatingType())
298 goto FloatingIntegralConversion;
299 if (FromType->isIntegralOrUnscopedEnumerationType())
300 goto IntegralConversion;
301 // Boolean conversions can be from pointers and pointers to members
302 // [conv.bool], and those aren't considered narrowing conversions.
303 return NK_Not_Narrowing;
304
Richard Smith66e05fe2012-01-18 05:21:49 +0000305 // -- from a floating-point type to an integer type, or
306 //
307 // -- from an integer type or unscoped enumeration type to a floating-point
308 // type, except where the source is a constant expression and the actual
309 // value after conversion will fit into the target type and will produce
310 // the original value when converted back to the original type, or
311 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000312 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000365 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000377 case ICK_Integral_Conversion:
378 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000379 assert(FromType->isIntegralOrUnscopedEnumerationType());
380 assert(ToType->isIntegralOrUnscopedEnumerationType());
381 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
382 const unsigned FromWidth = Ctx.getIntWidth(FromType);
383 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
384 const unsigned ToWidth = Ctx.getIntWidth(ToType);
385
386 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000387 (FromWidth == ToWidth && FromSigned != ToSigned) ||
388 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000389 // Not all values of FromType can be represented in ToType.
390 llvm::APSInt InitializerValue;
391 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000392 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
393 // Such conversions on variables are always narrowing.
394 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000395 }
396 bool Narrowing = false;
397 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000398 // Negative -> unsigned is narrowing. Otherwise, more bits is never
399 // narrowing.
400 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000401 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000402 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 // Add a bit to the InitializerValue so we don't have to worry about
404 // signed vs. unsigned comparisons.
405 InitializerValue = InitializerValue.extend(
406 InitializerValue.getBitWidth() + 1);
407 // Convert the initializer to and from the target width and signed-ness.
408 llvm::APSInt ConvertedValue = InitializerValue;
409 ConvertedValue = ConvertedValue.trunc(ToWidth);
410 ConvertedValue.setIsSigned(ToSigned);
411 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
412 ConvertedValue.setIsSigned(InitializerValue.isSigned());
413 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000414 if (ConvertedValue != InitializerValue)
415 Narrowing = true;
416 }
417 if (Narrowing) {
418 ConstantType = Initializer->getType();
419 ConstantValue = APValue(InitializerValue);
420 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000421 }
422 }
423 return NK_Not_Narrowing;
424 }
425
426 default:
427 // Other kinds of conversions are not narrowings.
428 return NK_Not_Narrowing;
429 }
430}
431
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000432/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000434void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000435 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000436 bool PrintedSomething = false;
437 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439 PrintedSomething = true;
440 }
441
442 if (Second != ICK_Identity) {
443 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000447
448 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000450 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 PrintedSomething = true;
456 }
457
458 if (Third != ICK_Identity) {
459 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 PrintedSomething = true;
464 }
465
466 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 }
469}
470
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000471/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000474 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000476 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000477 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000479 if (ConversionFunction)
480 OS << '\'' << *ConversionFunction << '\'';
481 else
482 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000484 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486 }
487}
488
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000489/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000491void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000493 if (isStdInitializerListElement())
494 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 switch (ConversionKind) {
496 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000498 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 break;
500 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000502 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503 break;
504 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
John McCall0d1da222010-01-12 00:44:57 +0000507 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000509 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 break;
513 }
514
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516}
517
John McCall0d1da222010-01-12 00:44:57 +0000518void AmbiguousConversionSequence::construct() {
519 new (&conversions()) ConversionSet();
520}
521
522void AmbiguousConversionSequence::destruct() {
523 conversions().~ConversionSet();
524}
525
526void
527AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
528 FromTypePtr = O.FromTypePtr;
529 ToTypePtr = O.ToTypePtr;
530 new (&conversions()) ConversionSet(O.conversions());
531}
532
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000535 // template argument information.
536 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537 TemplateArgument FirstArg;
538 TemplateArgument SecondArg;
539 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000540 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000541 // template parameter and template argument information.
542 struct DFIParamWithArguments : DFIArguments {
543 TemplateParameter Param;
544 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000545}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000549DeductionFailureInfo
550clang::MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
552 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000553 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000556 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Richard Smith44ecdbd2013-01-31 05:19:49 +0000570 case Sema::TDK_NonDeducedMismatch: {
571 // FIXME: Should allocate from normal heap so that we can free this later.
572 DFIArguments *Saved = new (Context) DFIArguments;
573 Saved->FirstArg = Info.FirstArg;
574 Saved->SecondArg = Info.SecondArg;
575 Result.Data = Saved;
576 break;
577 }
578
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000580 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000581 // FIXME: Should allocate from normal heap so that we can free this later.
582 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 Saved->Param = Info.Param;
584 Saved->FirstArg = Info.FirstArg;
585 Saved->SecondArg = Info.SecondArg;
586 Result.Data = Saved;
587 break;
588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000591 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000592 if (Info.hasSFINAEDiagnostic()) {
593 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
594 SourceLocation(), PartialDiagnostic::NullDiagnostic());
595 Info.takeSFINAEDiagnostic(*Diag);
596 Result.HasDiagnostic = true;
597 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000598 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000601 Result.Data = Info.Expression;
602 break;
603
Richard Smith44ecdbd2013-01-31 05:19:49 +0000604 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 return Result;
609}
John McCall0d1da222010-01-12 00:44:57 +0000610
Larisse Voufo98b20f12013-07-19 23:00:19 +0000611void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000612 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
613 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000614 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 case Sema::TDK_InstantiationDepth:
616 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000617 case Sema::TDK_TooManyArguments:
618 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000619 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000620 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000624 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000625 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000626 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000627 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000629
630 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000631 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000632 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000633 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
634 Diag->~PartialDiagnosticAt();
635 HasDiagnostic = false;
636 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor461761d2010-05-08 18:20:53 +0000639 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000640 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 break;
642 }
643}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Larisse Voufo98b20f12013-07-19 23:00:19 +0000645PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000646 if (HasDiagnostic)
647 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000648 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000649}
650
Larisse Voufo98b20f12013-07-19 23:00:19 +0000651TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
653 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000654 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000656 case Sema::TDK_TooManyArguments:
657 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000658 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000659 case Sema::TDK_NonDeducedMismatch:
660 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000664 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000666
667 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000668 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000671 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000672 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 break;
674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000676 return TemplateParameter();
677}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Larisse Voufo98b20f12013-07-19 23:00:19 +0000679TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000681 case Sema::TDK_Success:
682 case Sema::TDK_Invalid:
683 case Sema::TDK_InstantiationDepth:
684 case Sema::TDK_TooManyArguments:
685 case Sema::TDK_TooFewArguments:
686 case Sema::TDK_Incomplete:
687 case Sema::TDK_InvalidExplicitArguments:
688 case Sema::TDK_Inconsistent:
689 case Sema::TDK_Underqualified:
690 case Sema::TDK_NonDeducedMismatch:
691 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000692 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000693
Richard Smith44ecdbd2013-01-31 05:19:49 +0000694 case Sema::TDK_SubstitutionFailure:
695 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Richard Smith44ecdbd2013-01-31 05:19:49 +0000697 // Unhandled
698 case Sema::TDK_MiscellaneousDeductionFailure:
699 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000700 }
701
Craig Topperc3ec1492014-05-26 06:22:03 +0000702 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000703}
704
Larisse Voufo98b20f12013-07-19 23:00:19 +0000705const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
707 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000708 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000709 case Sema::TDK_InstantiationDepth:
710 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000711 case Sema::TDK_TooManyArguments:
712 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000713 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000714 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000715 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000716 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000719 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000720 case Sema::TDK_NonDeducedMismatch:
721 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722
Douglas Gregor461761d2010-05-08 18:20:53 +0000723 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000724 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 break;
726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Craig Topperc3ec1492014-05-26 06:22:03 +0000728 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730
Larisse Voufo98b20f12013-07-19 23:00:19 +0000731const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000734 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000737 case Sema::TDK_TooManyArguments:
738 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000739 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000740 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000741 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000744 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000745 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000746 case Sema::TDK_NonDeducedMismatch:
747 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748
Douglas Gregor461761d2010-05-08 18:20:53 +0000749 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000750 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000751 break;
752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753
Craig Topperc3ec1492014-05-26 06:22:03 +0000754 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755}
756
Larisse Voufo98b20f12013-07-19 23:00:19 +0000757Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000758 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
759 Sema::TDK_FailedOverloadResolution)
760 return static_cast<Expr*>(Data);
761
Craig Topperc3ec1492014-05-26 06:22:03 +0000762 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000763}
764
Benjamin Kramer97e59492012-10-09 15:52:25 +0000765void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000766 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000767 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
768 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000769 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
770 i->DeductionFailure.Destroy();
771 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000772}
773
774void OverloadCandidateSet::clear() {
775 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000776 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000777 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000778 Functions.clear();
779}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
John McCall4124c492011-10-17 18:40:02 +0000781namespace {
782 class UnbridgedCastsSet {
783 struct Entry {
784 Expr **Addr;
785 Expr *Saved;
786 };
787 SmallVector<Entry, 2> Entries;
788
789 public:
790 void save(Sema &S, Expr *&E) {
791 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
792 Entry entry = { &E, E };
793 Entries.push_back(entry);
794 E = S.stripARCUnbridgedCast(E);
795 }
796
797 void restore() {
798 for (SmallVectorImpl<Entry>::iterator
799 i = Entries.begin(), e = Entries.end(); i != e; ++i)
800 *i->Addr = i->Saved;
801 }
802 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000803}
John McCall4124c492011-10-17 18:40:02 +0000804
805/// checkPlaceholderForOverload - Do any interesting placeholder-like
806/// preprocessing on the given expression.
807///
808/// \param unbridgedCasts a collection to which to add unbridged casts;
809/// without this, they will be immediately diagnosed as errors
810///
811/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000812static bool
813checkPlaceholderForOverload(Sema &S, Expr *&E,
814 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000815 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
816 // We can't handle overloaded expressions here because overload
817 // resolution might reasonably tweak them.
818 if (placeholder->getKind() == BuiltinType::Overload) return false;
819
820 // If the context potentially accepts unbridged ARC casts, strip
821 // the unbridged cast and add it to the collection for later restoration.
822 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
823 unbridgedCasts) {
824 unbridgedCasts->save(S, E);
825 return false;
826 }
827
828 // Go ahead and check everything else.
829 ExprResult result = S.CheckPlaceholderExpr(E);
830 if (result.isInvalid())
831 return true;
832
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000833 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000834 return false;
835 }
836
837 // Nothing to do.
838 return false;
839}
840
841/// checkArgPlaceholdersForOverload - Check a set of call operands for
842/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000843static bool checkArgPlaceholdersForOverload(Sema &S,
844 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000845 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000846 for (unsigned i = 0, e = Args.size(); i != e; ++i)
847 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000848 return true;
849
850 return false;
851}
852
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000854// overload of the declarations in Old. This routine returns false if
855// New and Old cannot be overloaded, e.g., if New has the same
856// signature as some function in Old (C++ 1.3.10) or if the Old
857// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000858// it does return false, MatchedDecl will point to the decl that New
859// cannot be overloaded with. This decl may be a UsingShadowDecl on
860// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000861//
862// Example: Given the following input:
863//
864// void f(int, float); // #1
865// void f(int, int); // #2
866// int f(int, int); // #3
867//
868// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000869// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870//
John McCall3d988d92009-12-02 08:47:38 +0000871// When we process #2, Old contains only the FunctionDecl for #1. By
872// comparing the parameter types, we see that #1 and #2 are overloaded
873// (since they have different signatures), so this routine returns
874// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000875//
John McCall3d988d92009-12-02 08:47:38 +0000876// When we process #3, Old is an overload set containing #1 and #2. We
877// compare the signatures of #3 to #1 (they're overloaded, so we do
878// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
879// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880// signature), IsOverload returns false and MatchedDecl will be set to
881// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000882//
883// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
884// into a class by a using declaration. The rules for whether to hide
885// shadow declarations ignore some properties which otherwise figure
886// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000887Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000888Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
889 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000890 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000891 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000892 NamedDecl *OldD = *I;
893
894 bool OldIsUsingDecl = false;
895 if (isa<UsingShadowDecl>(OldD)) {
896 OldIsUsingDecl = true;
897
898 // We can always introduce two using declarations into the same
899 // context, even if they have identical signatures.
900 if (NewIsUsingDecl) continue;
901
902 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
903 }
904
Richard Smithf091e122015-09-15 01:28:55 +0000905 // A using-declaration does not conflict with another declaration
906 // if one of them is hidden.
907 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
908 continue;
909
John McCalle9cccd82010-06-16 08:42:20 +0000910 // If either declaration was introduced by a using declaration,
911 // we'll need to use slightly different rules for matching.
912 // Essentially, these rules are the normal rules, except that
913 // function templates hide function templates with different
914 // return types or template parameter lists.
915 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000916 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
917 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000918
Alp Tokera2794f92014-01-22 07:29:52 +0000919 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000920 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
921 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
922 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
923 continue;
924 }
925
Alp Tokera2794f92014-01-22 07:29:52 +0000926 if (!isa<FunctionTemplateDecl>(OldD) &&
927 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000928 continue;
929
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 Match = *I;
931 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000932 }
John McCalla8987a2942010-11-10 03:01:53 +0000933 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000934 // We can overload with these, which can show up when doing
935 // redeclaration checks for UsingDecls.
936 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000937 } else if (isa<TagDecl>(OldD)) {
938 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000939 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
940 // Optimistically assume that an unresolved using decl will
941 // overload; if it doesn't, we'll have to diagnose during
942 // template instantiation.
943 } else {
John McCall1f82f242009-11-18 22:49:29 +0000944 // (C++ 13p1):
945 // Only function declarations can be overloaded; object and type
946 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000947 Match = *I;
948 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000949 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 }
John McCall1f82f242009-11-18 22:49:29 +0000951
John McCalldaa3d6b2009-12-09 03:35:25 +0000952 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000953}
954
Richard Smithac974a32013-06-30 09:48:50 +0000955bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
956 bool UseUsingDeclRules) {
957 // C++ [basic.start.main]p2: This function shall not be overloaded.
958 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000959 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000960
David Majnemerc729b0b2013-09-16 22:44:20 +0000961 // MSVCRT user defined entry points cannot be overloaded.
962 if (New->isMSVCRTEntryPoint())
963 return false;
964
John McCall1f82f242009-11-18 22:49:29 +0000965 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
966 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
967
968 // C++ [temp.fct]p2:
969 // A function template can be overloaded with other function templates
970 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000972 return true;
973
974 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000975 QualType OldQType = Context.getCanonicalType(Old->getType());
976 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000977
978 // Compare the signatures (C++ 1.3.10) of the two functions to
979 // determine whether they are overloads. If we find any mismatch
980 // in the signature, they are overloads.
981
982 // If either of these functions is a K&R-style function (no
983 // prototype), then we consider them to have matching signatures.
984 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
985 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
986 return false;
987
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000988 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
989 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000990
991 // The signature of a function includes the types of its
992 // parameters (C++ 1.3.10), which includes the presence or absence
993 // of the ellipsis; see C++ DR 357).
994 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000995 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000996 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000997 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000998 return true;
999
1000 // C++ [temp.over.link]p4:
1001 // The signature of a function template consists of its function
1002 // signature, its return type and its template parameter list. The names
1003 // of the template parameters are significant only for establishing the
1004 // relationship between the template parameters and the rest of the
1005 // signature.
1006 //
1007 // We check the return type and template parameter lists for function
1008 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001009 //
1010 // However, we don't consider either of these when deciding whether
1011 // a member introduced by a shadow declaration is hidden.
1012 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001013 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1014 OldTemplate->getTemplateParameters(),
1015 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001016 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001017 return true;
1018
1019 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001020 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001021 //
1022 // As part of this, also check whether one of the member functions
1023 // is static, in which case they are not overloads (C++
1024 // 13.1p2). While not part of the definition of the signature,
1025 // this check is important to determine whether these functions
1026 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001027 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1028 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001029 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001030 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1031 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1032 if (!UseUsingDeclRules &&
1033 (OldMethod->getRefQualifier() == RQ_None ||
1034 NewMethod->getRefQualifier() == RQ_None)) {
1035 // C++0x [over.load]p2:
1036 // - Member function declarations with the same name and the same
1037 // parameter-type-list as well as member function template
1038 // declarations with the same name, the same parameter-type-list, and
1039 // the same template parameter lists cannot be overloaded if any of
1040 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001041 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001042 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001043 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001044 }
1045 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047
Richard Smith574f4f62013-01-14 05:37:29 +00001048 // We may not have applied the implicit const for a constexpr member
1049 // function yet (because we haven't yet resolved whether this is a static
1050 // or non-static member function). Add it now, on the assumption that this
1051 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001052 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001053 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001054 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001055 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001056 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001057
1058 // We do not allow overloading based off of '__restrict'.
1059 OldQuals &= ~Qualifiers::Restrict;
1060 NewQuals &= ~Qualifiers::Restrict;
1061 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001062 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001065 // enable_if attributes are an order-sensitive part of the signature.
1066 for (specific_attr_iterator<EnableIfAttr>
1067 NewI = New->specific_attr_begin<EnableIfAttr>(),
1068 NewE = New->specific_attr_end<EnableIfAttr>(),
1069 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1070 OldE = Old->specific_attr_end<EnableIfAttr>();
1071 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1072 if (NewI == NewE || OldI == OldE)
1073 return true;
1074 llvm::FoldingSetNodeID NewID, OldID;
1075 NewI->getCond()->Profile(NewID, Context, true);
1076 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001077 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001078 return true;
1079 }
1080
Artem Belevich94a55e82015-09-22 17:22:59 +00001081 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1082 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1083 OldTarget = IdentifyCUDATarget(Old);
1084 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1085 return false;
1086
1087 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1088
1089 // Don't allow mixing of HD with other kinds. This guarantees that
1090 // we have only one viable function with this signature on any
1091 // side of CUDA compilation .
1092 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1093 return false;
1094
1095 // Allow overloading of functions with same signature, but
1096 // different CUDA target attributes.
1097 return NewTarget != OldTarget;
1098 }
1099
John McCall1f82f242009-11-18 22:49:29 +00001100 // The signatures match; this is not an overload.
1101 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102}
1103
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001104/// \brief Checks availability of the function depending on the current
1105/// function context. Inside an unavailable function, unavailability is ignored.
1106///
1107/// \returns true if \arg FD is unavailable and current context is inside
1108/// an available function, false otherwise.
1109bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1110 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1111}
1112
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001113/// \brief Tries a user-defined conversion from From to ToType.
1114///
1115/// Produces an implicit conversion sequence for when a standard conversion
1116/// is not an option. See TryImplicitConversion for more information.
1117static ImplicitConversionSequence
1118TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1119 bool SuppressUserConversions,
1120 bool AllowExplicit,
1121 bool InOverloadResolution,
1122 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001123 bool AllowObjCWritebackConversion,
1124 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001125 ImplicitConversionSequence ICS;
1126
1127 if (SuppressUserConversions) {
1128 // We're not in the case above, so there is no conversion that
1129 // we can perform.
1130 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1131 return ICS;
1132 }
1133
1134 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001135 OverloadCandidateSet Conversions(From->getExprLoc(),
1136 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001137 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1138 Conversions, AllowExplicit,
1139 AllowObjCConversionOnExplicit)) {
1140 case OR_Success:
1141 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001142 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001143 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001144 // C++ [over.ics.user]p4:
1145 // A conversion of an expression of class type to the same class
1146 // type is given Exact Match rank, and a conversion of an
1147 // expression of class type to a base class of that type is
1148 // given Conversion rank, in spite of the fact that a copy
1149 // constructor (i.e., a user-defined conversion function) is
1150 // called for those cases.
1151 if (CXXConstructorDecl *Constructor
1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1153 QualType FromCanon
1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1155 QualType ToCanon
1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1157 if (Constructor->isCopyConstructor() &&
1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1159 // Turn this into a "standard" conversion sequence, so that it
1160 // gets ranked with standard conversion sequences.
1161 ICS.setStandard();
1162 ICS.Standard.setAsIdentityConversion();
1163 ICS.Standard.setFromType(From->getType());
1164 ICS.Standard.setAllToTypes(ToType);
1165 ICS.Standard.CopyConstructor = Constructor;
1166 if (ToCanon != FromCanon)
1167 ICS.Standard.Second = ICK_Derived_To_Base;
1168 }
1169 }
Richard Smith48372b62015-01-27 03:30:40 +00001170 break;
1171
1172 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001173 ICS.setAmbiguous();
1174 ICS.Ambiguous.setFromType(From->getType());
1175 ICS.Ambiguous.setToType(ToType);
1176 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1177 Cand != Conversions.end(); ++Cand)
1178 if (Cand->Viable)
1179 ICS.Ambiguous.addConversion(Cand->Function);
1180 break;
Richard Smith48372b62015-01-27 03:30:40 +00001181
1182 // Fall through.
1183 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001185 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001186 }
1187
1188 return ICS;
1189}
1190
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001191/// TryImplicitConversion - Attempt to perform an implicit conversion
1192/// from the given expression (Expr) to the given type (ToType). This
1193/// function returns an implicit conversion sequence that can be used
1194/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001195///
1196/// void f(float f);
1197/// void g(int i) { f(i); }
1198///
1199/// this routine would produce an implicit conversion sequence to
1200/// describe the initialization of f from i, which will be a standard
1201/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1202/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1203//
1204/// Note that this routine only determines how the conversion can be
1205/// performed; it does not actually perform the conversion. As such,
1206/// it will not produce any diagnostics if no conversion is available,
1207/// but will instead return an implicit conversion sequence of kind
1208/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001209///
1210/// If @p SuppressUserConversions, then user-defined conversions are
1211/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001212/// If @p AllowExplicit, then explicit user-defined conversions are
1213/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001214///
1215/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1216/// writeback conversion, which allows __autoreleasing id* parameters to
1217/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001218static ImplicitConversionSequence
1219TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1220 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001222 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001223 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001224 bool AllowObjCWritebackConversion,
1225 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001227 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001228 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001229 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001230 return ICS;
1231 }
1232
David Blaikiebbafb8a2012-03-11 07:00:24 +00001233 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001234 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001235 return ICS;
1236 }
1237
Douglas Gregor836a7e82010-08-11 02:15:33 +00001238 // C++ [over.ics.user]p4:
1239 // A conversion of an expression of class type to the same class
1240 // type is given Exact Match rank, and a conversion of an
1241 // expression of class type to a base class of that type is
1242 // given Conversion rank, in spite of the fact that a copy/move
1243 // constructor (i.e., a user-defined conversion function) is
1244 // called for those cases.
1245 QualType FromType = From->getType();
1246 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001247 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1248 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001249 ICS.setStandard();
1250 ICS.Standard.setAsIdentityConversion();
1251 ICS.Standard.setFromType(FromType);
1252 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253
Douglas Gregor5ab11652010-04-17 22:01:05 +00001254 // We don't actually check at this point whether there is a valid
1255 // copy/move constructor, since overloading just assumes that it
1256 // exists. When we actually perform initialization, we'll find the
1257 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001258 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259
Douglas Gregor5ab11652010-04-17 22:01:05 +00001260 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001261 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001262 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001263
Douglas Gregor836a7e82010-08-11 02:15:33 +00001264 return ICS;
1265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001267 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1268 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001269 AllowObjCWritebackConversion,
1270 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001271}
1272
John McCall31168b02011-06-15 23:02:42 +00001273ImplicitConversionSequence
1274Sema::TryImplicitConversion(Expr *From, QualType ToType,
1275 bool SuppressUserConversions,
1276 bool AllowExplicit,
1277 bool InOverloadResolution,
1278 bool CStyle,
1279 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001280 return ::TryImplicitConversion(*this, From, ToType,
1281 SuppressUserConversions, AllowExplicit,
1282 InOverloadResolution, CStyle,
1283 AllowObjCWritebackConversion,
1284 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001285}
1286
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001287/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001288/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001289/// converted expression. Flavor is the kind of conversion we're
1290/// performing, used in the error message. If @p AllowExplicit,
1291/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001292ExprResult
1293Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001294 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001295 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001296 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001297}
1298
John Wiegley01296292011-04-08 18:41:53 +00001299ExprResult
1300Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001301 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001302 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001303 if (checkPlaceholderForOverload(*this, From))
1304 return ExprError();
1305
John McCall31168b02011-06-15 23:02:42 +00001306 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1307 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001308 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001309 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001310 if (getLangOpts().ObjC1)
1311 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1312 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001313 ICS = ::TryImplicitConversion(*this, From, ToType,
1314 /*SuppressUserConversions=*/false,
1315 AllowExplicit,
1316 /*InOverloadResolution=*/false,
1317 /*CStyle=*/false,
1318 AllowObjCWritebackConversion,
1319 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001320 return PerformImplicitConversion(From, ToType, ICS, Action);
1321}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322
1323/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001324/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001325bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1326 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001327 if (Context.hasSameUnqualifiedType(FromType, ToType))
1328 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
John McCall991eb4b2010-12-21 00:44:39 +00001330 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1331 // where F adds one of the following at most once:
1332 // - a pointer
1333 // - a member pointer
1334 // - a block pointer
1335 CanQualType CanTo = Context.getCanonicalType(ToType);
1336 CanQualType CanFrom = Context.getCanonicalType(FromType);
1337 Type::TypeClass TyClass = CanTo->getTypeClass();
1338 if (TyClass != CanFrom->getTypeClass()) return false;
1339 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1340 if (TyClass == Type::Pointer) {
1341 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1342 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1343 } else if (TyClass == Type::BlockPointer) {
1344 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1345 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1346 } else if (TyClass == Type::MemberPointer) {
1347 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1348 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1349 } else {
1350 return false;
1351 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001352
John McCall991eb4b2010-12-21 00:44:39 +00001353 TyClass = CanTo->getTypeClass();
1354 if (TyClass != CanFrom->getTypeClass()) return false;
1355 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1356 return false;
1357 }
1358
1359 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1360 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1361 if (!EInfo.getNoReturn()) return false;
1362
1363 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1364 assert(QualType(FromFn, 0).isCanonical());
1365 if (QualType(FromFn, 0) != CanTo) return false;
1366
1367 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001368 return true;
1369}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
Douglas Gregor46188682010-05-18 22:42:18 +00001371/// \brief Determine whether the conversion from FromType to ToType is a valid
1372/// vector conversion.
1373///
1374/// \param ICK Will be set to the vector conversion kind, if this is a vector
1375/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001376static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001378 // We need at least one of these types to be a vector type to have a vector
1379 // conversion.
1380 if (!ToType->isVectorType() && !FromType->isVectorType())
1381 return false;
1382
1383 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001384 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001385 return false;
1386
1387 // There are no conversions between extended vector types, only identity.
1388 if (ToType->isExtVectorType()) {
1389 // There are no conversions between extended vector types other than the
1390 // identity conversion.
1391 if (FromType->isExtVectorType())
1392 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Douglas Gregor46188682010-05-18 22:42:18 +00001394 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001395 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001396 ICK = ICK_Vector_Splat;
1397 return true;
1398 }
1399 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001400
1401 // We can perform the conversion between vector types in the following cases:
1402 // 1)vector types are equivalent AltiVec and GCC vector types
1403 // 2)lax vector conversions are permitted and the vector types are of the
1404 // same size
1405 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001406 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1407 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001408 ICK = ICK_Vector_Conversion;
1409 return true;
1410 }
Douglas Gregor46188682010-05-18 22:42:18 +00001411 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001412
Douglas Gregor46188682010-05-18 22:42:18 +00001413 return false;
1414}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001416static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1417 bool InOverloadResolution,
1418 StandardConversionSequence &SCS,
1419 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001420
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001421/// IsStandardConversion - Determines whether there is a standard
1422/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1423/// expression From to the type ToType. Standard conversion sequences
1424/// only consider non-class types; for conversions that involve class
1425/// types, use TryImplicitConversion. If a conversion exists, SCS will
1426/// contain the standard conversion sequence required to perform this
1427/// conversion and this routine will return true. Otherwise, this
1428/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001429static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1430 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001431 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001432 bool CStyle,
1433 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001434 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001436 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001437 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001438 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001439 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001440 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001441
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001442 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001443 // abort early. When overloading in C, however, we do permit them.
1444 if (S.getLangOpts().CPlusPlus &&
1445 (FromType->isRecordType() || ToType->isRecordType()))
1446 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001447
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448 // The first conversion can be an lvalue-to-rvalue conversion,
1449 // array-to-pointer conversion, or function-to-pointer conversion
1450 // (C++ 4p1).
1451
John McCall5c32be02010-08-24 20:38:10 +00001452 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001453 DeclAccessPair AccessPair;
1454 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001456 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001457 // We were able to resolve the address of the overloaded function,
1458 // so we can convert to the type of that function.
1459 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001460 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001461
1462 // we can sometimes resolve &foo<int> regardless of ToType, so check
1463 // if the type matches (identity) or we are converting to bool
1464 if (!S.Context.hasSameUnqualifiedType(
1465 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1466 QualType resultTy;
1467 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001468 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001469 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1470 // otherwise, only a boolean conversion is standard
1471 if (!ToType->isBooleanType())
1472 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474
Chandler Carruthffce2452011-03-29 08:08:18 +00001475 // Check if the "from" expression is taking the address of an overloaded
1476 // function and recompute the FromType accordingly. Take advantage of the
1477 // fact that non-static member functions *must* have such an address-of
1478 // expression.
1479 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1480 if (Method && !Method->isStatic()) {
1481 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1482 "Non-unary operator on non-static member address");
1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1484 == UO_AddrOf &&
1485 "Non-address-of operator on non-static member address");
1486 const Type *ClassType
1487 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1488 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001489 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1490 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1491 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001492 "Non-address-of operator for overloaded function expression");
1493 FromType = S.Context.getPointerType(FromType);
1494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregor980fb162010-04-29 18:24:40 +00001496 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001497 assert(S.Context.hasSameType(
1498 FromType,
1499 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001500 } else {
1501 return false;
1502 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001503 }
John McCall154a2fd2011-08-30 00:57:29 +00001504 // Lvalue-to-rvalue conversion (C++11 4.1):
1505 // A glvalue (3.10) of a non-function, non-array type T can
1506 // be converted to a prvalue.
1507 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001508 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001509 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001510 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001512
Douglas Gregorc79862f2012-04-12 17:51:55 +00001513 // C11 6.3.2.1p2:
1514 // ... if the lvalue has atomic type, the value has the non-atomic version
1515 // of the type of the lvalue ...
1516 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1517 FromType = Atomic->getValueType();
1518
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 // If T is a non-class type, the type of the rvalue is the
1520 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001521 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1522 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001524 } else if (FromType->isArrayType()) {
1525 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527
1528 // An lvalue or rvalue of type "array of N T" or "array of unknown
1529 // bound of T" can be converted to an rvalue of type "pointer to
1530 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001531 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001532
John McCall5c32be02010-08-24 20:38:10 +00001533 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001534 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001535 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536
1537 // For the purpose of ranking in overload resolution
1538 // (13.3.3.1.1), this conversion is considered an
1539 // array-to-pointer conversion followed by a qualification
1540 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541 SCS.Second = ICK_Identity;
1542 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001543 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001544 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546 }
John McCall086a4642010-11-24 05:12:34 +00001547 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550
1551 // An lvalue of function type T can be converted to an rvalue of
1552 // type "pointer to T." The result is a pointer to the
1553 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001554 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001555 } else {
1556 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001557 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001559 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
1561 // The second conversion can be an integral promotion, floating
1562 // point promotion, integral conversion, floating point conversion,
1563 // floating-integral conversion, pointer conversion,
1564 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001565 // For overloading in C, this can also be a "compatible-type"
1566 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001567 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001568 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001569 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570 // The unqualified versions of the types are the same: there's no
1571 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001572 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001573 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001574 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001575 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001577 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001578 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001579 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001581 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001582 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001583 SCS.Second = ICK_Complex_Promotion;
1584 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001585 } else if (ToType->isBooleanType() &&
1586 (FromType->isArithmeticType() ||
1587 FromType->isAnyPointerType() ||
1588 FromType->isBlockPointerType() ||
1589 FromType->isMemberPointerType() ||
1590 FromType->isNullPtrType())) {
1591 // Boolean conversions (C++ 4.12).
1592 SCS.Second = ICK_Boolean_Conversion;
1593 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001594 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001595 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001596 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001597 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001598 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001599 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001600 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001601 SCS.Second = ICK_Complex_Conversion;
1602 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001603 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1604 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001605 // Complex-real conversions (C99 6.3.1.7)
1606 SCS.Second = ICK_Complex_Real;
1607 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001608 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001609 // Floating point conversions (C++ 4.8).
1610 SCS.Second = ICK_Floating_Conversion;
1611 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001613 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001614 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001615 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001616 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001617 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001619 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001620 SCS.Second = ICK_Block_Pointer_Conversion;
1621 } else if (AllowObjCWritebackConversion &&
1622 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1623 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001624 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1625 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001626 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001627 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001628 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001629 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001631 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001632 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001633 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001634 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001635 SCS.Second = SecondICK;
1636 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001637 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001638 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001639 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001640 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001641 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001642 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001643 // Treat a conversion that strips "noreturn" as an identity conversion.
1644 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001645 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1646 InOverloadResolution,
1647 SCS, CStyle)) {
1648 SCS.Second = ICK_TransparentUnionConversion;
1649 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001650 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1651 CStyle)) {
1652 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001653 // appropriately.
1654 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001655 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001656 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001657 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001658 SCS.Second = ICK_Zero_Event_Conversion;
1659 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660 } else {
1661 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001664 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001666 QualType CanonFrom;
1667 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001669 bool ObjCLifetimeConversion;
1670 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1671 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001673 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001675 CanonFrom = S.Context.getCanonicalType(FromType);
1676 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677 } else {
1678 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001679 SCS.Third = ICK_Identity;
1680
Mike Stump11289f42009-09-09 15:08:12 +00001681 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001682 // [...] Any difference in top-level cv-qualification is
1683 // subsumed by the initialization itself and does not constitute
1684 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001685 CanonFrom = S.Context.getCanonicalType(FromType);
1686 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001688 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001689 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001690 FromType = ToType;
1691 CanonFrom = CanonTo;
1692 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001694 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695
George Burgess IV45461812015-10-11 20:13:20 +00001696 if (CanonFrom == CanonTo)
1697 return true;
1698
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001700 // this is a bad conversion sequence, unless we're resolving an overload in C.
1701 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001702 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703
George Burgess IV45461812015-10-11 20:13:20 +00001704 ExprResult ER = ExprResult{From};
1705 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1706 /*Diagnose=*/false,
1707 /*DiagnoseCFAudited=*/false,
1708 /*ConvertRHS=*/false);
1709 if (Conv != Sema::Compatible)
1710 return false;
1711
1712 SCS.setAllToTypes(ToType);
1713 // We need to set all three because we want this conversion to rank terribly,
1714 // and we don't know what conversions it may overlap with.
1715 SCS.First = ICK_C_Only_Conversion;
1716 SCS.Second = ICK_C_Only_Conversion;
1717 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001718 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001720
1721static bool
1722IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1723 QualType &ToType,
1724 bool InOverloadResolution,
1725 StandardConversionSequence &SCS,
1726 bool CStyle) {
1727
1728 const RecordType *UT = ToType->getAsUnionType();
1729 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1730 return false;
1731 // The field to initialize within the transparent union.
1732 RecordDecl *UD = UT->getDecl();
1733 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001734 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001735 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1736 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001737 ToType = it->getType();
1738 return true;
1739 }
1740 }
1741 return false;
1742}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743
1744/// IsIntegralPromotion - Determines whether the conversion from the
1745/// expression From (whose potentially-adjusted type is FromType) to
1746/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1747/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001748bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001749 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001750 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001751 if (!To) {
1752 return false;
1753 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001754
1755 // An rvalue of type char, signed char, unsigned char, short int, or
1756 // unsigned short int can be converted to an rvalue of type int if
1757 // int can represent all the values of the source type; otherwise,
1758 // the source rvalue can be converted to an rvalue of type unsigned
1759 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001760 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1761 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001762 if (// We can promote any signed, promotable integer type to an int
1763 (FromType->isSignedIntegerType() ||
1764 // We can promote any unsigned integer type whose size is
1765 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001766 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001767 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001769 }
1770
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 return To->getKind() == BuiltinType::UInt;
1772 }
1773
Richard Smithb9c5a602012-09-13 21:18:54 +00001774 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775 // A prvalue of an unscoped enumeration type whose underlying type is not
1776 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1777 // following types that can represent all the values of the enumeration
1778 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1779 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001780 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001782 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783 // with lowest integer conversion rank (4.13) greater than the rank of long
1784 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001785 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001786 // C++11 [conv.prom]p4:
1787 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1788 // can be converted to a prvalue of its underlying type. Moreover, if
1789 // integral promotion can be applied to its underlying type, a prvalue of an
1790 // unscoped enumeration type whose underlying type is fixed can also be
1791 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001792 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1793 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1794 // provided for a scoped enumeration.
1795 if (FromEnumType->getDecl()->isScoped())
1796 return false;
1797
Richard Smithb9c5a602012-09-13 21:18:54 +00001798 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001799 // even if that's not the promoted type. Note that the check for promoting
1800 // the underlying type is based on the type alone, and does not consider
1801 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001802 if (FromEnumType->getDecl()->isFixed()) {
1803 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1804 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001805 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001806 }
1807
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001808 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001810 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001811 return Context.hasSameUnqualifiedType(
1812 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001813 }
John McCall56774992009-12-09 09:09:27 +00001814
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001815 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1817 // to an rvalue a prvalue of the first of the following types that can
1818 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001819 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001821 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001822 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001823 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001825 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 // Determine whether the type we're converting from is signed or
1827 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001828 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831 // The types we'll try to promote to, in the appropriate
1832 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001833 QualType PromoteTypes[6] = {
1834 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001835 Context.LongTy, Context.UnsignedLongTy ,
1836 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001837 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001838 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001839 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1840 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001841 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1843 // We found the type that we can promote to. If this is the
1844 // type we wanted, we have a promotion. Otherwise, no
1845 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001846 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001847 }
1848 }
1849 }
1850
1851 // An rvalue for an integral bit-field (9.6) can be converted to an
1852 // rvalue of type int if int can represent all the values of the
1853 // bit-field; otherwise, it can be converted to unsigned int if
1854 // unsigned int can represent all the values of the bit-field. If
1855 // the bit-field is larger yet, no integral promotion applies to
1856 // it. If the bit-field has an enumerated type, it is treated as any
1857 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001858 // FIXME: We should delay checking of bit-fields until we actually perform the
1859 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001860 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001861 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001862 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001863 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001864 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001865 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001866 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001868 // Are we promoting to an int from a bitfield that fits in an int?
1869 if (BitWidth < ToSize ||
1870 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1871 return To->getKind() == BuiltinType::Int;
1872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001874 // Are we promoting to an unsigned int from an unsigned bitfield
1875 // that fits into an unsigned int?
1876 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1877 return To->getKind() == BuiltinType::UInt;
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001880 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001881 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001883 }
Mike Stump11289f42009-09-09 15:08:12 +00001884
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885 // An rvalue of type bool can be converted to an rvalue of type int,
1886 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001889 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001890
1891 return false;
1892}
1893
1894/// IsFloatingPointPromotion - Determines whether the conversion from
1895/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1896/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001897bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001898 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1899 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001900 /// An rvalue of type float can be converted to an rvalue of type
1901 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001902 if (FromBuiltin->getKind() == BuiltinType::Float &&
1903 ToBuiltin->getKind() == BuiltinType::Double)
1904 return true;
1905
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001906 // C99 6.3.1.5p1:
1907 // When a float is promoted to double or long double, or a
1908 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001910 (FromBuiltin->getKind() == BuiltinType::Float ||
1911 FromBuiltin->getKind() == BuiltinType::Double) &&
1912 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1913 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001914
1915 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001916 if (!getLangOpts().NativeHalfType &&
1917 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001918 ToBuiltin->getKind() == BuiltinType::Float)
1919 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001920 }
1921
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001922 return false;
1923}
1924
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001925/// \brief Determine if a conversion is a complex promotion.
1926///
1927/// A complex promotion is defined as a complex -> complex conversion
1928/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001929/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001930bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001931 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001932 if (!FromComplex)
1933 return false;
1934
John McCall9dd450b2009-09-21 23:43:11 +00001935 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001936 if (!ToComplex)
1937 return false;
1938
1939 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001940 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001941 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001942 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001943}
1944
Douglas Gregor237f96c2008-11-26 23:31:11 +00001945/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1946/// the pointer type FromPtr to a pointer to type ToPointee, with the
1947/// same type qualifiers as FromPtr has on its pointee type. ToType,
1948/// if non-empty, will be a pointer to ToType that may or may not have
1949/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001950///
Mike Stump11289f42009-09-09 15:08:12 +00001951static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001952BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001953 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001954 ASTContext &Context,
1955 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001956 assert((FromPtr->getTypeClass() == Type::Pointer ||
1957 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1958 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
John McCall31168b02011-06-15 23:02:42 +00001960 /// Conversions to 'id' subsume cv-qualifier conversions.
1961 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001962 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
1964 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001965 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001966 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001967 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCall31168b02011-06-15 23:02:42 +00001969 if (StripObjCLifetime)
1970 Quals.removeObjCLifetime();
1971
Mike Stump11289f42009-09-09 15:08:12 +00001972 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001973 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001974 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001975 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001976 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001977
1978 // Build a pointer to ToPointee. It has the right qualifiers
1979 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001980 if (isa<ObjCObjectPointerType>(ToType))
1981 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001982 return Context.getPointerType(ToPointee);
1983 }
1984
1985 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001986 QualType QualifiedCanonToPointee
1987 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001989 if (isa<ObjCObjectPointerType>(ToType))
1990 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1991 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001992}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Mike Stump11289f42009-09-09 15:08:12 +00001994static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001995 bool InOverloadResolution,
1996 ASTContext &Context) {
1997 // Handle value-dependent integral null pointer constants correctly.
1998 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1999 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002000 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002001 return !InOverloadResolution;
2002
Douglas Gregor56751b52009-09-25 04:25:58 +00002003 return Expr->isNullPointerConstant(Context,
2004 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2005 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002006}
Mike Stump11289f42009-09-09 15:08:12 +00002007
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008/// IsPointerConversion - Determines whether the conversion of the
2009/// expression From, which has the (possibly adjusted) type FromType,
2010/// can be converted to the type ToType via a pointer conversion (C++
2011/// 4.10). If so, returns true and places the converted type (that
2012/// might differ from ToType in its cv-qualifiers at some level) into
2013/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002014///
Douglas Gregora29dc052008-11-27 01:19:21 +00002015/// This routine also supports conversions to and from block pointers
2016/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2017/// pointers to interfaces. FIXME: Once we've determined the
2018/// appropriate overloading rules for Objective-C, we may want to
2019/// split the Objective-C checks into a different routine; however,
2020/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002021/// conversions, so for now they live here. IncompatibleObjC will be
2022/// set if the conversion is an allowed Objective-C conversion that
2023/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002025 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002026 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002027 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002028 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002029 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2030 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002031 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002032
Mike Stump11289f42009-09-09 15:08:12 +00002033 // Conversion from a null pointer constant to any Objective-C pointer type.
2034 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039
Douglas Gregor231d1c62008-11-27 00:15:41 +00002040 // Blocks: Block pointers can be converted to void*.
2041 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002042 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
2046 // Blocks: A null pointer constant can be converted to a block
2047 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002048 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002050 ConvertedType = ToType;
2051 return true;
2052 }
2053
Sebastian Redl576fd422009-05-10 18:38:11 +00002054 // If the left-hand-side is nullptr_t, the right side can be a null
2055 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002056 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002057 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002058 ConvertedType = ToType;
2059 return true;
2060 }
2061
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002062 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002063 if (!ToTypePtr)
2064 return false;
2065
2066 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002067 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002068 ConvertedType = ToType;
2069 return true;
2070 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002071
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002073 // , including objective-c pointers.
2074 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002075 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002076 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002077 ConvertedType = BuildSimilarlyQualifiedPointerType(
2078 FromType->getAs<ObjCObjectPointerType>(),
2079 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002080 ToType, Context);
2081 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002082 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002083 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002084 if (!FromTypePtr)
2085 return false;
2086
2087 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002088
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002090 // pointer conversion, so don't do all of the work below.
2091 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2092 return false;
2093
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002094 // An rvalue of type "pointer to cv T," where T is an object type,
2095 // can be converted to an rvalue of type "pointer to cv void" (C++
2096 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002097 if (FromPointeeType->isIncompleteOrObjectType() &&
2098 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002100 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002101 ToType, Context,
2102 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002103 return true;
2104 }
2105
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002106 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002107 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002108 ToPointeeType->isVoidType()) {
2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2110 ToPointeeType,
2111 ToType, Context);
2112 return true;
2113 }
2114
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002115 // When we're overloading in C, we allow a special kind of pointer
2116 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002117 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002118 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002120 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002121 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002122 return true;
2123 }
2124
Douglas Gregor5c407d92008-10-23 00:40:37 +00002125 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002126 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002127 // An rvalue of type "pointer to cv D," where D is a class type,
2128 // can be converted to an rvalue of type "pointer to cv B," where
2129 // B is a base class (clause 10) of D. If B is an inaccessible
2130 // (clause 11) or ambiguous (10.2) base class of D, a program that
2131 // necessitates this conversion is ill-formed. The result of the
2132 // conversion is a pointer to the base class sub-object of the
2133 // derived class object. The null pointer value is converted to
2134 // the null pointer value of the destination type.
2135 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002136 // Note that we do not check for ambiguity or inaccessibility
2137 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002138 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002139 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002140 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002141 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002142 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002143 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002144 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 ToType, Context);
2146 return true;
2147 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002148
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002149 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2150 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2152 ToPointeeType,
2153 ToType, Context);
2154 return true;
2155 }
2156
Douglas Gregora119f102008-12-19 19:13:09 +00002157 return false;
2158}
Douglas Gregoraec25842011-04-26 23:16:46 +00002159
2160/// \brief Adopt the given qualifiers for the given type.
2161static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2162 Qualifiers TQs = T.getQualifiers();
2163
2164 // Check whether qualifiers already match.
2165 if (TQs == Qs)
2166 return T;
2167
2168 if (Qs.compatiblyIncludes(TQs))
2169 return Context.getQualifiedType(T, Qs);
2170
2171 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2172}
Douglas Gregora119f102008-12-19 19:13:09 +00002173
2174/// isObjCPointerConversion - Determines whether this is an
2175/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2176/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002177bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002178 QualType& ConvertedType,
2179 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002180 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002181 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
Douglas Gregoraec25842011-04-26 23:16:46 +00002183 // The set of qualifiers on the type we're converting from.
2184 Qualifiers FromQualifiers = FromType.getQualifiers();
2185
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002187 const ObjCObjectPointerType* ToObjCPtr =
2188 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002189 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002190 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002191
Steve Naroff7cae42b2009-07-10 23:34:53 +00002192 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002193 // If the pointee types are the same (ignoring qualifications),
2194 // then this is not a pointer conversion.
2195 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2196 FromObjCPtr->getPointeeType()))
2197 return false;
2198
Douglas Gregorab209d82015-07-07 03:58:42 +00002199 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002203 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2205 FromObjCPtr->getPointeeType()))
2206 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002208 ToObjCPtr->getPointeeType(),
2209 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002211 return true;
2212 }
2213
2214 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2215 // Okay: this is some kind of implicit downcast of Objective-C
2216 // interfaces, which is permitted. However, we're going to
2217 // complain about it.
2218 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002220 ToObjCPtr->getPointeeType(),
2221 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002223 return true;
2224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002226 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002227 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002229 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002230 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002231 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002232 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002233 // to a block pointer type.
2234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002236 return true;
2237 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002238 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002243 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002245 return true;
2246 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002247 else
Douglas Gregora119f102008-12-19 19:13:09 +00002248 return false;
2249
Douglas Gregor033f56d2008-12-23 00:53:59 +00002250 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002252 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002253 else if (const BlockPointerType *FromBlockPtr =
2254 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002255 FromPointeeType = FromBlockPtr->getPointeeType();
2256 else
Douglas Gregora119f102008-12-19 19:13:09 +00002257 return false;
2258
Douglas Gregora119f102008-12-19 19:13:09 +00002259 // If we have pointers to pointers, recursively check whether this
2260 // is an Objective-C conversion.
2261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2263 IncompatibleObjC)) {
2264 // We always complain about this conversion.
2265 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002266 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002268 return true;
2269 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002270 // Allow conversion of pointee being objective-c pointer to another one;
2271 // as in I* to id.
2272 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2273 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2274 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2275 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002276
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002277 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002278 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002279 return true;
2280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281
Douglas Gregor033f56d2008-12-23 00:53:59 +00002282 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002283 // differences in the argument and result types are in Objective-C
2284 // pointer conversions. If so, we permit the conversion (but
2285 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002286 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002287 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002288 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002289 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002290 if (FromFunctionType && ToFunctionType) {
2291 // If the function types are exactly the same, this isn't an
2292 // Objective-C pointer conversion.
2293 if (Context.getCanonicalType(FromPointeeType)
2294 == Context.getCanonicalType(ToPointeeType))
2295 return false;
2296
2297 // Perform the quick checks that will tell us whether these
2298 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2301 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2302 return false;
2303
2304 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002305 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2306 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002307 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002308 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2309 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002310 ConvertedType, IncompatibleObjC)) {
2311 // Okay, we have an Objective-C pointer conversion.
2312 HasObjCConversion = true;
2313 } else {
2314 // Function types are too different. Abort.
2315 return false;
2316 }
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregora119f102008-12-19 19:13:09 +00002318 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002320 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002321 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2322 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002323 if (Context.getCanonicalType(FromArgType)
2324 == Context.getCanonicalType(ToArgType)) {
2325 // Okay, the types match exactly. Nothing to do.
2326 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2327 ConvertedType, IncompatibleObjC)) {
2328 // Okay, we have an Objective-C pointer conversion.
2329 HasObjCConversion = true;
2330 } else {
2331 // Argument types are too different. Abort.
2332 return false;
2333 }
2334 }
2335
2336 if (HasObjCConversion) {
2337 // We had an Objective-C conversion. Allow this pointer
2338 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002340 IncompatibleObjC = true;
2341 return true;
2342 }
2343 }
2344
Sebastian Redl72b597d2009-01-25 19:43:20 +00002345 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002346}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
John McCall31168b02011-06-15 23:02:42 +00002348/// \brief Determine whether this is an Objective-C writeback conversion,
2349/// used for parameter passing when performing automatic reference counting.
2350///
2351/// \param FromType The type we're converting form.
2352///
2353/// \param ToType The type we're converting to.
2354///
2355/// \param ConvertedType The type that will be produced after applying
2356/// this conversion.
2357bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2358 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002359 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002360 Context.hasSameUnqualifiedType(FromType, ToType))
2361 return false;
2362
2363 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2364 QualType ToPointee;
2365 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2366 ToPointee = ToPointer->getPointeeType();
2367 else
2368 return false;
2369
2370 Qualifiers ToQuals = ToPointee.getQualifiers();
2371 if (!ToPointee->isObjCLifetimeType() ||
2372 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002373 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002374 return false;
2375
2376 // Argument must be a pointer to __strong to __weak.
2377 QualType FromPointee;
2378 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2379 FromPointee = FromPointer->getPointeeType();
2380 else
2381 return false;
2382
2383 Qualifiers FromQuals = FromPointee.getQualifiers();
2384 if (!FromPointee->isObjCLifetimeType() ||
2385 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2386 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2387 return false;
2388
2389 // Make sure that we have compatible qualifiers.
2390 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2391 if (!ToQuals.compatiblyIncludes(FromQuals))
2392 return false;
2393
2394 // Remove qualifiers from the pointee type we're converting from; they
2395 // aren't used in the compatibility check belong, and we'll be adding back
2396 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2397 FromPointee = FromPointee.getUnqualifiedType();
2398
2399 // The unqualified form of the pointee types must be compatible.
2400 ToPointee = ToPointee.getUnqualifiedType();
2401 bool IncompatibleObjC;
2402 if (Context.typesAreCompatible(FromPointee, ToPointee))
2403 FromPointee = ToPointee;
2404 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2405 IncompatibleObjC))
2406 return false;
2407
2408 /// \brief Construct the type we're converting to, which is a pointer to
2409 /// __autoreleasing pointee.
2410 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2411 ConvertedType = Context.getPointerType(FromPointee);
2412 return true;
2413}
2414
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002415bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2416 QualType& ConvertedType) {
2417 QualType ToPointeeType;
2418 if (const BlockPointerType *ToBlockPtr =
2419 ToType->getAs<BlockPointerType>())
2420 ToPointeeType = ToBlockPtr->getPointeeType();
2421 else
2422 return false;
2423
2424 QualType FromPointeeType;
2425 if (const BlockPointerType *FromBlockPtr =
2426 FromType->getAs<BlockPointerType>())
2427 FromPointeeType = FromBlockPtr->getPointeeType();
2428 else
2429 return false;
2430 // We have pointer to blocks, check whether the only
2431 // differences in the argument and result types are in Objective-C
2432 // pointer conversions. If so, we permit the conversion.
2433
2434 const FunctionProtoType *FromFunctionType
2435 = FromPointeeType->getAs<FunctionProtoType>();
2436 const FunctionProtoType *ToFunctionType
2437 = ToPointeeType->getAs<FunctionProtoType>();
2438
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 if (!FromFunctionType || !ToFunctionType)
2440 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002441
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002442 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002443 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002444
2445 // Perform the quick checks that will tell us whether these
2446 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002447 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002448 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2449 return false;
2450
2451 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2452 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2453 if (FromEInfo != ToEInfo)
2454 return false;
2455
2456 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002457 if (Context.hasSameType(FromFunctionType->getReturnType(),
2458 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002459 // Okay, the types match exactly. Nothing to do.
2460 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002461 QualType RHS = FromFunctionType->getReturnType();
2462 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002464 !RHS.hasQualifiers() && LHS.hasQualifiers())
2465 LHS = LHS.getUnqualifiedType();
2466
2467 if (Context.hasSameType(RHS,LHS)) {
2468 // OK exact match.
2469 } else if (isObjCPointerConversion(RHS, LHS,
2470 ConvertedType, IncompatibleObjC)) {
2471 if (IncompatibleObjC)
2472 return false;
2473 // Okay, we have an Objective-C pointer conversion.
2474 }
2475 else
2476 return false;
2477 }
2478
2479 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002480 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002481 ArgIdx != NumArgs; ++ArgIdx) {
2482 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002485 if (Context.hasSameType(FromArgType, ToArgType)) {
2486 // Okay, the types match exactly. Nothing to do.
2487 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2488 ConvertedType, IncompatibleObjC)) {
2489 if (IncompatibleObjC)
2490 return false;
2491 // Okay, we have an Objective-C pointer conversion.
2492 } else
2493 // Argument types are too different. Abort.
2494 return false;
2495 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002496 if (LangOpts.ObjCAutoRefCount &&
2497 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2498 ToFunctionType))
2499 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002500
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002501 ConvertedType = ToType;
2502 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002503}
2504
Richard Trieucaff2472011-11-23 22:32:32 +00002505enum {
2506 ft_default,
2507 ft_different_class,
2508 ft_parameter_arity,
2509 ft_parameter_mismatch,
2510 ft_return_type,
George Burgess IV5f21c712015-10-12 19:57:04 +00002511 ft_qualifer_mismatch,
2512 ft_addr_enable_if
Richard Trieucaff2472011-11-23 22:32:32 +00002513};
2514
2515/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2516/// function types. Catches different number of parameter, mismatch in
2517/// parameter types, and different return types.
2518void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2519 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002520 // If either type is not valid, include no extra info.
2521 if (FromType.isNull() || ToType.isNull()) {
2522 PDiag << ft_default;
2523 return;
2524 }
2525
Richard Trieucaff2472011-11-23 22:32:32 +00002526 // Get the function type from the pointers.
2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2529 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002530 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2532 << QualType(FromMember->getClass(), 0);
2533 return;
2534 }
2535 FromType = FromMember->getPointeeType();
2536 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002537 }
2538
Richard Trieu96ed5b62011-12-13 23:19:45 +00002539 if (FromType->isPointerType())
2540 FromType = FromType->getPointeeType();
2541 if (ToType->isPointerType())
2542 ToType = ToType->getPointeeType();
2543
2544 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002545 FromType = FromType.getNonReferenceType();
2546 ToType = ToType.getNonReferenceType();
2547
Richard Trieucaff2472011-11-23 22:32:32 +00002548 // Don't print extra info for non-specialized template functions.
2549 if (FromType->isInstantiationDependentType() &&
2550 !FromType->getAs<TemplateSpecializationType>()) {
2551 PDiag << ft_default;
2552 return;
2553 }
2554
Richard Trieu96ed5b62011-12-13 23:19:45 +00002555 // No extra info for same types.
2556 if (Context.hasSameType(FromType, ToType)) {
2557 PDiag << ft_default;
2558 return;
2559 }
2560
Richard Trieucaff2472011-11-23 22:32:32 +00002561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2562 *ToFunction = ToType->getAs<FunctionProtoType>();
2563
2564 // Both types need to be function types.
2565 if (!FromFunction || !ToFunction) {
2566 PDiag << ft_default;
2567 return;
2568 }
2569
Alp Toker9cacbab2014-01-20 20:26:09 +00002570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2571 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2572 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002573 return;
2574 }
2575
2576 // Handle different parameter types.
2577 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002579 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002580 << ToFunction->getParamType(ArgPos)
2581 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002582 return;
2583 }
2584
2585 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002586 if (!Context.hasSameType(FromFunction->getReturnType(),
2587 ToFunction->getReturnType())) {
2588 PDiag << ft_return_type << ToFunction->getReturnType()
2589 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002590 return;
2591 }
2592
2593 unsigned FromQuals = FromFunction->getTypeQuals(),
2594 ToQuals = ToFunction->getTypeQuals();
2595 if (FromQuals != ToQuals) {
2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2597 return;
2598 }
2599
2600 // Unable to find a difference, so add no extra info.
2601 PDiag << ft_default;
2602}
2603
Alp Toker9cacbab2014-01-20 20:26:09 +00002604/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002605/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002606/// they have same number of arguments. If the parameters are different,
2607/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002608bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2609 const FunctionProtoType *NewType,
2610 unsigned *ArgPos) {
2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2612 N = NewType->param_type_begin(),
2613 E = OldType->param_type_end();
2614 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002615 if (!Context.hasSameType(O->getUnqualifiedType(),
2616 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002617 if (ArgPos)
2618 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002619 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002620 }
2621 }
2622 return true;
2623}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002624
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625/// CheckPointerConversion - Check the pointer conversion from the
2626/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002627/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002628/// conversions for which IsPointerConversion has already returned
2629/// true. It returns true and produces a diagnostic if there was an
2630/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002631bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002632 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002633 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002634 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002635 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002637
John McCall8cb679e2010-11-15 09:13:47 +00002638 Kind = CK_BitCast;
2639
David Blaikie1c7c8f72012-08-08 17:33:31 +00002640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002642 Expr::NPCK_ZeroExpression) {
2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2644 DiagRuntimeBehavior(From->getExprLoc(), From,
2645 PDiag(diag::warn_impcast_bool_to_null_pointer)
2646 << ToType << From->getSourceRange());
2647 else if (!isUnevaluatedContext())
2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2649 << ToType << From->getSourceRange();
2650 }
John McCall9320b872011-09-09 05:25:32 +00002651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002653 QualType FromPointeeType = FromPtrType->getPointeeType(),
2654 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002655
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002658 // We must have a derived-to-base conversion. Check an
2659 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2661 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002662 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002663 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002664 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002666 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002667 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002668 }
2669 }
John McCall9320b872011-09-09 05:25:32 +00002670 } else if (const ObjCObjectPointerType *ToPtrType =
2671 ToType->getAs<ObjCObjectPointerType>()) {
2672 if (const ObjCObjectPointerType *FromPtrType =
2673 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002674 // Objective-C++ conversions are always okay.
2675 // FIXME: We should have a different class of conversions for the
2676 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002677 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002678 return false;
John McCall9320b872011-09-09 05:25:32 +00002679 } else if (FromType->isBlockPointerType()) {
2680 Kind = CK_BlockPointerToObjCPointerCast;
2681 } else {
2682 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002683 }
John McCall9320b872011-09-09 05:25:32 +00002684 } else if (ToType->isBlockPointerType()) {
2685 if (!FromType->isBlockPointerType())
2686 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002687 }
John McCall8cb679e2010-11-15 09:13:47 +00002688
2689 // We shouldn't fall into this case unless it's valid for other
2690 // reasons.
2691 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2692 Kind = CK_NullToPointer;
2693
Douglas Gregor39c16d42008-10-24 04:54:22 +00002694 return false;
2695}
2696
Sebastian Redl72b597d2009-01-25 19:43:20 +00002697/// IsMemberPointerConversion - Determines whether the conversion of the
2698/// expression From, which has the (possibly adjusted) type FromType, can be
2699/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2700/// If so, returns true and places the converted type (that might differ from
2701/// ToType in its cv-qualifiers at some level) into ConvertedType.
2702bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002704 bool InOverloadResolution,
2705 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002706 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002707 if (!ToTypePtr)
2708 return false;
2709
2710 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 if (From->isNullPointerConstant(Context,
2712 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2713 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714 ConvertedType = ToType;
2715 return true;
2716 }
2717
2718 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002719 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720 if (!FromTypePtr)
2721 return false;
2722
2723 // A pointer to member of B can be converted to a pointer to member of D,
2724 // where D is derived from B (C++ 4.11p2).
2725 QualType FromClass(FromTypePtr->getClass(), 0);
2726 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002728 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002729 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002730 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002731 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2732 ToClass.getTypePtr());
2733 return true;
2734 }
2735
2736 return false;
2737}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739/// CheckMemberPointerConversion - Check the member pointer conversion from the
2740/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002741/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002742/// for which IsMemberPointerConversion has already returned true. It returns
2743/// true and produces a diagnostic if there was an error, or returns false
2744/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002745bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002746 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002747 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002748 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002750 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002751 if (!FromPtrType) {
2752 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002754 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002755 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002756 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002757 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002758 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002759
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002760 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002761 assert(ToPtrType && "No member pointer cast has a target type "
2762 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002763
Sebastian Redled8f2002009-01-28 18:33:18 +00002764 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2765 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002766
Sebastian Redled8f2002009-01-28 18:33:18 +00002767 // FIXME: What about dependent types?
2768 assert(FromClass->isRecordType() && "Pointer into non-class.");
2769 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002772 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002773 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2774 assert(DerivationOkay &&
2775 "Should not have been called if derivation isn't OK.");
2776 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002777
Sebastian Redled8f2002009-01-28 18:33:18 +00002778 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2779 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002780 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2781 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2782 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2783 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002784 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002785
Douglas Gregor89ee6822009-02-28 01:32:25 +00002786 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002787 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2788 << FromClass << ToClass << QualType(VBase, 0)
2789 << From->getSourceRange();
2790 return true;
2791 }
2792
John McCall5b0829a2010-02-10 09:31:12 +00002793 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002794 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2795 Paths.front(),
2796 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002797
Anders Carlssond7923c62009-08-22 23:33:40 +00002798 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002799 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002800 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002801 return false;
2802}
2803
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002804/// Determine whether the lifetime conversion between the two given
2805/// qualifiers sets is nontrivial.
2806static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2807 Qualifiers ToQuals) {
2808 // Converting anything to const __unsafe_unretained is trivial.
2809 if (ToQuals.hasConst() &&
2810 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2811 return false;
2812
2813 return true;
2814}
2815
Douglas Gregor9a657932008-10-21 23:43:52 +00002816/// IsQualificationConversion - Determines whether the conversion from
2817/// an rvalue of type FromType to ToType is a qualification conversion
2818/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002819///
2820/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2821/// when the qualification conversion involves a change in the Objective-C
2822/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002823bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002825 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002826 FromType = Context.getCanonicalType(FromType);
2827 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002828 ObjCLifetimeConversion = false;
2829
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 // If FromType and ToType are the same type, this is not a
2831 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002832 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002834
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // (C++ 4.4p4):
2836 // A conversion can add cv-qualifiers at levels other than the first
2837 // in multi-level pointers, subject to the following rules: [...]
2838 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002839 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002840 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 // Within each iteration of the loop, we check the qualifiers to
2842 // determine if this still looks like a qualification
2843 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002844 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002845 // until there are no more pointers or pointers-to-members left to
2846 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002847 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002848
Douglas Gregor90609aa2011-04-25 18:40:17 +00002849 Qualifiers FromQuals = FromType.getQualifiers();
2850 Qualifiers ToQuals = ToType.getQualifiers();
2851
John McCall31168b02011-06-15 23:02:42 +00002852 // Objective-C ARC:
2853 // Check Objective-C lifetime conversions.
2854 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2855 UnwrappedAnyPointer) {
2856 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002857 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2858 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002859 FromQuals.removeObjCLifetime();
2860 ToQuals.removeObjCLifetime();
2861 } else {
2862 // Qualification conversions cannot cast between different
2863 // Objective-C lifetime qualifiers.
2864 return false;
2865 }
2866 }
2867
Douglas Gregorf30053d2011-05-08 06:09:53 +00002868 // Allow addition/removal of GC attributes but not changing GC attributes.
2869 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2870 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2871 FromQuals.removeObjCGCAttr();
2872 ToQuals.removeObjCGCAttr();
2873 }
2874
Douglas Gregor9a657932008-10-21 23:43:52 +00002875 // -- for every j > 0, if const is in cv 1,j then const is in cv
2876 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002877 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002878 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002879
Douglas Gregor9a657932008-10-21 23:43:52 +00002880 // -- if the cv 1,j and cv 2,j are different, then const is in
2881 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002882 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002883 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002884 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor9a657932008-10-21 23:43:52 +00002886 // Keep track of whether all prior cv-qualifiers in the "to" type
2887 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002888 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002889 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002890 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002891
2892 // We are left with FromType and ToType being the pointee types
2893 // after unwrapping the original FromType and ToType the same number
2894 // of types. If we unwrapped any pointers, and if FromType and
2895 // ToType have the same unqualified type (since we checked
2896 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002897 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002898}
2899
Douglas Gregorc79862f2012-04-12 17:51:55 +00002900/// \brief - Determine whether this is a conversion from a scalar type to an
2901/// atomic type.
2902///
2903/// If successful, updates \c SCS's second and third steps in the conversion
2904/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002905static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2906 bool InOverloadResolution,
2907 StandardConversionSequence &SCS,
2908 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002909 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2910 if (!ToAtomic)
2911 return false;
2912
2913 StandardConversionSequence InnerSCS;
2914 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2915 InOverloadResolution, InnerSCS,
2916 CStyle, /*AllowObjCWritebackConversion=*/false))
2917 return false;
2918
2919 SCS.Second = InnerSCS.Second;
2920 SCS.setToType(1, InnerSCS.getToType(1));
2921 SCS.Third = InnerSCS.Third;
2922 SCS.QualificationIncludesObjCLifetime
2923 = InnerSCS.QualificationIncludesObjCLifetime;
2924 SCS.setToType(2, InnerSCS.getToType(2));
2925 return true;
2926}
2927
Sebastian Redle5417162012-03-27 18:33:03 +00002928static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2929 CXXConstructorDecl *Constructor,
2930 QualType Type) {
2931 const FunctionProtoType *CtorType =
2932 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002933 if (CtorType->getNumParams() > 0) {
2934 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002935 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2936 return true;
2937 }
2938 return false;
2939}
2940
Sebastian Redl82ace982012-02-11 23:51:08 +00002941static OverloadingResult
2942IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2943 CXXRecordDecl *To,
2944 UserDefinedConversionSequence &User,
2945 OverloadCandidateSet &CandidateSet,
2946 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002947 DeclContext::lookup_result R = S.LookupConstructors(To);
2948 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002949 Con != ConEnd; ++Con) {
2950 NamedDecl *D = *Con;
2951 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2952
2953 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002955 FunctionTemplateDecl *ConstructorTmpl
2956 = dyn_cast<FunctionTemplateDecl>(D);
2957 if (ConstructorTmpl)
2958 Constructor
2959 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2960 else
2961 Constructor = cast<CXXConstructorDecl>(D);
2962
2963 bool Usable = !Constructor->isInvalidDecl() &&
2964 S.isInitListConstructor(Constructor) &&
2965 (AllowExplicit || !Constructor->isExplicit());
2966 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002967 // If the first argument is (a reference to) the target type,
2968 // suppress conversions.
2969 bool SuppressUserConversions =
2970 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002971 if (ConstructorTmpl)
2972 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002973 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002974 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002975 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002976 else
2977 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002978 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002979 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002980 }
2981 }
2982
2983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984
2985 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002986 switch (auto Result =
2987 CandidateSet.BestViableFunction(S, From->getLocStart(),
2988 Best, true)) {
2989 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00002990 case OR_Success: {
2991 // Record the standard conversion we used and the conversion function.
2992 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002993 QualType ThisType = Constructor->getThisType(S.Context);
2994 // Initializer lists don't have conversions as such.
2995 User.Before.setAsIdentityConversion();
2996 User.HadMultipleCandidates = HadMultipleCandidates;
2997 User.ConversionFunction = Constructor;
2998 User.FoundConversionFunction = Best->FoundDecl;
2999 User.After.setAsIdentityConversion();
3000 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3001 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003002 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003003 }
3004
3005 case OR_No_Viable_Function:
3006 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003007 case OR_Ambiguous:
3008 return OR_Ambiguous;
3009 }
3010
3011 llvm_unreachable("Invalid OverloadResult!");
3012}
3013
Douglas Gregor576e98c2009-01-30 23:27:23 +00003014/// Determines whether there is a user-defined conversion sequence
3015/// (C++ [over.ics.user]) that converts expression From to the type
3016/// ToType. If such a conversion exists, User will contain the
3017/// user-defined conversion sequence that performs such a conversion
3018/// and this routine will return true. Otherwise, this routine returns
3019/// false and User is unspecified.
3020///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003021/// \param AllowExplicit true if the conversion should consider C++0x
3022/// "explicit" conversion functions as well as non-explicit conversion
3023/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003024///
3025/// \param AllowObjCConversionOnExplicit true if the conversion should
3026/// allow an extra Objective-C pointer conversion on uses of explicit
3027/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003028static OverloadingResult
3029IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003030 UserDefinedConversionSequence &User,
3031 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003032 bool AllowExplicit,
3033 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003034 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003035
Douglas Gregor5ab11652010-04-17 22:01:05 +00003036 // Whether we will only visit constructors.
3037 bool ConstructorsOnly = false;
3038
3039 // If the type we are conversion to is a class type, enumerate its
3040 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003041 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003042 // C++ [over.match.ctor]p1:
3043 // When objects of class type are direct-initialized (8.5), or
3044 // copy-initialized from an expression of the same or a
3045 // derived class type (8.5), overload resolution selects the
3046 // constructor. [...] For copy-initialization, the candidate
3047 // functions are all the converting constructors (12.3.1) of
3048 // that class. The argument list is the expression-list within
3049 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003050 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003051 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003052 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003053 ConstructorsOnly = true;
3054
Benjamin Kramer90633e32012-11-23 17:04:52 +00003055 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003056 // RequireCompleteType may have returned true due to some invalid decl
3057 // during template instantiation, but ToType may be complete enough now
3058 // to try to recover.
3059 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003060 // We're not going to find any constructors.
3061 } else if (CXXRecordDecl *ToRecordDecl
3062 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003063
3064 Expr **Args = &From;
3065 unsigned NumArgs = 1;
3066 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003067 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003068 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003069 OverloadingResult Result = IsInitializerListConstructorConversion(
3070 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3071 if (Result != OR_No_Viable_Function)
3072 return Result;
3073 // Never mind.
3074 CandidateSet.clear();
3075
3076 // If we're list-initializing, we pass the individual elements as
3077 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003078 Args = InitList->getInits();
3079 NumArgs = InitList->getNumInits();
3080 ListInitializing = true;
3081 }
3082
David Blaikieff7d47a2012-12-19 00:45:41 +00003083 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3084 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003085 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003086 NamedDecl *D = *Con;
3087 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3088
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003089 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003090 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003091 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003092 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003093 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003094 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003095 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3096 else
John McCalla0296f72010-03-19 07:35:19 +00003097 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003099 bool Usable = !Constructor->isInvalidDecl();
3100 if (ListInitializing)
3101 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3102 else
3103 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3104 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003105 bool SuppressUserConversions = !ConstructorsOnly;
3106 if (SuppressUserConversions && ListInitializing) {
3107 SuppressUserConversions = false;
3108 if (NumArgs == 1) {
3109 // If the first argument is (a reference to) the target type,
3110 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003111 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3112 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003113 }
3114 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003115 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003116 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003117 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003118 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003119 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003120 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003121 // Allow one user-defined conversion when user specifies a
3122 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003123 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003124 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003125 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003126 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003127 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003128 }
3129 }
3130
Douglas Gregor5ab11652010-04-17 22:01:05 +00003131 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003132 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003133 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003134 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003135 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003136 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003137 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003138 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3139 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003140 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3141 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003142 DeclAccessPair FoundDecl = I.getPair();
3143 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003144 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3145 if (isa<UsingShadowDecl>(D))
3146 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3147
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003148 CXXConversionDecl *Conv;
3149 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003150 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3151 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003152 else
John McCallda4458e2010-03-31 01:36:47 +00003153 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003154
3155 if (AllowExplicit || !Conv->isExplicit()) {
3156 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003157 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3158 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003159 CandidateSet,
3160 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003161 else
John McCall5c32be02010-08-24 20:38:10 +00003162 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003163 From, ToType, CandidateSet,
3164 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003165 }
3166 }
3167 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003168 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003169
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003170 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3171
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003172 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003173 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3174 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003175 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003176 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003177 // Record the standard conversion we used and the conversion function.
3178 if (CXXConstructorDecl *Constructor
3179 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3180 // C++ [over.ics.user]p1:
3181 // If the user-defined conversion is specified by a
3182 // constructor (12.3.1), the initial standard conversion
3183 // sequence converts the source type to the type required by
3184 // the argument of the constructor.
3185 //
3186 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003187 if (isa<InitListExpr>(From)) {
3188 // Initializer lists don't have conversions as such.
3189 User.Before.setAsIdentityConversion();
3190 } else {
3191 if (Best->Conversions[0].isEllipsis())
3192 User.EllipsisConversion = true;
3193 else {
3194 User.Before = Best->Conversions[0].Standard;
3195 User.EllipsisConversion = false;
3196 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003197 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003198 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003199 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003200 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003201 User.After.setAsIdentityConversion();
3202 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3203 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003204 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003205 }
3206 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003207 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3208 // C++ [over.ics.user]p1:
3209 //
3210 // [...] If the user-defined conversion is specified by a
3211 // conversion function (12.3.2), the initial standard
3212 // conversion sequence converts the source type to the
3213 // implicit object parameter of the conversion function.
3214 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003215 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003216 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003217 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003218 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003219
John McCall5c32be02010-08-24 20:38:10 +00003220 // C++ [over.ics.user]p2:
3221 // The second standard conversion sequence converts the
3222 // result of the user-defined conversion to the target type
3223 // for the sequence. Since an implicit conversion sequence
3224 // is an initialization, the special rules for
3225 // initialization by user-defined conversion apply when
3226 // selecting the best user-defined conversion for a
3227 // user-defined conversion sequence (see 13.3.3 and
3228 // 13.3.3.1).
3229 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003230 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003231 }
David Blaikie8a40f702012-01-17 06:56:22 +00003232 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003233
John McCall5c32be02010-08-24 20:38:10 +00003234 case OR_No_Viable_Function:
3235 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
John McCall5c32be02010-08-24 20:38:10 +00003237 case OR_Ambiguous:
3238 return OR_Ambiguous;
3239 }
3240
David Blaikie8a40f702012-01-17 06:56:22 +00003241 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003242}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003244bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003245Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003246 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003247 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3248 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003250 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003251 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003252 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003253 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3254 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003255 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003256 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003257 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003258 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003259 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003260 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003261 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003262 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003265}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003266
Douglas Gregor2837aa22012-02-22 17:32:19 +00003267/// \brief Compare the user-defined conversion functions or constructors
3268/// of two user-defined conversion sequences to determine whether any ordering
3269/// is possible.
3270static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003271compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003272 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003273 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003274 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003275
Douglas Gregor2837aa22012-02-22 17:32:19 +00003276 // Objective-C++:
3277 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003278 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003279 // respectively, always prefer the conversion to a function pointer,
3280 // because the function pointer is more lightweight and is more likely
3281 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003282 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003283 if (!Conv1)
3284 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003285
Douglas Gregor2837aa22012-02-22 17:32:19 +00003286 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3287 if (!Conv2)
3288 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003289
Douglas Gregor2837aa22012-02-22 17:32:19 +00003290 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3291 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3292 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3293 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003294 return Block1 ? ImplicitConversionSequence::Worse
3295 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003296 }
3297
3298 return ImplicitConversionSequence::Indistinguishable;
3299}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003300
3301static bool hasDeprecatedStringLiteralToCharPtrConversion(
3302 const ImplicitConversionSequence &ICS) {
3303 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3304 (ICS.isUserDefined() &&
3305 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3306}
3307
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003308/// CompareImplicitConversionSequences - Compare two implicit
3309/// conversion sequences to determine whether one is better than the
3310/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003311static ImplicitConversionSequence::CompareKind
3312CompareImplicitConversionSequences(Sema &S,
3313 const ImplicitConversionSequence& ICS1,
3314 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003315{
3316 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3317 // conversion sequences (as defined in 13.3.3.1)
3318 // -- a standard conversion sequence (13.3.3.1.1) is a better
3319 // conversion sequence than a user-defined conversion sequence or
3320 // an ellipsis conversion sequence, and
3321 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3322 // conversion sequence than an ellipsis conversion sequence
3323 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003324 //
John McCall0d1da222010-01-12 00:44:57 +00003325 // C++0x [over.best.ics]p10:
3326 // For the purpose of ranking implicit conversion sequences as
3327 // described in 13.3.3.2, the ambiguous conversion sequence is
3328 // treated as a user-defined sequence that is indistinguishable
3329 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003330
3331 // String literal to 'char *' conversion has been deprecated in C++03. It has
3332 // been removed from C++11. We still accept this conversion, if it happens at
3333 // the best viable function. Otherwise, this conversion is considered worse
3334 // than ellipsis conversion. Consider this as an extension; this is not in the
3335 // standard. For example:
3336 //
3337 // int &f(...); // #1
3338 // void f(char*); // #2
3339 // void g() { int &r = f("foo"); }
3340 //
3341 // In C++03, we pick #2 as the best viable function.
3342 // In C++11, we pick #1 as the best viable function, because ellipsis
3343 // conversion is better than string-literal to char* conversion (since there
3344 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3345 // convert arguments, #2 would be the best viable function in C++11.
3346 // If the best viable function has this conversion, a warning will be issued
3347 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3348
3349 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3350 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3351 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3352 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3353 ? ImplicitConversionSequence::Worse
3354 : ImplicitConversionSequence::Better;
3355
Douglas Gregor5ab11652010-04-17 22:01:05 +00003356 if (ICS1.getKindRank() < ICS2.getKindRank())
3357 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003358 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003359 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003360
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003361 // The following checks require both conversion sequences to be of
3362 // the same kind.
3363 if (ICS1.getKind() != ICS2.getKind())
3364 return ImplicitConversionSequence::Indistinguishable;
3365
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003366 ImplicitConversionSequence::CompareKind Result =
3367 ImplicitConversionSequence::Indistinguishable;
3368
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003369 // Two implicit conversion sequences of the same form are
3370 // indistinguishable conversion sequences unless one of the
3371 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003372
3373 // List-initialization sequence L1 is a better conversion sequence than
3374 // list-initialization sequence L2 if:
3375 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3376 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003377 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003378 // and N1 is smaller than N2.,
3379 // even if one of the other rules in this paragraph would otherwise apply.
3380 if (!ICS1.isBad()) {
3381 if (ICS1.isStdInitializerListElement() &&
3382 !ICS2.isStdInitializerListElement())
3383 return ImplicitConversionSequence::Better;
3384 if (!ICS1.isStdInitializerListElement() &&
3385 ICS2.isStdInitializerListElement())
3386 return ImplicitConversionSequence::Worse;
3387 }
3388
John McCall0d1da222010-01-12 00:44:57 +00003389 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003390 // Standard conversion sequence S1 is a better conversion sequence than
3391 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003392 Result = CompareStandardConversionSequences(S,
3393 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003394 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003395 // User-defined conversion sequence U1 is a better conversion
3396 // sequence than another user-defined conversion sequence U2 if
3397 // they contain the same user-defined conversion function or
3398 // constructor and if the second standard conversion sequence of
3399 // U1 is better than the second standard conversion sequence of
3400 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003401 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003403 Result = CompareStandardConversionSequences(S,
3404 ICS1.UserDefined.After,
3405 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003406 else
3407 Result = compareConversionFunctions(S,
3408 ICS1.UserDefined.ConversionFunction,
3409 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003410 }
3411
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003412 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003413}
3414
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003415static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3416 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3417 Qualifiers Quals;
3418 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003422 return Context.hasSameUnqualifiedType(T1, T2);
3423}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003425// Per 13.3.3.2p3, compare the given standard conversion sequences to
3426// determine if one is a proper subset of the other.
3427static ImplicitConversionSequence::CompareKind
3428compareStandardConversionSubsets(ASTContext &Context,
3429 const StandardConversionSequence& SCS1,
3430 const StandardConversionSequence& SCS2) {
3431 ImplicitConversionSequence::CompareKind Result
3432 = ImplicitConversionSequence::Indistinguishable;
3433
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003435 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003436 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3437 return ImplicitConversionSequence::Better;
3438 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3439 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003441 if (SCS1.Second != SCS2.Second) {
3442 if (SCS1.Second == ICK_Identity)
3443 Result = ImplicitConversionSequence::Better;
3444 else if (SCS2.Second == ICK_Identity)
3445 Result = ImplicitConversionSequence::Worse;
3446 else
3447 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003448 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003449 return ImplicitConversionSequence::Indistinguishable;
3450
3451 if (SCS1.Third == SCS2.Third) {
3452 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3453 : ImplicitConversionSequence::Indistinguishable;
3454 }
3455
3456 if (SCS1.Third == ICK_Identity)
3457 return Result == ImplicitConversionSequence::Worse
3458 ? ImplicitConversionSequence::Indistinguishable
3459 : ImplicitConversionSequence::Better;
3460
3461 if (SCS2.Third == ICK_Identity)
3462 return Result == ImplicitConversionSequence::Better
3463 ? ImplicitConversionSequence::Indistinguishable
3464 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003466 return ImplicitConversionSequence::Indistinguishable;
3467}
3468
Douglas Gregore696ebb2011-01-26 14:52:12 +00003469/// \brief Determine whether one of the given reference bindings is better
3470/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003471static bool
3472isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3473 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003474 // C++0x [over.ics.rank]p3b4:
3475 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3476 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003478 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003480 // reference*.
3481 //
3482 // FIXME: Rvalue references. We're going rogue with the above edits,
3483 // because the semantics in the current C++0x working paper (N3225 at the
3484 // time of this writing) break the standard definition of std::forward
3485 // and std::reference_wrapper when dealing with references to functions.
3486 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003487 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3488 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3489 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregore696ebb2011-01-26 14:52:12 +00003491 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3492 SCS2.IsLvalueReference) ||
3493 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003494 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003495}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003497/// CompareStandardConversionSequences - Compare two standard
3498/// conversion sequences to determine whether one is better than the
3499/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003500static ImplicitConversionSequence::CompareKind
3501CompareStandardConversionSequences(Sema &S,
3502 const StandardConversionSequence& SCS1,
3503 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003504{
3505 // Standard conversion sequence S1 is a better conversion sequence
3506 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3507
3508 // -- S1 is a proper subsequence of S2 (comparing the conversion
3509 // sequences in the canonical form defined by 13.3.3.1.1,
3510 // excluding any Lvalue Transformation; the identity conversion
3511 // sequence is considered to be a subsequence of any
3512 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003513 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003514 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003515 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003516
3517 // -- the rank of S1 is better than the rank of S2 (by the rules
3518 // defined below), or, if not that,
3519 ImplicitConversionRank Rank1 = SCS1.getRank();
3520 ImplicitConversionRank Rank2 = SCS2.getRank();
3521 if (Rank1 < Rank2)
3522 return ImplicitConversionSequence::Better;
3523 else if (Rank2 < Rank1)
3524 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003525
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003526 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3527 // are indistinguishable unless one of the following rules
3528 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003529
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003530 // A conversion that is not a conversion of a pointer, or
3531 // pointer to member, to bool is better than another conversion
3532 // that is such a conversion.
3533 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3534 return SCS2.isPointerConversionToBool()
3535 ? ImplicitConversionSequence::Better
3536 : ImplicitConversionSequence::Worse;
3537
Douglas Gregor5c407d92008-10-23 00:40:37 +00003538 // C++ [over.ics.rank]p4b2:
3539 //
3540 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003541 // conversion of B* to A* is better than conversion of B* to
3542 // void*, and conversion of A* to void* is better than conversion
3543 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003544 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003545 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003546 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003547 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003548 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3549 // Exactly one of the conversion sequences is a conversion to
3550 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003551 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3552 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003553 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3554 // Neither conversion sequence converts to a void pointer; compare
3555 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003556 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003557 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003558 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003559 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3560 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003561 // Both conversion sequences are conversions to void
3562 // pointers. Compare the source types to determine if there's an
3563 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003564 QualType FromType1 = SCS1.getFromType();
3565 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003566
3567 // Adjust the types we're converting from via the array-to-pointer
3568 // conversion, if we need to.
3569 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003570 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003571 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003572 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003573
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003574 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3575 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003576
John McCall5c32be02010-08-24 20:38:10 +00003577 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003578 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003579 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003580 return ImplicitConversionSequence::Worse;
3581
3582 // Objective-C++: If one interface is more specific than the
3583 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003584 const ObjCObjectPointerType* FromObjCPtr1
3585 = FromType1->getAs<ObjCObjectPointerType>();
3586 const ObjCObjectPointerType* FromObjCPtr2
3587 = FromType2->getAs<ObjCObjectPointerType>();
3588 if (FromObjCPtr1 && FromObjCPtr2) {
3589 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3590 FromObjCPtr2);
3591 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3592 FromObjCPtr1);
3593 if (AssignLeft != AssignRight) {
3594 return AssignLeft? ImplicitConversionSequence::Better
3595 : ImplicitConversionSequence::Worse;
3596 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003597 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003598 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003599
3600 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3601 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003602 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003603 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003604 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003605
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003606 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003607 // Check for a better reference binding based on the kind of bindings.
3608 if (isBetterReferenceBindingKind(SCS1, SCS2))
3609 return ImplicitConversionSequence::Better;
3610 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3611 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Sebastian Redlb28b4072009-03-22 23:49:27 +00003613 // C++ [over.ics.rank]p3b4:
3614 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3615 // which the references refer are the same type except for
3616 // top-level cv-qualifiers, and the type to which the reference
3617 // initialized by S2 refers is more cv-qualified than the type
3618 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003619 QualType T1 = SCS1.getToType(2);
3620 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003621 T1 = S.Context.getCanonicalType(T1);
3622 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003623 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003624 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3625 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003626 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003627 // Objective-C++ ARC: If the references refer to objects with different
3628 // lifetimes, prefer bindings that don't change lifetime.
3629 if (SCS1.ObjCLifetimeConversionBinding !=
3630 SCS2.ObjCLifetimeConversionBinding) {
3631 return SCS1.ObjCLifetimeConversionBinding
3632 ? ImplicitConversionSequence::Worse
3633 : ImplicitConversionSequence::Better;
3634 }
3635
Chandler Carruth8e543b32010-12-12 08:17:55 +00003636 // If the type is an array type, promote the element qualifiers to the
3637 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003638 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003639 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003640 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003641 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003642 if (T2.isMoreQualifiedThan(T1))
3643 return ImplicitConversionSequence::Better;
3644 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003645 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003646 }
3647 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003648
Francois Pichet08d2fa02011-09-18 21:37:37 +00003649 // In Microsoft mode, prefer an integral conversion to a
3650 // floating-to-integral conversion if the integral conversion
3651 // is between types of the same size.
3652 // For example:
3653 // void f(float);
3654 // void f(int);
3655 // int main {
3656 // long a;
3657 // f(a);
3658 // }
3659 // Here, MSVC will call f(int) instead of generating a compile error
3660 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003661 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3662 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003663 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003664 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003665 return ImplicitConversionSequence::Better;
3666
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003667 return ImplicitConversionSequence::Indistinguishable;
3668}
3669
3670/// CompareQualificationConversions - Compares two standard conversion
3671/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003672/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003673static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003674CompareQualificationConversions(Sema &S,
3675 const StandardConversionSequence& SCS1,
3676 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003677 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003678 // -- S1 and S2 differ only in their qualification conversion and
3679 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3680 // cv-qualification signature of type T1 is a proper subset of
3681 // the cv-qualification signature of type T2, and S1 is not the
3682 // deprecated string literal array-to-pointer conversion (4.2).
3683 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3684 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3685 return ImplicitConversionSequence::Indistinguishable;
3686
3687 // FIXME: the example in the standard doesn't use a qualification
3688 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003689 QualType T1 = SCS1.getToType(2);
3690 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003691 T1 = S.Context.getCanonicalType(T1);
3692 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003694 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3695 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696
3697 // If the types are the same, we won't learn anything by unwrapped
3698 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003699 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003700 return ImplicitConversionSequence::Indistinguishable;
3701
Chandler Carruth607f38e2009-12-29 07:16:59 +00003702 // If the type is an array type, promote the element qualifiers to the type
3703 // for comparison.
3704 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003705 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003706 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003707 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003708
Mike Stump11289f42009-09-09 15:08:12 +00003709 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003711
3712 // Objective-C++ ARC:
3713 // Prefer qualification conversions not involving a change in lifetime
3714 // to qualification conversions that do not change lifetime.
3715 if (SCS1.QualificationIncludesObjCLifetime !=
3716 SCS2.QualificationIncludesObjCLifetime) {
3717 Result = SCS1.QualificationIncludesObjCLifetime
3718 ? ImplicitConversionSequence::Worse
3719 : ImplicitConversionSequence::Better;
3720 }
3721
John McCall5c32be02010-08-24 20:38:10 +00003722 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003723 // Within each iteration of the loop, we check the qualifiers to
3724 // determine if this still looks like a qualification
3725 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003726 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003727 // until there are no more pointers or pointers-to-members left
3728 // to unwrap. This essentially mimics what
3729 // IsQualificationConversion does, but here we're checking for a
3730 // strict subset of qualifiers.
3731 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3732 // The qualifiers are the same, so this doesn't tell us anything
3733 // about how the sequences rank.
3734 ;
3735 else if (T2.isMoreQualifiedThan(T1)) {
3736 // T1 has fewer qualifiers, so it could be the better sequence.
3737 if (Result == ImplicitConversionSequence::Worse)
3738 // Neither has qualifiers that are a subset of the other's
3739 // qualifiers.
3740 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003741
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003742 Result = ImplicitConversionSequence::Better;
3743 } else if (T1.isMoreQualifiedThan(T2)) {
3744 // T2 has fewer qualifiers, so it could be the better sequence.
3745 if (Result == ImplicitConversionSequence::Better)
3746 // Neither has qualifiers that are a subset of the other's
3747 // qualifiers.
3748 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003749
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003750 Result = ImplicitConversionSequence::Worse;
3751 } else {
3752 // Qualifiers are disjoint.
3753 return ImplicitConversionSequence::Indistinguishable;
3754 }
3755
3756 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003757 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003758 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003759 }
3760
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003761 // Check that the winning standard conversion sequence isn't using
3762 // the deprecated string literal array to pointer conversion.
3763 switch (Result) {
3764 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003765 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003766 Result = ImplicitConversionSequence::Indistinguishable;
3767 break;
3768
3769 case ImplicitConversionSequence::Indistinguishable:
3770 break;
3771
3772 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003773 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003774 Result = ImplicitConversionSequence::Indistinguishable;
3775 break;
3776 }
3777
3778 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003779}
3780
Douglas Gregor5c407d92008-10-23 00:40:37 +00003781/// CompareDerivedToBaseConversions - Compares two standard conversion
3782/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003783/// various kinds of derived-to-base conversions (C++
3784/// [over.ics.rank]p4b3). As part of these checks, we also look at
3785/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003786static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003787CompareDerivedToBaseConversions(Sema &S,
3788 const StandardConversionSequence& SCS1,
3789 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003790 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003791 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003792 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003793 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794
3795 // Adjust the types we're converting from via the array-to-pointer
3796 // conversion, if we need to.
3797 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003798 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003799 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003800 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003801
3802 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003803 FromType1 = S.Context.getCanonicalType(FromType1);
3804 ToType1 = S.Context.getCanonicalType(ToType1);
3805 FromType2 = S.Context.getCanonicalType(FromType2);
3806 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003807
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003808 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003809 //
3810 // If class B is derived directly or indirectly from class A and
3811 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003812 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003813 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003814 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003815 SCS2.Second == ICK_Pointer_Conversion &&
3816 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3817 FromType1->isPointerType() && FromType2->isPointerType() &&
3818 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003819 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003820 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003821 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003822 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003823 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003824 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003825 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003826 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003827
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003828 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003830 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003831 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003833 return ImplicitConversionSequence::Worse;
3834 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003835
3836 // -- conversion of B* to A* is better than conversion of C* to A*,
3837 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003838 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003839 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003840 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003841 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003842 }
3843 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3844 SCS2.Second == ICK_Pointer_Conversion) {
3845 const ObjCObjectPointerType *FromPtr1
3846 = FromType1->getAs<ObjCObjectPointerType>();
3847 const ObjCObjectPointerType *FromPtr2
3848 = FromType2->getAs<ObjCObjectPointerType>();
3849 const ObjCObjectPointerType *ToPtr1
3850 = ToType1->getAs<ObjCObjectPointerType>();
3851 const ObjCObjectPointerType *ToPtr2
3852 = ToType2->getAs<ObjCObjectPointerType>();
3853
3854 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3855 // Apply the same conversion ranking rules for Objective-C pointer types
3856 // that we do for C++ pointers to class types. However, we employ the
3857 // Objective-C pseudo-subtyping relationship used for assignment of
3858 // Objective-C pointer types.
3859 bool FromAssignLeft
3860 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3861 bool FromAssignRight
3862 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3863 bool ToAssignLeft
3864 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3865 bool ToAssignRight
3866 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3867
3868 // A conversion to an a non-id object pointer type or qualified 'id'
3869 // type is better than a conversion to 'id'.
3870 if (ToPtr1->isObjCIdType() &&
3871 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3872 return ImplicitConversionSequence::Worse;
3873 if (ToPtr2->isObjCIdType() &&
3874 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3875 return ImplicitConversionSequence::Better;
3876
3877 // A conversion to a non-id object pointer type is better than a
3878 // conversion to a qualified 'id' type
3879 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3880 return ImplicitConversionSequence::Worse;
3881 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3882 return ImplicitConversionSequence::Better;
3883
3884 // A conversion to an a non-Class object pointer type or qualified 'Class'
3885 // type is better than a conversion to 'Class'.
3886 if (ToPtr1->isObjCClassType() &&
3887 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3888 return ImplicitConversionSequence::Worse;
3889 if (ToPtr2->isObjCClassType() &&
3890 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3891 return ImplicitConversionSequence::Better;
3892
3893 // A conversion to a non-Class object pointer type is better than a
3894 // conversion to a qualified 'Class' type.
3895 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3896 return ImplicitConversionSequence::Worse;
3897 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3898 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003899
Douglas Gregor058d3de2011-01-31 18:51:41 +00003900 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3901 if (S.Context.hasSameType(FromType1, FromType2) &&
3902 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3903 (ToAssignLeft != ToAssignRight))
3904 return ToAssignLeft? ImplicitConversionSequence::Worse
3905 : ImplicitConversionSequence::Better;
3906
3907 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3908 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3909 (FromAssignLeft != FromAssignRight))
3910 return FromAssignLeft? ImplicitConversionSequence::Better
3911 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003912 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003913 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003914
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003915 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003916 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3917 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3918 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003920 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003922 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003924 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003926 ToType2->getAs<MemberPointerType>();
3927 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3928 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3929 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3930 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3931 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3932 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3933 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3934 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003935 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003936 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003937 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003938 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003939 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003940 return ImplicitConversionSequence::Better;
3941 }
3942 // conversion of B::* to C::* is better than conversion of A::* to C::*
3943 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003944 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003945 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003946 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003947 return ImplicitConversionSequence::Worse;
3948 }
3949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Douglas Gregor5ab11652010-04-17 22:01:05 +00003951 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003952 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003953 // -- binding of an expression of type C to a reference of type
3954 // B& is better than binding an expression of type C to a
3955 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003956 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3957 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3958 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003959 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003960 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003961 return ImplicitConversionSequence::Worse;
3962 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003963
Douglas Gregor2fe98832008-11-03 19:09:14 +00003964 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003965 // -- binding of an expression of type B to a reference of type
3966 // A& is better than binding an expression of type C to a
3967 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003968 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3969 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3970 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003971 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003972 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003973 return ImplicitConversionSequence::Worse;
3974 }
3975 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003976
Douglas Gregor5c407d92008-10-23 00:40:37 +00003977 return ImplicitConversionSequence::Indistinguishable;
3978}
3979
Douglas Gregor45bb4832013-03-26 23:36:30 +00003980/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3981/// C++ class.
3982static bool isTypeValid(QualType T) {
3983 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3984 return !Record->isInvalidDecl();
3985
3986 return true;
3987}
3988
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3990/// determine whether they are reference-related,
3991/// reference-compatible, reference-compatible with added
3992/// qualification, or incompatible, for use in C++ initialization by
3993/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3994/// type, and the first type (T1) is the pointee type of the reference
3995/// type being initialized.
3996Sema::ReferenceCompareResult
3997Sema::CompareReferenceRelationship(SourceLocation Loc,
3998 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003999 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004000 bool &ObjCConversion,
4001 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004002 assert(!OrigT1->isReferenceType() &&
4003 "T1 must be the pointee type of the reference type");
4004 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4005
4006 QualType T1 = Context.getCanonicalType(OrigT1);
4007 QualType T2 = Context.getCanonicalType(OrigT2);
4008 Qualifiers T1Quals, T2Quals;
4009 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4010 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4011
4012 // C++ [dcl.init.ref]p4:
4013 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4014 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4015 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004016 DerivedToBase = false;
4017 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004018 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004019 if (UnqualT1 == UnqualT2) {
4020 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004021 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004022 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4023 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004024 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004025 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4026 UnqualT2->isObjCObjectOrInterfaceType() &&
4027 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4028 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004029 else
4030 return Ref_Incompatible;
4031
4032 // At this point, we know that T1 and T2 are reference-related (at
4033 // least).
4034
4035 // If the type is an array type, promote the element qualifiers to the type
4036 // for comparison.
4037 if (isa<ArrayType>(T1) && T1Quals)
4038 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4039 if (isa<ArrayType>(T2) && T2Quals)
4040 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4041
4042 // C++ [dcl.init.ref]p4:
4043 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4044 // reference-related to T2 and cv1 is the same cv-qualification
4045 // as, or greater cv-qualification than, cv2. For purposes of
4046 // overload resolution, cases for which cv1 is greater
4047 // cv-qualification than cv2 are identified as
4048 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004049 //
4050 // Note that we also require equivalence of Objective-C GC and address-space
4051 // qualifiers when performing these computations, so that e.g., an int in
4052 // address space 1 is not reference-compatible with an int in address
4053 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004054 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4055 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004056 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4057 ObjCLifetimeConversion = true;
4058
John McCall31168b02011-06-15 23:02:42 +00004059 T1Quals.removeObjCLifetime();
4060 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004061 }
4062
Douglas Gregord517d552011-04-28 17:56:11 +00004063 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004064 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004065 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004066 return Ref_Compatible_With_Added_Qualification;
4067 else
4068 return Ref_Related;
4069}
4070
Douglas Gregor836a7e82010-08-11 02:15:33 +00004071/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004072/// with DeclType. Return true if something definite is found.
4073static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004074FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4075 QualType DeclType, SourceLocation DeclLoc,
4076 Expr *Init, QualType T2, bool AllowRvalues,
4077 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004078 assert(T2->isRecordType() && "Can only find conversions of record types.");
4079 CXXRecordDecl *T2RecordDecl
4080 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4081
Richard Smith100b24a2014-04-17 01:52:14 +00004082 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004083 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4084 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004085 NamedDecl *D = *I;
4086 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4087 if (isa<UsingShadowDecl>(D))
4088 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4089
4090 FunctionTemplateDecl *ConvTemplate
4091 = dyn_cast<FunctionTemplateDecl>(D);
4092 CXXConversionDecl *Conv;
4093 if (ConvTemplate)
4094 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4095 else
4096 Conv = cast<CXXConversionDecl>(D);
4097
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004099 // explicit conversions, skip it.
4100 if (!AllowExplicit && Conv->isExplicit())
4101 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102
Douglas Gregor836a7e82010-08-11 02:15:33 +00004103 if (AllowRvalues) {
4104 bool DerivedToBase = false;
4105 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004106 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004107
4108 // If we are initializing an rvalue reference, don't permit conversion
4109 // functions that return lvalues.
4110 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4111 const ReferenceType *RefType
4112 = Conv->getConversionType()->getAs<LValueReferenceType>();
4113 if (RefType && !RefType->getPointeeType()->isFunctionType())
4114 continue;
4115 }
4116
Douglas Gregor836a7e82010-08-11 02:15:33 +00004117 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004118 S.CompareReferenceRelationship(
4119 DeclLoc,
4120 Conv->getConversionType().getNonReferenceType()
4121 .getUnqualifiedType(),
4122 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004123 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004124 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004125 continue;
4126 } else {
4127 // If the conversion function doesn't return a reference type,
4128 // it can't be considered for this conversion. An rvalue reference
4129 // is only acceptable if its referencee is a function type.
4130
4131 const ReferenceType *RefType =
4132 Conv->getConversionType()->getAs<ReferenceType>();
4133 if (!RefType ||
4134 (!RefType->isLValueReferenceType() &&
4135 !RefType->getPointeeType()->isFunctionType()))
4136 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138
Douglas Gregor836a7e82010-08-11 02:15:33 +00004139 if (ConvTemplate)
4140 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004141 Init, DeclType, CandidateSet,
4142 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004143 else
4144 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004145 DeclType, CandidateSet,
4146 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004147 }
4148
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004149 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4150
Sebastian Redld92badf2010-06-30 18:13:39 +00004151 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004152 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004153 case OR_Success:
4154 // C++ [over.ics.ref]p1:
4155 //
4156 // [...] If the parameter binds directly to the result of
4157 // applying a conversion function to the argument
4158 // expression, the implicit conversion sequence is a
4159 // user-defined conversion sequence (13.3.3.1.2), with the
4160 // second standard conversion sequence either an identity
4161 // conversion or, if the conversion function returns an
4162 // entity of a type that is a derived class of the parameter
4163 // type, a derived-to-base Conversion.
4164 if (!Best->FinalConversion.DirectBinding)
4165 return false;
4166
4167 ICS.setUserDefined();
4168 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4169 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004170 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004171 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004172 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004173 ICS.UserDefined.EllipsisConversion = false;
4174 assert(ICS.UserDefined.After.ReferenceBinding &&
4175 ICS.UserDefined.After.DirectBinding &&
4176 "Expected a direct reference binding!");
4177 return true;
4178
4179 case OR_Ambiguous:
4180 ICS.setAmbiguous();
4181 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4182 Cand != CandidateSet.end(); ++Cand)
4183 if (Cand->Viable)
4184 ICS.Ambiguous.addConversion(Cand->Function);
4185 return true;
4186
4187 case OR_No_Viable_Function:
4188 case OR_Deleted:
4189 // There was no suitable conversion, or we found a deleted
4190 // conversion; continue with other checks.
4191 return false;
4192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
David Blaikie8a40f702012-01-17 06:56:22 +00004194 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004195}
4196
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004197/// \brief Compute an implicit conversion sequence for reference
4198/// initialization.
4199static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004200TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201 SourceLocation DeclLoc,
4202 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004203 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004204 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4205
4206 // Most paths end in a failed conversion.
4207 ImplicitConversionSequence ICS;
4208 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4209
4210 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4211 QualType T2 = Init->getType();
4212
4213 // If the initializer is the address of an overloaded function, try
4214 // to resolve the overloaded function. If all goes well, T2 is the
4215 // type of the resulting function.
4216 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4217 DeclAccessPair Found;
4218 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4219 false, Found))
4220 T2 = Fn->getType();
4221 }
4222
4223 // Compute some basic properties of the types and the initializer.
4224 bool isRValRef = DeclType->isRValueReferenceType();
4225 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004226 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004227 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004228 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004229 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004230 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004231 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004232
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004233
Sebastian Redld92badf2010-06-30 18:13:39 +00004234 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004235 // A reference to type "cv1 T1" is initialized by an expression
4236 // of type "cv2 T2" as follows:
4237
Sebastian Redld92badf2010-06-30 18:13:39 +00004238 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004239 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004240 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4241 // reference-compatible with "cv2 T2," or
4242 //
4243 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4244 if (InitCategory.isLValue() &&
4245 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004246 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004247 // When a parameter of reference type binds directly (8.5.3)
4248 // to an argument expression, the implicit conversion sequence
4249 // is the identity conversion, unless the argument expression
4250 // has a type that is a derived class of the parameter type,
4251 // in which case the implicit conversion sequence is a
4252 // derived-to-base Conversion (13.3.3.1).
4253 ICS.setStandard();
4254 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004255 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4256 : ObjCConversion? ICK_Compatible_Conversion
4257 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004258 ICS.Standard.Third = ICK_Identity;
4259 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4260 ICS.Standard.setToType(0, T2);
4261 ICS.Standard.setToType(1, T1);
4262 ICS.Standard.setToType(2, T1);
4263 ICS.Standard.ReferenceBinding = true;
4264 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004265 ICS.Standard.IsLvalueReference = !isRValRef;
4266 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4267 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004268 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004269 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004270 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004271 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004272
Sebastian Redld92badf2010-06-30 18:13:39 +00004273 // Nothing more to do: the inaccessibility/ambiguity check for
4274 // derived-to-base conversions is suppressed when we're
4275 // computing the implicit conversion sequence (C++
4276 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004277 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004278 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004279
Sebastian Redld92badf2010-06-30 18:13:39 +00004280 // -- has a class type (i.e., T2 is a class type), where T1 is
4281 // not reference-related to T2, and can be implicitly
4282 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4283 // is reference-compatible with "cv3 T3" 92) (this
4284 // conversion is selected by enumerating the applicable
4285 // conversion functions (13.3.1.6) and choosing the best
4286 // one through overload resolution (13.3)),
4287 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004289 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004290 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4291 Init, T2, /*AllowRvalues=*/false,
4292 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004293 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004294 }
4295 }
4296
Sebastian Redld92badf2010-06-30 18:13:39 +00004297 // -- Otherwise, the reference shall be an lvalue reference to a
4298 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004299 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004300 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004301 return ICS;
4302
Douglas Gregorf143cd52011-01-24 16:14:37 +00004303 // -- If the initializer expression
4304 //
4305 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004306 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4308 (InitCategory.isXValue() ||
4309 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4310 (InitCategory.isLValue() && T2->isFunctionType()))) {
4311 ICS.setStandard();
4312 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 : ObjCConversion? ICK_Compatible_Conversion
4315 : ICK_Identity;
4316 ICS.Standard.Third = ICK_Identity;
4317 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4318 ICS.Standard.setToType(0, T2);
4319 ICS.Standard.setToType(1, T1);
4320 ICS.Standard.setToType(2, T1);
4321 ICS.Standard.ReferenceBinding = true;
4322 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4323 // binding unless we're binding to a class prvalue.
4324 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4325 // allow the use of rvalue references in C++98/03 for the benefit of
4326 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004328 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004329 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004330 ICS.Standard.IsLvalueReference = !isRValRef;
4331 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004334 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004335 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004336 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
Douglas Gregorf143cd52011-01-24 16:14:37 +00004340 // -- has a class type (i.e., T2 is a class type), where T1 is not
4341 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342 // an xvalue, class prvalue, or function lvalue of type
4343 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004344 // "cv3 T3",
4345 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004347 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004349 // class subobject).
4350 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004352 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4353 Init, T2, /*AllowRvalues=*/true,
4354 AllowExplicit)) {
4355 // In the second case, if the reference is an rvalue reference
4356 // and the second standard conversion sequence of the
4357 // user-defined conversion sequence includes an lvalue-to-rvalue
4358 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004360 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4361 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4362
Douglas Gregor95273c32011-01-21 16:36:05 +00004363 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Richard Smith19172c42014-07-14 02:28:44 +00004366 // A temporary of function type cannot be created; don't even try.
4367 if (T1->isFunctionType())
4368 return ICS;
4369
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004370 // -- Otherwise, a temporary of type "cv1 T1" is created and
4371 // initialized from the initializer expression using the
4372 // rules for a non-reference copy initialization (8.5). The
4373 // reference is then bound to the temporary. If T1 is
4374 // reference-related to T2, cv1 must be the same
4375 // cv-qualification as, or greater cv-qualification than,
4376 // cv2; otherwise, the program is ill-formed.
4377 if (RefRelationship == Sema::Ref_Related) {
4378 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4379 // we would be reference-compatible or reference-compatible with
4380 // added qualification. But that wasn't the case, so the reference
4381 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004382 //
4383 // Note that we only want to check address spaces and cvr-qualifiers here.
4384 // ObjC GC and lifetime qualifiers aren't important.
4385 Qualifiers T1Quals = T1.getQualifiers();
4386 Qualifiers T2Quals = T2.getQualifiers();
4387 T1Quals.removeObjCGCAttr();
4388 T1Quals.removeObjCLifetime();
4389 T2Quals.removeObjCGCAttr();
4390 T2Quals.removeObjCLifetime();
4391 if (!T1Quals.compatiblyIncludes(T2Quals))
4392 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393 }
4394
4395 // If at least one of the types is a class type, the types are not
4396 // related, and we aren't allowed any user conversions, the
4397 // reference binding fails. This case is important for breaking
4398 // recursion, since TryImplicitConversion below will attempt to
4399 // create a temporary through the use of a copy constructor.
4400 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4401 (T1->isRecordType() || T2->isRecordType()))
4402 return ICS;
4403
Douglas Gregorcba72b12011-01-21 05:18:22 +00004404 // If T1 is reference-related to T2 and the reference is an rvalue
4405 // reference, the initializer expression shall not be an lvalue.
4406 if (RefRelationship >= Sema::Ref_Related &&
4407 isRValRef && Init->Classify(S.Context).isLValue())
4408 return ICS;
4409
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004411 // When a parameter of reference type is not bound directly to
4412 // an argument expression, the conversion sequence is the one
4413 // required to convert the argument expression to the
4414 // underlying type of the reference according to
4415 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4416 // to copy-initializing a temporary of the underlying type with
4417 // the argument expression. Any difference in top-level
4418 // cv-qualification is subsumed by the initialization itself
4419 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004420 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4421 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004422 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004423 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004424 /*AllowObjCWritebackConversion=*/false,
4425 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004426
4427 // Of course, that's still a reference binding.
4428 if (ICS.isStandard()) {
4429 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004430 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004431 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004432 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004433 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004434 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004435 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004436 const ReferenceType *LValRefType =
4437 ICS.UserDefined.ConversionFunction->getReturnType()
4438 ->getAs<LValueReferenceType>();
4439
4440 // C++ [over.ics.ref]p3:
4441 // Except for an implicit object parameter, for which see 13.3.1, a
4442 // standard conversion sequence cannot be formed if it requires [...]
4443 // binding an rvalue reference to an lvalue other than a function
4444 // lvalue.
4445 // Note that the function case is not possible here.
4446 if (DeclType->isRValueReferenceType() && LValRefType) {
4447 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4448 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4449 // reference to an rvalue!
4450 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4451 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004452 }
Richard Smith19172c42014-07-14 02:28:44 +00004453
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004454 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004455 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004456 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004457 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4458 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004459 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4460 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004462
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 return ICS;
4464}
4465
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004466static ImplicitConversionSequence
4467TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4468 bool SuppressUserConversions,
4469 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004470 bool AllowObjCWritebackConversion,
4471 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004472
4473/// TryListConversion - Try to copy-initialize a value of type ToType from the
4474/// initializer list From.
4475static ImplicitConversionSequence
4476TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4477 bool SuppressUserConversions,
4478 bool InOverloadResolution,
4479 bool AllowObjCWritebackConversion) {
4480 // C++11 [over.ics.list]p1:
4481 // When an argument is an initializer list, it is not an expression and
4482 // special rules apply for converting it to a parameter type.
4483
4484 ImplicitConversionSequence Result;
4485 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4486
Sebastian Redl09edce02012-01-23 22:09:39 +00004487 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004488 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004489 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004490 return Result;
4491
Larisse Voufo19d08672015-01-27 18:47:05 +00004492 // Per DR1467:
4493 // If the parameter type is a class X and the initializer list has a single
4494 // element of type cv U, where U is X or a class derived from X, the
4495 // implicit conversion sequence is the one required to convert the element
4496 // to the parameter type.
4497 //
4498 // Otherwise, if the parameter type is a character array [... ]
4499 // and the initializer list has a single element that is an
4500 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4501 // implicit conversion sequence is the identity conversion.
4502 if (From->getNumInits() == 1) {
4503 if (ToType->isRecordType()) {
4504 QualType InitType = From->getInit(0)->getType();
4505 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4506 S.IsDerivedFrom(InitType, ToType))
4507 return TryCopyInitialization(S, From->getInit(0), ToType,
4508 SuppressUserConversions,
4509 InOverloadResolution,
4510 AllowObjCWritebackConversion);
4511 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004512 // FIXME: Check the other conditions here: array of character type,
4513 // initializer is a string literal.
4514 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004515 InitializedEntity Entity =
4516 InitializedEntity::InitializeParameter(S.Context, ToType,
4517 /*Consumed=*/false);
4518 if (S.CanPerformCopyInitialization(Entity, From)) {
4519 Result.setStandard();
4520 Result.Standard.setAsIdentityConversion();
4521 Result.Standard.setFromType(ToType);
4522 Result.Standard.setAllToTypes(ToType);
4523 return Result;
4524 }
4525 }
4526 }
4527
4528 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004529 // C++11 [over.ics.list]p2:
4530 // If the parameter type is std::initializer_list<X> or "array of X" and
4531 // all the elements can be implicitly converted to X, the implicit
4532 // conversion sequence is the worst conversion necessary to convert an
4533 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004534 //
4535 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004536 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004537 // list has exactly N elements or if it has fewer than N elements and X is
4538 // default-constructible, and if all the elements of the initializer list
4539 // can be implicitly converted to X, the implicit conversion sequence is
4540 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004541 //
4542 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004543 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004544 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004545 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004546 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004547 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004548 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004549 if (!X.isNull()) {
4550 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4551 Expr *Init = From->getInit(i);
4552 ImplicitConversionSequence ICS =
4553 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4554 InOverloadResolution,
4555 AllowObjCWritebackConversion);
4556 // If a single element isn't convertible, fail.
4557 if (ICS.isBad()) {
4558 Result = ICS;
4559 break;
4560 }
4561 // Otherwise, look for the worst conversion.
4562 if (Result.isBad() ||
4563 CompareImplicitConversionSequences(S, ICS, Result) ==
4564 ImplicitConversionSequence::Worse)
4565 Result = ICS;
4566 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004567
4568 // For an empty list, we won't have computed any conversion sequence.
4569 // Introduce the identity conversion sequence.
4570 if (From->getNumInits() == 0) {
4571 Result.setStandard();
4572 Result.Standard.setAsIdentityConversion();
4573 Result.Standard.setFromType(ToType);
4574 Result.Standard.setAllToTypes(ToType);
4575 }
4576
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004577 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004578 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004579 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004580
Larisse Voufo19d08672015-01-27 18:47:05 +00004581 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004582 // C++11 [over.ics.list]p3:
4583 // Otherwise, if the parameter is a non-aggregate class X and overload
4584 // resolution chooses a single best constructor [...] the implicit
4585 // conversion sequence is a user-defined conversion sequence. If multiple
4586 // constructors are viable but none is better than the others, the
4587 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004588 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4589 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004590 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4591 /*AllowExplicit=*/false,
4592 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004593 AllowObjCWritebackConversion,
4594 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004595 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004596
Larisse Voufo19d08672015-01-27 18:47:05 +00004597 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004598 // C++11 [over.ics.list]p4:
4599 // Otherwise, if the parameter has an aggregate type which can be
4600 // initialized from the initializer list [...] the implicit conversion
4601 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004602 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004603 // Type is an aggregate, argument is an init list. At this point it comes
4604 // down to checking whether the initialization works.
4605 // FIXME: Find out whether this parameter is consumed or not.
4606 InitializedEntity Entity =
4607 InitializedEntity::InitializeParameter(S.Context, ToType,
4608 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004609 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004610 Result.setUserDefined();
4611 Result.UserDefined.Before.setAsIdentityConversion();
4612 // Initializer lists don't have a type.
4613 Result.UserDefined.Before.setFromType(QualType());
4614 Result.UserDefined.Before.setAllToTypes(QualType());
4615
4616 Result.UserDefined.After.setAsIdentityConversion();
4617 Result.UserDefined.After.setFromType(ToType);
4618 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004619 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004620 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004621 return Result;
4622 }
4623
Larisse Voufo19d08672015-01-27 18:47:05 +00004624 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004625 // C++11 [over.ics.list]p5:
4626 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004627 if (ToType->isReferenceType()) {
4628 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4629 // mention initializer lists in any way. So we go by what list-
4630 // initialization would do and try to extrapolate from that.
4631
4632 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4633
4634 // If the initializer list has a single element that is reference-related
4635 // to the parameter type, we initialize the reference from that.
4636 if (From->getNumInits() == 1) {
4637 Expr *Init = From->getInit(0);
4638
4639 QualType T2 = Init->getType();
4640
4641 // If the initializer is the address of an overloaded function, try
4642 // to resolve the overloaded function. If all goes well, T2 is the
4643 // type of the resulting function.
4644 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4645 DeclAccessPair Found;
4646 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4647 Init, ToType, false, Found))
4648 T2 = Fn->getType();
4649 }
4650
4651 // Compute some basic properties of the types and the initializer.
4652 bool dummy1 = false;
4653 bool dummy2 = false;
4654 bool dummy3 = false;
4655 Sema::ReferenceCompareResult RefRelationship
4656 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4657 dummy2, dummy3);
4658
Richard Smith4d2bbd72013-09-06 01:22:42 +00004659 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004660 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4661 SuppressUserConversions,
4662 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004663 }
Sebastian Redldf888642011-12-03 14:54:30 +00004664 }
4665
4666 // Otherwise, we bind the reference to a temporary created from the
4667 // initializer list.
4668 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4669 InOverloadResolution,
4670 AllowObjCWritebackConversion);
4671 if (Result.isFailure())
4672 return Result;
4673 assert(!Result.isEllipsis() &&
4674 "Sub-initialization cannot result in ellipsis conversion.");
4675
4676 // Can we even bind to a temporary?
4677 if (ToType->isRValueReferenceType() ||
4678 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4679 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4680 Result.UserDefined.After;
4681 SCS.ReferenceBinding = true;
4682 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4683 SCS.BindsToRvalue = true;
4684 SCS.BindsToFunctionLvalue = false;
4685 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4686 SCS.ObjCLifetimeConversionBinding = false;
4687 } else
4688 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4689 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004690 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004691 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004692
Larisse Voufo19d08672015-01-27 18:47:05 +00004693 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004694 // C++11 [over.ics.list]p6:
4695 // Otherwise, if the parameter type is not a class:
4696 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004697 // - if the initializer list has one element that is not itself an
4698 // initializer list, the implicit conversion sequence is the one
4699 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004700 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004701 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004702 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4703 SuppressUserConversions,
4704 InOverloadResolution,
4705 AllowObjCWritebackConversion);
4706 // - if the initializer list has no elements, the implicit conversion
4707 // sequence is the identity conversion.
4708 else if (NumInits == 0) {
4709 Result.setStandard();
4710 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004711 Result.Standard.setFromType(ToType);
4712 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004713 }
4714 return Result;
4715 }
4716
Larisse Voufo19d08672015-01-27 18:47:05 +00004717 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004718 // C++11 [over.ics.list]p7:
4719 // In all cases other than those enumerated above, no conversion is possible
4720 return Result;
4721}
4722
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004723/// TryCopyInitialization - Try to copy-initialize a value of type
4724/// ToType from the expression From. Return the implicit conversion
4725/// sequence required to pass this argument, which may be a bad
4726/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004727/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004728/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004729static ImplicitConversionSequence
4730TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004732 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004733 bool AllowObjCWritebackConversion,
4734 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004735 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4736 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4737 InOverloadResolution,AllowObjCWritebackConversion);
4738
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004739 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004740 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004741 /*FIXME:*/From->getLocStart(),
4742 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004743 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004744
John McCall5c32be02010-08-24 20:38:10 +00004745 return TryImplicitConversion(S, From, ToType,
4746 SuppressUserConversions,
4747 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004748 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004749 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004750 AllowObjCWritebackConversion,
4751 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004752}
4753
Anna Zaks1b068122011-07-28 19:46:48 +00004754static bool TryCopyInitialization(const CanQualType FromQTy,
4755 const CanQualType ToQTy,
4756 Sema &S,
4757 SourceLocation Loc,
4758 ExprValueKind FromVK) {
4759 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4760 ImplicitConversionSequence ICS =
4761 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4762
4763 return !ICS.isBad();
4764}
4765
Douglas Gregor436424c2008-11-18 23:14:02 +00004766/// TryObjectArgumentInitialization - Try to initialize the object
4767/// parameter of the given member function (@c Method) from the
4768/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004769static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004770TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004771 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004772 CXXMethodDecl *Method,
4773 CXXRecordDecl *ActingContext) {
4774 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004775 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4776 // const volatile object.
4777 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4778 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004779 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004780
4781 // Set up the conversion sequence as a "bad" conversion, to allow us
4782 // to exit early.
4783 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004784
4785 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004786 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004787 FromType = PT->getPointeeType();
4788
Douglas Gregor02824322011-01-26 19:30:28 +00004789 // When we had a pointer, it's implicitly dereferenced, so we
4790 // better have an lvalue.
4791 assert(FromClassification.isLValue());
4792 }
4793
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004794 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004795
Douglas Gregor02824322011-01-26 19:30:28 +00004796 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004798 // parameter is
4799 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004800 // - "lvalue reference to cv X" for functions declared without a
4801 // ref-qualifier or with the & ref-qualifier
4802 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004803 // ref-qualifier
4804 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004806 // cv-qualification on the member function declaration.
4807 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004809 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004810 // (C++ [over.match.funcs]p5). We perform a simplified version of
4811 // reference binding here, that allows class rvalues to bind to
4812 // non-constant references.
4813
Douglas Gregor02824322011-01-26 19:30:28 +00004814 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004815 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004817 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004818 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004819 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004820 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004821 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004822 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004823
4824 // Check that we have either the same type or a derived type. It
4825 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004826 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004827 ImplicitConversionKind SecondKind;
4828 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4829 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004830 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004831 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004832 else {
John McCall65eb8792010-02-25 01:37:24 +00004833 ICS.setBad(BadConversionSequence::unrelated_class,
4834 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004835 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004836 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004837
Douglas Gregor02824322011-01-26 19:30:28 +00004838 // Check the ref-qualifier.
4839 switch (Method->getRefQualifier()) {
4840 case RQ_None:
4841 // Do nothing; we don't care about lvalueness or rvalueness.
4842 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Douglas Gregor02824322011-01-26 19:30:28 +00004844 case RQ_LValue:
4845 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4846 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004848 ImplicitParamType);
4849 return ICS;
4850 }
4851 break;
4852
4853 case RQ_RValue:
4854 if (!FromClassification.isRValue()) {
4855 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004857 ImplicitParamType);
4858 return ICS;
4859 }
4860 break;
4861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Douglas Gregor436424c2008-11-18 23:14:02 +00004863 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004864 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004865 ICS.Standard.setAsIdentityConversion();
4866 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004867 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004868 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004869 ICS.Standard.ReferenceBinding = true;
4870 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004872 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004873 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4874 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4875 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004876 return ICS;
4877}
4878
4879/// PerformObjectArgumentInitialization - Perform initialization of
4880/// the implicit object parameter for the given Method with the given
4881/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004882ExprResult
4883Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004885 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004886 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004887 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004888 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004889 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004890
Douglas Gregor02824322011-01-26 19:30:28 +00004891 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004892 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004893 FromRecordType = PT->getPointeeType();
4894 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004895 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004896 } else {
4897 FromRecordType = From->getType();
4898 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004899 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004900 }
4901
John McCall6e9f8f62009-12-03 04:06:58 +00004902 // Note that we always use the true parent context when performing
4903 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004904 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4905 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004906 if (ICS.isBad()) {
4907 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4908 Qualifiers FromQs = FromRecordType.getQualifiers();
4909 Qualifiers ToQs = DestType.getQualifiers();
4910 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4911 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004912 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004913 diag::err_member_function_call_bad_cvr)
4914 << Method->getDeclName() << FromRecordType << (CVR - 1)
4915 << From->getSourceRange();
4916 Diag(Method->getLocation(), diag::note_previous_decl)
4917 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004918 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004919 }
4920 }
4921
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004922 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004923 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004924 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004925 }
Mike Stump11289f42009-09-09 15:08:12 +00004926
John Wiegley01296292011-04-08 18:41:53 +00004927 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4928 ExprResult FromRes =
4929 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4930 if (FromRes.isInvalid())
4931 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004932 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004933 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004934
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004935 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004936 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004937 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004938 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004939}
4940
Douglas Gregor5fb53972009-01-14 15:45:31 +00004941/// TryContextuallyConvertToBool - Attempt to contextually convert the
4942/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004943static ImplicitConversionSequence
4944TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004945 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004946 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004947 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004948 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004949 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004950 /*AllowObjCWritebackConversion=*/false,
4951 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004952}
4953
4954/// PerformContextuallyConvertToBool - Perform a contextual conversion
4955/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004956ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004957 if (checkPlaceholderForOverload(*this, From))
4958 return ExprError();
4959
John McCall5c32be02010-08-24 20:38:10 +00004960 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004961 if (!ICS.isBad())
4962 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Fariborz Jahanian76197412009-11-18 18:26:29 +00004964 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004965 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004966 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004967 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004968 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004969}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970
Richard Smithf8379a02012-01-18 23:55:52 +00004971/// Check that the specified conversion is permitted in a converted constant
4972/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4973/// is acceptable.
4974static bool CheckConvertedConstantConversions(Sema &S,
4975 StandardConversionSequence &SCS) {
4976 // Since we know that the target type is an integral or unscoped enumeration
4977 // type, most conversion kinds are impossible. All possible First and Third
4978 // conversions are fine.
4979 switch (SCS.Second) {
4980 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004981 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004982 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004983 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004984 return true;
4985
4986 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004987 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004988 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4989 // conversion, so we allow it in a converted constant expression.
4990 //
4991 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4992 // a lot of popular code. We should at least add a warning for this
4993 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004994 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4995 SCS.getToType(2)->isBooleanType();
4996
Richard Smith410cc892014-11-26 03:26:53 +00004997 case ICK_Pointer_Conversion:
4998 case ICK_Pointer_Member:
4999 // C++1z: null pointer conversions and null member pointer conversions are
5000 // only permitted if the source type is std::nullptr_t.
5001 return SCS.getFromType()->isNullPtrType();
5002
5003 case ICK_Floating_Promotion:
5004 case ICK_Complex_Promotion:
5005 case ICK_Floating_Conversion:
5006 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005007 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005008 case ICK_Compatible_Conversion:
5009 case ICK_Derived_To_Base:
5010 case ICK_Vector_Conversion:
5011 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005012 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005013 case ICK_Block_Pointer_Conversion:
5014 case ICK_TransparentUnionConversion:
5015 case ICK_Writeback_Conversion:
5016 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005017 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005018 return false;
5019
5020 case ICK_Lvalue_To_Rvalue:
5021 case ICK_Array_To_Pointer:
5022 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005023 llvm_unreachable("found a first conversion kind in Second");
5024
Richard Smithf8379a02012-01-18 23:55:52 +00005025 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005026 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005027
5028 case ICK_Num_Conversion_Kinds:
5029 break;
5030 }
5031
5032 llvm_unreachable("unknown conversion kind");
5033}
5034
5035/// CheckConvertedConstantExpression - Check that the expression From is a
5036/// converted constant expression of type T, perform the conversion and produce
5037/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005038static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5039 QualType T, APValue &Value,
5040 Sema::CCEKind CCE,
5041 bool RequireInt) {
5042 assert(S.getLangOpts().CPlusPlus11 &&
5043 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005044
Richard Smith410cc892014-11-26 03:26:53 +00005045 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005046 return ExprError();
5047
Richard Smith410cc892014-11-26 03:26:53 +00005048 // C++1z [expr.const]p3:
5049 // A converted constant expression of type T is an expression,
5050 // implicitly converted to type T, where the converted
5051 // expression is a constant expression and the implicit conversion
5052 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005053 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005054 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005055 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005056 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005057 /*AllowObjcWritebackConversion=*/false,
5058 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005059 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005060 switch (ICS.getKind()) {
5061 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005062 SCS = &ICS.Standard;
5063 break;
5064 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005065 // We are converting to a non-class type, so the Before sequence
5066 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005067 SCS = &ICS.UserDefined.After;
5068 break;
5069 case ImplicitConversionSequence::AmbiguousConversion:
5070 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005071 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5072 return S.Diag(From->getLocStart(),
5073 diag::err_typecheck_converted_constant_expression)
5074 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005075 return ExprError();
5076
5077 case ImplicitConversionSequence::EllipsisConversion:
5078 llvm_unreachable("ellipsis conversion in converted constant expression");
5079 }
5080
Richard Smith410cc892014-11-26 03:26:53 +00005081 // Check that we would only use permitted conversions.
5082 if (!CheckConvertedConstantConversions(S, *SCS)) {
5083 return S.Diag(From->getLocStart(),
5084 diag::err_typecheck_converted_constant_expression_disallowed)
5085 << From->getType() << From->getSourceRange() << T;
5086 }
5087 // [...] and where the reference binding (if any) binds directly.
5088 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5089 return S.Diag(From->getLocStart(),
5090 diag::err_typecheck_converted_constant_expression_indirect)
5091 << From->getType() << From->getSourceRange() << T;
5092 }
5093
5094 ExprResult Result =
5095 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005096 if (Result.isInvalid())
5097 return Result;
5098
5099 // Check for a narrowing implicit conversion.
5100 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005101 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005102 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005103 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005104 case NK_Variable_Narrowing:
5105 // Implicit conversion to a narrower type, and the value is not a constant
5106 // expression. We'll diagnose this in a moment.
5107 case NK_Not_Narrowing:
5108 break;
5109
5110 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005111 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005112 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005113 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005114 break;
5115
5116 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005117 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005118 << CCE << /*Constant*/0 << From->getType() << T;
5119 break;
5120 }
5121
5122 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005123 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005124 Expr::EvalResult Eval;
5125 Eval.Diag = &Notes;
5126
Richard Smith410cc892014-11-26 03:26:53 +00005127 if ((T->isReferenceType()
5128 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5129 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5130 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005131 // The expression can't be folded, so we can't keep it at this position in
5132 // the AST.
5133 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005134 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005135 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005136
5137 if (Notes.empty()) {
5138 // It's a constant expression.
5139 return Result;
5140 }
Richard Smithf8379a02012-01-18 23:55:52 +00005141 }
5142
5143 // It's not a constant expression. Produce an appropriate diagnostic.
5144 if (Notes.size() == 1 &&
5145 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005146 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005147 else {
Richard Smith410cc892014-11-26 03:26:53 +00005148 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005149 << CCE << From->getSourceRange();
5150 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005151 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005152 }
Richard Smith410cc892014-11-26 03:26:53 +00005153 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005154}
5155
Richard Smith410cc892014-11-26 03:26:53 +00005156ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5157 APValue &Value, CCEKind CCE) {
5158 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5159}
5160
5161ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5162 llvm::APSInt &Value,
5163 CCEKind CCE) {
5164 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5165
5166 APValue V;
5167 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5168 if (!R.isInvalid())
5169 Value = V.getInt();
5170 return R;
5171}
5172
5173
John McCallfec112d2011-09-09 06:11:02 +00005174/// dropPointerConversions - If the given standard conversion sequence
5175/// involves any pointer conversions, remove them. This may change
5176/// the result type of the conversion sequence.
5177static void dropPointerConversion(StandardConversionSequence &SCS) {
5178 if (SCS.Second == ICK_Pointer_Conversion) {
5179 SCS.Second = ICK_Identity;
5180 SCS.Third = ICK_Identity;
5181 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5182 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005183}
John McCall5c32be02010-08-24 20:38:10 +00005184
John McCallfec112d2011-09-09 06:11:02 +00005185/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5186/// convert the expression From to an Objective-C pointer type.
5187static ImplicitConversionSequence
5188TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5189 // Do an implicit conversion to 'id'.
5190 QualType Ty = S.Context.getObjCIdType();
5191 ImplicitConversionSequence ICS
5192 = TryImplicitConversion(S, From, Ty,
5193 // FIXME: Are these flags correct?
5194 /*SuppressUserConversions=*/false,
5195 /*AllowExplicit=*/true,
5196 /*InOverloadResolution=*/false,
5197 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005198 /*AllowObjCWritebackConversion=*/false,
5199 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005200
5201 // Strip off any final conversions to 'id'.
5202 switch (ICS.getKind()) {
5203 case ImplicitConversionSequence::BadConversion:
5204 case ImplicitConversionSequence::AmbiguousConversion:
5205 case ImplicitConversionSequence::EllipsisConversion:
5206 break;
5207
5208 case ImplicitConversionSequence::UserDefinedConversion:
5209 dropPointerConversion(ICS.UserDefined.After);
5210 break;
5211
5212 case ImplicitConversionSequence::StandardConversion:
5213 dropPointerConversion(ICS.Standard);
5214 break;
5215 }
5216
5217 return ICS;
5218}
5219
5220/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5221/// conversion of the expression From to an Objective-C pointer type.
5222ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005223 if (checkPlaceholderForOverload(*this, From))
5224 return ExprError();
5225
John McCall8b07ec22010-05-15 11:32:37 +00005226 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005227 ImplicitConversionSequence ICS =
5228 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005229 if (!ICS.isBad())
5230 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005231 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005232}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005233
Richard Smith8dd34252012-02-04 07:07:42 +00005234/// Determine whether the provided type is an integral type, or an enumeration
5235/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005236bool Sema::ICEConvertDiagnoser::match(QualType T) {
5237 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5238 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005239}
5240
Larisse Voufo236bec22013-06-10 06:50:24 +00005241static ExprResult
5242diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5243 Sema::ContextualImplicitConverter &Converter,
5244 QualType T, UnresolvedSetImpl &ViableConversions) {
5245
5246 if (Converter.Suppress)
5247 return ExprError();
5248
5249 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5250 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5251 CXXConversionDecl *Conv =
5252 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5253 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5254 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5255 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005256 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005257}
5258
5259static bool
5260diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5261 Sema::ContextualImplicitConverter &Converter,
5262 QualType T, bool HadMultipleCandidates,
5263 UnresolvedSetImpl &ExplicitConversions) {
5264 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5265 DeclAccessPair Found = ExplicitConversions[0];
5266 CXXConversionDecl *Conversion =
5267 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5268
5269 // The user probably meant to invoke the given explicit
5270 // conversion; use it.
5271 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5272 std::string TypeStr;
5273 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5274
5275 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5276 << FixItHint::CreateInsertion(From->getLocStart(),
5277 "static_cast<" + TypeStr + ">(")
5278 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005279 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005280 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5281
5282 // If we aren't in a SFINAE context, build a call to the
5283 // explicit conversion function.
5284 if (SemaRef.isSFINAEContext())
5285 return true;
5286
Craig Topperc3ec1492014-05-26 06:22:03 +00005287 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005288 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5289 HadMultipleCandidates);
5290 if (Result.isInvalid())
5291 return true;
5292 // Record usage of conversion in an implicit cast.
5293 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005294 CK_UserDefinedConversion, Result.get(),
5295 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005296 }
5297 return false;
5298}
5299
5300static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5301 Sema::ContextualImplicitConverter &Converter,
5302 QualType T, bool HadMultipleCandidates,
5303 DeclAccessPair &Found) {
5304 CXXConversionDecl *Conversion =
5305 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005306 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005307
5308 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5309 if (!Converter.SuppressConversion) {
5310 if (SemaRef.isSFINAEContext())
5311 return true;
5312
5313 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5314 << From->getSourceRange();
5315 }
5316
5317 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5318 HadMultipleCandidates);
5319 if (Result.isInvalid())
5320 return true;
5321 // Record usage of conversion in an implicit cast.
5322 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005323 CK_UserDefinedConversion, Result.get(),
5324 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005325 return false;
5326}
5327
5328static ExprResult finishContextualImplicitConversion(
5329 Sema &SemaRef, SourceLocation Loc, Expr *From,
5330 Sema::ContextualImplicitConverter &Converter) {
5331 if (!Converter.match(From->getType()) && !Converter.Suppress)
5332 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5333 << From->getSourceRange();
5334
5335 return SemaRef.DefaultLvalueConversion(From);
5336}
5337
5338static void
5339collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5340 UnresolvedSetImpl &ViableConversions,
5341 OverloadCandidateSet &CandidateSet) {
5342 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5343 DeclAccessPair FoundDecl = ViableConversions[I];
5344 NamedDecl *D = FoundDecl.getDecl();
5345 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5346 if (isa<UsingShadowDecl>(D))
5347 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5348
5349 CXXConversionDecl *Conv;
5350 FunctionTemplateDecl *ConvTemplate;
5351 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5352 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5353 else
5354 Conv = cast<CXXConversionDecl>(D);
5355
5356 if (ConvTemplate)
5357 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005358 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5359 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005360 else
5361 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005362 ToType, CandidateSet,
5363 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005364 }
5365}
5366
Richard Smithccc11812013-05-21 19:05:48 +00005367/// \brief Attempt to convert the given expression to a type which is accepted
5368/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005369///
Richard Smithccc11812013-05-21 19:05:48 +00005370/// This routine will attempt to convert an expression of class type to a
5371/// type accepted by the specified converter. In C++11 and before, the class
5372/// must have a single non-explicit conversion function converting to a matching
5373/// type. In C++1y, there can be multiple such conversion functions, but only
5374/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005375///
Douglas Gregor4799d032010-06-30 00:20:43 +00005376/// \param Loc The source location of the construct that requires the
5377/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005378///
James Dennett18348b62012-06-22 08:52:37 +00005379/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005380///
Richard Smithccc11812013-05-21 19:05:48 +00005381/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005382///
Douglas Gregor4799d032010-06-30 00:20:43 +00005383/// \returns The expression, converted to an integral or enumeration type if
5384/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005385ExprResult Sema::PerformContextualImplicitConversion(
5386 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005387 // We can't perform any more checking for type-dependent expressions.
5388 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005389 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
Eli Friedman1da70392012-01-26 00:26:18 +00005391 // Process placeholders immediately.
5392 if (From->hasPlaceholderType()) {
5393 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005394 if (result.isInvalid())
5395 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005396 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005397 }
5398
Richard Smithccc11812013-05-21 19:05:48 +00005399 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005400 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005401 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005402 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005403
5404 // FIXME: Check for missing '()' if T is a function type?
5405
Richard Smithccc11812013-05-21 19:05:48 +00005406 // We can only perform contextual implicit conversions on objects of class
5407 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005408 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005409 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005410 if (!Converter.Suppress)
5411 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005412 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005414
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005415 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005416 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005417 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005418 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005419
5420 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5421 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5422
Craig Toppere14c0f82014-03-12 04:55:44 +00005423 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005424 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005425 }
Richard Smithccc11812013-05-21 19:05:48 +00005426 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005427
5428 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005429 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005430
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005431 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005432 UnresolvedSet<4>
5433 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005434 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005435 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005436 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005437
Larisse Voufo236bec22013-06-10 06:50:24 +00005438 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005439 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005440
Larisse Voufo236bec22013-06-10 06:50:24 +00005441 // To check that there is only one target type, in C++1y:
5442 QualType ToType;
5443 bool HasUniqueTargetType = true;
5444
5445 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005446 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005447 NamedDecl *D = (*I)->getUnderlyingDecl();
5448 CXXConversionDecl *Conversion;
5449 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5450 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005451 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005452 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5453 else
5454 continue; // C++11 does not consider conversion operator templates(?).
5455 } else
5456 Conversion = cast<CXXConversionDecl>(D);
5457
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005458 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005459 "Conversion operator templates are considered potentially "
5460 "viable in C++1y");
5461
5462 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5463 if (Converter.match(CurToType) || ConvTemplate) {
5464
5465 if (Conversion->isExplicit()) {
5466 // FIXME: For C++1y, do we need this restriction?
5467 // cf. diagnoseNoViableConversion()
5468 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005469 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005470 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005471 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005472 if (ToType.isNull())
5473 ToType = CurToType.getUnqualifiedType();
5474 else if (HasUniqueTargetType &&
5475 (CurToType.getUnqualifiedType() != ToType))
5476 HasUniqueTargetType = false;
5477 }
5478 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005479 }
Richard Smith8dd34252012-02-04 07:07:42 +00005480 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005482
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005483 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005484 // C++1y [conv]p6:
5485 // ... An expression e of class type E appearing in such a context
5486 // is said to be contextually implicitly converted to a specified
5487 // type T and is well-formed if and only if e can be implicitly
5488 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005489 // for conversion functions whose return type is cv T or reference to
5490 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005491 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
Larisse Voufo236bec22013-06-10 06:50:24 +00005493 // If no unique T is found:
5494 if (ToType.isNull()) {
5495 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5496 HadMultipleCandidates,
5497 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005498 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005499 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501
Larisse Voufo236bec22013-06-10 06:50:24 +00005502 // If more than one unique Ts are found:
5503 if (!HasUniqueTargetType)
5504 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5505 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005506
Larisse Voufo236bec22013-06-10 06:50:24 +00005507 // If one unique T is found:
5508 // First, build a candidate set from the previously recorded
5509 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005510 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005511 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5512 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 // Then, perform overload resolution over the candidate set.
5515 OverloadCandidateSet::iterator Best;
5516 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5517 case OR_Success: {
5518 // Apply this conversion.
5519 DeclAccessPair Found =
5520 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5521 if (recordConversion(*this, Loc, From, Converter, T,
5522 HadMultipleCandidates, Found))
5523 return ExprError();
5524 break;
5525 }
5526 case OR_Ambiguous:
5527 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5528 ViableConversions);
5529 case OR_No_Viable_Function:
5530 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5531 HadMultipleCandidates,
5532 ExplicitConversions))
5533 return ExprError();
5534 // fall through 'OR_Deleted' case.
5535 case OR_Deleted:
5536 // We'll complain below about a non-integral condition type.
5537 break;
5538 }
5539 } else {
5540 switch (ViableConversions.size()) {
5541 case 0: {
5542 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5543 HadMultipleCandidates,
5544 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005545 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005546
Larisse Voufo236bec22013-06-10 06:50:24 +00005547 // We'll complain below about a non-integral condition type.
5548 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005549 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005550 case 1: {
5551 // Apply this conversion.
5552 DeclAccessPair Found = ViableConversions[0];
5553 if (recordConversion(*this, Loc, From, Converter, T,
5554 HadMultipleCandidates, Found))
5555 return ExprError();
5556 break;
5557 }
5558 default:
5559 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5560 ViableConversions);
5561 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Larisse Voufo236bec22013-06-10 06:50:24 +00005564 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005565}
5566
Richard Smith100b24a2014-04-17 01:52:14 +00005567/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5568/// an acceptable non-member overloaded operator for a call whose
5569/// arguments have types T1 (and, if non-empty, T2). This routine
5570/// implements the check in C++ [over.match.oper]p3b2 concerning
5571/// enumeration types.
5572static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5573 FunctionDecl *Fn,
5574 ArrayRef<Expr *> Args) {
5575 QualType T1 = Args[0]->getType();
5576 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5577
5578 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5579 return true;
5580
5581 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5582 return true;
5583
5584 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5585 if (Proto->getNumParams() < 1)
5586 return false;
5587
5588 if (T1->isEnumeralType()) {
5589 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5590 if (Context.hasSameUnqualifiedType(T1, ArgType))
5591 return true;
5592 }
5593
5594 if (Proto->getNumParams() < 2)
5595 return false;
5596
5597 if (!T2.isNull() && T2->isEnumeralType()) {
5598 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5599 if (Context.hasSameUnqualifiedType(T2, ArgType))
5600 return true;
5601 }
5602
5603 return false;
5604}
5605
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005606/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005607/// candidate functions, using the given function call arguments. If
5608/// @p SuppressUserConversions, then don't allow user-defined
5609/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005610///
James Dennett2a4d13c2012-06-15 07:13:21 +00005611/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005612/// based on an incomplete set of function arguments. This feature is used by
5613/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005614void
5615Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005616 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005617 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005618 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005619 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005620 bool PartialOverloading,
5621 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005622 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005623 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005624 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005625 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005626 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005627
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005629 if (!isa<CXXConstructorDecl>(Method)) {
5630 // If we get here, it's because we're calling a member function
5631 // that is named without a member access expression (e.g.,
5632 // "this->f") that was either written explicitly or created
5633 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005634 // function, e.g., X::f(). We use an empty type for the implied
5635 // object argument (C++ [over.call.func]p3), and the acting context
5636 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005637 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005638 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005639 Args, CandidateSet, SuppressUserConversions,
5640 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005641 return;
5642 }
5643 // We treat a constructor like a non-member function, since its object
5644 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005645 }
5646
Douglas Gregorff7028a2009-11-13 23:59:09 +00005647 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005648 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005649
Richard Smith100b24a2014-04-17 01:52:14 +00005650 // C++ [over.match.oper]p3:
5651 // if no operand has a class type, only those non-member functions in the
5652 // lookup set that have a first parameter of type T1 or "reference to
5653 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5654 // is a right operand) a second parameter of type T2 or "reference to
5655 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5656 // candidate functions.
5657 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5658 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5659 return;
5660
Richard Smith8b86f2d2013-11-04 01:48:18 +00005661 // C++11 [class.copy]p11: [DR1402]
5662 // A defaulted move constructor that is defined as deleted is ignored by
5663 // overload resolution.
5664 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5665 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5666 Constructor->isMoveConstructor())
5667 return;
5668
Douglas Gregor27381f32009-11-23 12:27:39 +00005669 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005670 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005671
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005672 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005673 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005674 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005675 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005676 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005677 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005678 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005679 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680
John McCall578a1f82014-12-14 01:46:53 +00005681 if (Constructor) {
5682 // C++ [class.copy]p3:
5683 // A member function template is never instantiated to perform the copy
5684 // of a class object to an object of its class type.
5685 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5686 if (Args.size() == 1 &&
5687 Constructor->isSpecializationCopyingObject() &&
5688 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5689 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5690 Candidate.Viable = false;
5691 Candidate.FailureKind = ovl_fail_illegal_constructor;
5692 return;
5693 }
5694 }
5695
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005696 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005697
5698 // (C++ 13.3.2p2): A candidate function having fewer than m
5699 // parameters is viable only if it has an ellipsis in its parameter
5700 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005701 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005702 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005703 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005704 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005705 return;
5706 }
5707
5708 // (C++ 13.3.2p2): A candidate function having more than m parameters
5709 // is viable only if the (m+1)st parameter has a default argument
5710 // (8.3.6). For the purposes of overload resolution, the
5711 // parameter list is truncated on the right, so that there are
5712 // exactly m parameters.
5713 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005714 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005715 // Not enough arguments.
5716 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005717 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005718 return;
5719 }
5720
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005721 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005722 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005723 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005724 // Skip the check for callers that are implicit members, because in this
5725 // case we may not yet know what the member's target is; the target is
5726 // inferred for the member automatically, based on the bases and fields of
5727 // the class.
5728 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005729 Candidate.Viable = false;
5730 Candidate.FailureKind = ovl_fail_bad_target;
5731 return;
5732 }
5733
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005734 // Determine the implicit conversion sequences for each of the
5735 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005736 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005737 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005738 // (C++ 13.3.2p3): for F to be a viable function, there shall
5739 // exist for each argument an implicit conversion sequence
5740 // (13.3.3.1) that converts that argument to the corresponding
5741 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005742 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005743 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005744 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005746 /*InOverloadResolution=*/true,
5747 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005748 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005749 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005750 if (Candidate.Conversions[ArgIdx].isBad()) {
5751 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005752 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005753 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005754 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005755 } else {
5756 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5757 // argument for which there is no corresponding parameter is
5758 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005759 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005760 }
5761 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005762
5763 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5764 Candidate.Viable = false;
5765 Candidate.FailureKind = ovl_fail_enable_if;
5766 Candidate.DeductionFailure.Data = FailedAttr;
5767 return;
5768 }
5769}
5770
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005771ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005772 bool IsInstance) {
5773 SmallVector<ObjCMethodDecl*, 4> Methods;
5774 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5775 return nullptr;
5776
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005777 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5778 bool Match = true;
5779 ObjCMethodDecl *Method = Methods[b];
5780 unsigned NumNamedArgs = Sel.getNumArgs();
5781 // Method might have more arguments than selector indicates. This is due
5782 // to addition of c-style arguments in method.
5783 if (Method->param_size() > NumNamedArgs)
5784 NumNamedArgs = Method->param_size();
5785 if (Args.size() < NumNamedArgs)
5786 continue;
5787
5788 for (unsigned i = 0; i < NumNamedArgs; i++) {
5789 // We can't do any type-checking on a type-dependent argument.
5790 if (Args[i]->isTypeDependent()) {
5791 Match = false;
5792 break;
5793 }
5794
5795 ParmVarDecl *param = Method->parameters()[i];
5796 Expr *argExpr = Args[i];
5797 assert(argExpr && "SelectBestMethod(): missing expression");
5798
5799 // Strip the unbridged-cast placeholder expression off unless it's
5800 // a consumed argument.
5801 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5802 !param->hasAttr<CFConsumedAttr>())
5803 argExpr = stripARCUnbridgedCast(argExpr);
5804
5805 // If the parameter is __unknown_anytype, move on to the next method.
5806 if (param->getType() == Context.UnknownAnyTy) {
5807 Match = false;
5808 break;
5809 }
George Burgess IV45461812015-10-11 20:13:20 +00005810
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005811 ImplicitConversionSequence ConversionState
5812 = TryCopyInitialization(*this, argExpr, param->getType(),
5813 /*SuppressUserConversions*/false,
5814 /*InOverloadResolution=*/true,
5815 /*AllowObjCWritebackConversion=*/
5816 getLangOpts().ObjCAutoRefCount,
5817 /*AllowExplicit*/false);
5818 if (ConversionState.isBad()) {
5819 Match = false;
5820 break;
5821 }
5822 }
5823 // Promote additional arguments to variadic methods.
5824 if (Match && Method->isVariadic()) {
5825 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5826 if (Args[i]->isTypeDependent()) {
5827 Match = false;
5828 break;
5829 }
5830 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5831 nullptr);
5832 if (Arg.isInvalid()) {
5833 Match = false;
5834 break;
5835 }
5836 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005837 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005838 // Check for extra arguments to non-variadic methods.
5839 if (Args.size() != NumNamedArgs)
5840 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005841 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5842 // Special case when selectors have no argument. In this case, select
5843 // one with the most general result type of 'id'.
5844 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5845 QualType ReturnT = Methods[b]->getReturnType();
5846 if (ReturnT->isObjCIdType())
5847 return Methods[b];
5848 }
5849 }
5850 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005851
5852 if (Match)
5853 return Method;
5854 }
5855 return nullptr;
5856}
5857
George Burgess IV2a6150d2015-10-16 01:17:38 +00005858// specific_attr_iterator iterates over enable_if attributes in reverse, and
5859// enable_if is order-sensitive. As a result, we need to reverse things
5860// sometimes. Size of 4 elements is arbitrary.
5861static SmallVector<EnableIfAttr *, 4>
5862getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5863 SmallVector<EnableIfAttr *, 4> Result;
5864 if (!Function->hasAttrs())
5865 return Result;
5866
5867 const auto &FuncAttrs = Function->getAttrs();
5868 for (Attr *Attr : FuncAttrs)
5869 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5870 Result.push_back(EnableIf);
5871
5872 std::reverse(Result.begin(), Result.end());
5873 return Result;
5874}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005875
5876EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5877 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005878 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5879 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005880 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005881
5882 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005883 SmallVector<Expr *, 16> ConvertedArgs;
5884 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005885 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005886
5887 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005888 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5889 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005890 !cast<CXXMethodDecl>(Function)->isStatic() &&
5891 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005892 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5893 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005894 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005895 Method, Method);
5896 if (R.isInvalid()) {
5897 InitializationFailed = true;
5898 break;
5899 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005900 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005901 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005902 } else {
5903 ExprResult R =
5904 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5905 Context,
5906 Function->getParamDecl(i)),
5907 SourceLocation(),
5908 Args[i]);
5909 if (R.isInvalid()) {
5910 InitializationFailed = true;
5911 break;
5912 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005913 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005914 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005915 }
5916 }
5917
5918 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005919 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005920
Nick Lewyckye283c552015-08-25 22:33:16 +00005921 // Push default arguments if needed.
5922 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5923 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5924 ParmVarDecl *P = Function->getParamDecl(i);
5925 ExprResult R = PerformCopyInitialization(
5926 InitializedEntity::InitializeParameter(Context,
5927 Function->getParamDecl(i)),
5928 SourceLocation(),
5929 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5930 : P->getDefaultArg());
5931 if (R.isInvalid()) {
5932 InitializationFailed = true;
5933 break;
5934 }
5935 ContainsValueDependentExpr |= R.get()->isValueDependent();
5936 ConvertedArgs.push_back(R.get());
5937 }
5938
5939 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005940 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00005941 }
5942
George Burgess IV2a6150d2015-10-16 01:17:38 +00005943 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005944 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005945 if (EIA->getCond()->isValueDependent()) {
5946 // Don't even try now, we'll examine it after instantiation.
5947 continue;
5948 }
5949
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005950 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005951 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5952 if (!ContainsValueDependentExpr)
5953 return EIA;
5954 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005955 return EIA;
5956 }
5957 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005958 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005959}
5960
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005961/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005962/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005963void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005964 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005965 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005966 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005967 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005968 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005969 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005970 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005972 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005973 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005974 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005975 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005976 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005977 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005978 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005979 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005980 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005981 } else {
John McCalla0296f72010-03-19 07:35:19 +00005982 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005983 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5984 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005985 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005986 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005987 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005988 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005989 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005990 CandidateSet, SuppressUserConversions,
5991 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005992 else
John McCalla0296f72010-03-19 07:35:19 +00005993 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005994 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005995 CandidateSet, SuppressUserConversions,
5996 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005997 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005998 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005999}
6000
John McCallf0f1cf02009-11-17 07:50:12 +00006001/// AddMethodCandidate - Adds a named decl (which is some kind of
6002/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006003void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006004 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006005 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006006 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006007 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006008 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006009 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006010 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006011
6012 if (isa<UsingShadowDecl>(Decl))
6013 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006014
John McCallf0f1cf02009-11-17 07:50:12 +00006015 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6016 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6017 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006018 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006019 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006020 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006021 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006022 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006023 } else {
John McCalla0296f72010-03-19 07:35:19 +00006024 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006025 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006026 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006027 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006028 }
6029}
6030
Douglas Gregor436424c2008-11-18 23:14:02 +00006031/// AddMethodCandidate - Adds the given C++ member function to the set
6032/// of candidate functions, using the given function call arguments
6033/// and the object argument (@c Object). For example, in a call
6034/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6035/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6036/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006037/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006038void
John McCalla0296f72010-03-19 07:35:19 +00006039Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006040 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006041 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006042 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006043 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006044 bool SuppressUserConversions,
6045 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006046 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006047 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006048 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006049 assert(!isa<CXXConstructorDecl>(Method) &&
6050 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006051
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006052 if (!CandidateSet.isNewCandidate(Method))
6053 return;
6054
Richard Smith8b86f2d2013-11-04 01:48:18 +00006055 // C++11 [class.copy]p23: [DR1402]
6056 // A defaulted move assignment operator that is defined as deleted is
6057 // ignored by overload resolution.
6058 if (Method->isDefaulted() && Method->isDeleted() &&
6059 Method->isMoveAssignmentOperator())
6060 return;
6061
Douglas Gregor27381f32009-11-23 12:27:39 +00006062 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006063 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006064
Douglas Gregor436424c2008-11-18 23:14:02 +00006065 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006066 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006067 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006068 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006069 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006070 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006071 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006072
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006073 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006074
6075 // (C++ 13.3.2p2): A candidate function having fewer than m
6076 // parameters is viable only if it has an ellipsis in its parameter
6077 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006078 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6079 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006080 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006081 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006082 return;
6083 }
6084
6085 // (C++ 13.3.2p2): A candidate function having more than m parameters
6086 // is viable only if the (m+1)st parameter has a default argument
6087 // (8.3.6). For the purposes of overload resolution, the
6088 // parameter list is truncated on the right, so that there are
6089 // exactly m parameters.
6090 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006091 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006092 // Not enough arguments.
6093 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006094 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006095 return;
6096 }
6097
6098 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006099
John McCall6e9f8f62009-12-03 04:06:58 +00006100 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006101 // The implicit object argument is ignored.
6102 Candidate.IgnoreObjectArgument = true;
6103 else {
6104 // Determine the implicit conversion sequence for the object
6105 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006106 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006107 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6108 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006109 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006110 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006111 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006112 return;
6113 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006114 }
6115
Eli Bendersky291a57e2014-09-25 23:59:08 +00006116 // (CUDA B.1): Check for invalid calls between targets.
6117 if (getLangOpts().CUDA)
6118 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6119 if (CheckCUDATarget(Caller, Method)) {
6120 Candidate.Viable = false;
6121 Candidate.FailureKind = ovl_fail_bad_target;
6122 return;
6123 }
6124
Douglas Gregor436424c2008-11-18 23:14:02 +00006125 // Determine the implicit conversion sequences for each of the
6126 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006127 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006128 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006129 // (C++ 13.3.2p3): for F to be a viable function, there shall
6130 // exist for each argument an implicit conversion sequence
6131 // (13.3.3.1) that converts that argument to the corresponding
6132 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006133 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006134 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006135 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006137 /*InOverloadResolution=*/true,
6138 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006139 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006140 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006141 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006142 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006143 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006144 }
6145 } else {
6146 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6147 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006148 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006149 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006150 }
6151 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006152
6153 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6154 Candidate.Viable = false;
6155 Candidate.FailureKind = ovl_fail_enable_if;
6156 Candidate.DeductionFailure.Data = FailedAttr;
6157 return;
6158 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006159}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006160
Douglas Gregor97628d62009-08-21 00:16:32 +00006161/// \brief Add a C++ member function template as a candidate to the candidate
6162/// set, using template argument deduction to produce an appropriate member
6163/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006164void
Douglas Gregor97628d62009-08-21 00:16:32 +00006165Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006166 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006167 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006168 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006169 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006170 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006171 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006172 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006173 bool SuppressUserConversions,
6174 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006175 if (!CandidateSet.isNewCandidate(MethodTmpl))
6176 return;
6177
Douglas Gregor97628d62009-08-21 00:16:32 +00006178 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006179 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006180 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006181 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006182 // candidate functions in the usual way.113) A given name can refer to one
6183 // or more function templates and also to a set of overloaded non-template
6184 // functions. In such a case, the candidate functions generated from each
6185 // function template are combined with the set of non-template candidate
6186 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006187 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006188 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006189 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006190 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006191 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006192 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006193 Candidate.FoundDecl = FoundDecl;
6194 Candidate.Function = MethodTmpl->getTemplatedDecl();
6195 Candidate.Viable = false;
6196 Candidate.FailureKind = ovl_fail_bad_deduction;
6197 Candidate.IsSurrogate = false;
6198 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006199 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006201 Info);
6202 return;
6203 }
Mike Stump11289f42009-09-09 15:08:12 +00006204
Douglas Gregor97628d62009-08-21 00:16:32 +00006205 // Add the function template specialization produced by template argument
6206 // deduction as a candidate.
6207 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006208 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006209 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006210 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006211 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006212 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006213}
6214
Douglas Gregor05155d82009-08-21 23:19:43 +00006215/// \brief Add a C++ function template specialization as a candidate
6216/// in the candidate set, using template argument deduction to produce
6217/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006218void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006219Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006220 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006221 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006222 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006223 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006224 bool SuppressUserConversions,
6225 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006226 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6227 return;
6228
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006229 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006230 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006231 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006232 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006233 // candidate functions in the usual way.113) A given name can refer to one
6234 // or more function templates and also to a set of overloaded non-template
6235 // functions. In such a case, the candidate functions generated from each
6236 // function template are combined with the set of non-template candidate
6237 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006238 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006239 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006240 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006241 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006242 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006243 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006244 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006245 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6246 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006247 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006248 Candidate.IsSurrogate = false;
6249 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006250 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006252 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006253 return;
6254 }
Mike Stump11289f42009-09-09 15:08:12 +00006255
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006256 // Add the function template specialization produced by template argument
6257 // deduction as a candidate.
6258 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006259 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006260 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006261}
Mike Stump11289f42009-09-09 15:08:12 +00006262
Douglas Gregor4b60a152013-11-07 22:34:54 +00006263/// Determine whether this is an allowable conversion from the result
6264/// of an explicit conversion operator to the expected type, per C++
6265/// [over.match.conv]p1 and [over.match.ref]p1.
6266///
6267/// \param ConvType The return type of the conversion function.
6268///
6269/// \param ToType The type we are converting to.
6270///
6271/// \param AllowObjCPointerConversion Allow a conversion from one
6272/// Objective-C pointer to another.
6273///
6274/// \returns true if the conversion is allowable, false otherwise.
6275static bool isAllowableExplicitConversion(Sema &S,
6276 QualType ConvType, QualType ToType,
6277 bool AllowObjCPointerConversion) {
6278 QualType ToNonRefType = ToType.getNonReferenceType();
6279
6280 // Easy case: the types are the same.
6281 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6282 return true;
6283
6284 // Allow qualification conversions.
6285 bool ObjCLifetimeConversion;
6286 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6287 ObjCLifetimeConversion))
6288 return true;
6289
6290 // If we're not allowed to consider Objective-C pointer conversions,
6291 // we're done.
6292 if (!AllowObjCPointerConversion)
6293 return false;
6294
6295 // Is this an Objective-C pointer conversion?
6296 bool IncompatibleObjC = false;
6297 QualType ConvertedType;
6298 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6299 IncompatibleObjC);
6300}
6301
Douglas Gregora1f013e2008-11-07 22:36:19 +00006302/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006303/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006304/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006305/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006306/// (which may or may not be the same type as the type that the
6307/// conversion function produces).
6308void
6309Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006310 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006311 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006312 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006313 OverloadCandidateSet& CandidateSet,
6314 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006315 assert(!Conversion->getDescribedFunctionTemplate() &&
6316 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006317 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006318 if (!CandidateSet.isNewCandidate(Conversion))
6319 return;
6320
Richard Smith2a7d4812013-05-04 07:00:32 +00006321 // If the conversion function has an undeduced return type, trigger its
6322 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006323 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006324 if (DeduceReturnType(Conversion, From->getExprLoc()))
6325 return;
6326 ConvType = Conversion->getConversionType().getNonReferenceType();
6327 }
6328
Richard Smith089c3162013-09-21 21:55:46 +00006329 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6330 // operator is only a candidate if its return type is the target type or
6331 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006332 if (Conversion->isExplicit() &&
6333 !isAllowableExplicitConversion(*this, ConvType, ToType,
6334 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006335 return;
6336
Douglas Gregor27381f32009-11-23 12:27:39 +00006337 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006338 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006339
Douglas Gregora1f013e2008-11-07 22:36:19 +00006340 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006341 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006342 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006343 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006344 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006345 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006346 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006347 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006348 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006349 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006350 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006351
Douglas Gregor6affc782010-08-19 15:37:02 +00006352 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006353 // For conversion functions, the function is considered to be a member of
6354 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006355 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006356 //
6357 // Determine the implicit conversion sequence for the implicit
6358 // object parameter.
6359 QualType ImplicitParamType = From->getType();
6360 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6361 ImplicitParamType = FromPtrType->getPointeeType();
6362 CXXRecordDecl *ConversionContext
6363 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006365 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006366 = TryObjectArgumentInitialization(*this, From->getType(),
6367 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006368 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006369
John McCall0d1da222010-01-12 00:44:57 +00006370 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006371 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006372 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006373 return;
6374 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006375
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006376 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006377 // derived to base as such conversions are given Conversion Rank. They only
6378 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6379 QualType FromCanon
6380 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6381 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6382 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6383 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006384 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006385 return;
6386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006387
Douglas Gregora1f013e2008-11-07 22:36:19 +00006388 // To determine what the conversion from the result of calling the
6389 // conversion function to the type we're eventually trying to
6390 // convert to (ToType), we need to synthesize a call to the
6391 // conversion function and attempt copy initialization from it. This
6392 // makes sure that we get the right semantics with respect to
6393 // lvalues/rvalues and the type. Fortunately, we can allocate this
6394 // call on the stack and we don't need its arguments to be
6395 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006396 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006397 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006398 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6399 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006400 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006401 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006402
Richard Smith48d24642011-07-13 22:53:21 +00006403 QualType ConversionType = Conversion->getConversionType();
6404 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006405 Candidate.Viable = false;
6406 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6407 return;
6408 }
6409
Richard Smith48d24642011-07-13 22:53:21 +00006410 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006411
Mike Stump11289f42009-09-09 15:08:12 +00006412 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006413 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6414 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006415 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006416 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006417 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006418 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006419 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006420 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006421 /*InOverloadResolution=*/false,
6422 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006423
John McCall0d1da222010-01-12 00:44:57 +00006424 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006425 case ImplicitConversionSequence::StandardConversion:
6426 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006428 // C++ [over.ics.user]p3:
6429 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006431 // shall have exact match rank.
6432 if (Conversion->getPrimaryTemplate() &&
6433 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6434 Candidate.Viable = false;
6435 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006436 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
Douglas Gregorcba72b12011-01-21 05:18:22 +00006439 // C++0x [dcl.init.ref]p5:
6440 // In the second case, if the reference is an rvalue reference and
6441 // the second standard conversion sequence of the user-defined
6442 // conversion sequence includes an lvalue-to-rvalue conversion, the
6443 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006445 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6446 Candidate.Viable = false;
6447 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006448 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006449 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006450 break;
6451
6452 case ImplicitConversionSequence::BadConversion:
6453 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006454 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006455 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006456
6457 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006458 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006459 "Can only end up with a standard conversion sequence or failure");
6460 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006461
Craig Topper5fc8fc22014-08-27 06:28:36 +00006462 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006463 Candidate.Viable = false;
6464 Candidate.FailureKind = ovl_fail_enable_if;
6465 Candidate.DeductionFailure.Data = FailedAttr;
6466 return;
6467 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006468}
6469
Douglas Gregor05155d82009-08-21 23:19:43 +00006470/// \brief Adds a conversion function template specialization
6471/// candidate to the overload set, using template argument deduction
6472/// to deduce the template arguments of the conversion function
6473/// template from the type that we are converting to (C++
6474/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006475void
Douglas Gregor05155d82009-08-21 23:19:43 +00006476Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006477 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006478 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006479 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006480 OverloadCandidateSet &CandidateSet,
6481 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006482 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6483 "Only conversion function templates permitted here");
6484
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006485 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6486 return;
6487
Craig Toppere6706e42012-09-19 02:26:47 +00006488 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006489 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006490 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006491 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006492 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006493 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006494 Candidate.FoundDecl = FoundDecl;
6495 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6496 Candidate.Viable = false;
6497 Candidate.FailureKind = ovl_fail_bad_deduction;
6498 Candidate.IsSurrogate = false;
6499 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006500 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006501 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006502 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006503 return;
6504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505
Douglas Gregor05155d82009-08-21 23:19:43 +00006506 // Add the conversion function template specialization produced by
6507 // template argument deduction as a candidate.
6508 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006509 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006510 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006511}
6512
Douglas Gregorab7897a2008-11-19 22:57:39 +00006513/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6514/// converts the given @c Object to a function pointer via the
6515/// conversion function @c Conversion, and then attempts to call it
6516/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6517/// the type of function that we'll eventually be calling.
6518void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006519 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006520 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006521 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006522 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006523 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006524 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006525 if (!CandidateSet.isNewCandidate(Conversion))
6526 return;
6527
Douglas Gregor27381f32009-11-23 12:27:39 +00006528 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006529 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006530
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006531 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006532 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006533 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006534 Candidate.Surrogate = Conversion;
6535 Candidate.Viable = true;
6536 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006537 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006538 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006539
6540 // Determine the implicit conversion sequence for the implicit
6541 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006542 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006544 Object->Classify(Context),
6545 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006546 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006547 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006548 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006549 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006550 return;
6551 }
6552
6553 // The first conversion is actually a user-defined conversion whose
6554 // first conversion is ObjectInit's standard conversion (which is
6555 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006556 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006557 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006558 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006559 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006560 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006561 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006562 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006563 = Candidate.Conversions[0].UserDefined.Before;
6564 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6565
Mike Stump11289f42009-09-09 15:08:12 +00006566 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006567 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006568
6569 // (C++ 13.3.2p2): A candidate function having fewer than m
6570 // parameters is viable only if it has an ellipsis in its parameter
6571 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006572 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006573 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006574 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006575 return;
6576 }
6577
6578 // Function types don't have any default arguments, so just check if
6579 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006580 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006581 // Not enough arguments.
6582 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006583 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006584 return;
6585 }
6586
6587 // Determine the implicit conversion sequences for each of the
6588 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006589 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006590 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006591 // (C++ 13.3.2p3): for F to be a viable function, there shall
6592 // exist for each argument an implicit conversion sequence
6593 // (13.3.3.1) that converts that argument to the corresponding
6594 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006595 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006596 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006598 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006599 /*InOverloadResolution=*/false,
6600 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006601 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006602 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006603 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006604 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006605 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006606 }
6607 } else {
6608 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6609 // argument for which there is no corresponding parameter is
6610 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006611 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006612 }
6613 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006614
Craig Topper5fc8fc22014-08-27 06:28:36 +00006615 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006616 Candidate.Viable = false;
6617 Candidate.FailureKind = ovl_fail_enable_if;
6618 Candidate.DeductionFailure.Data = FailedAttr;
6619 return;
6620 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006621}
6622
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006623/// \brief Add overload candidates for overloaded operators that are
6624/// member functions.
6625///
6626/// Add the overloaded operator candidates that are member functions
6627/// for the operator Op that was used in an operator expression such
6628/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6629/// CandidateSet will store the added overload candidates. (C++
6630/// [over.match.oper]).
6631void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6632 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006633 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006634 OverloadCandidateSet& CandidateSet,
6635 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006636 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6637
6638 // C++ [over.match.oper]p3:
6639 // For a unary operator @ with an operand of a type whose
6640 // cv-unqualified version is T1, and for a binary operator @ with
6641 // a left operand of a type whose cv-unqualified version is T1 and
6642 // a right operand of a type whose cv-unqualified version is T2,
6643 // three sets of candidate functions, designated member
6644 // candidates, non-member candidates and built-in candidates, are
6645 // constructed as follows:
6646 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006647
Richard Smith0feaf0c2013-04-20 12:41:22 +00006648 // -- If T1 is a complete class type or a class currently being
6649 // defined, the set of member candidates is the result of the
6650 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6651 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006652 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006653 // Complete the type if it can be completed.
6654 RequireCompleteType(OpLoc, T1, 0);
6655 // If the type is neither complete nor being defined, bail out now.
6656 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006657 return;
Mike Stump11289f42009-09-09 15:08:12 +00006658
John McCall27b18f82009-11-17 02:14:36 +00006659 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6660 LookupQualifiedName(Operators, T1Rec->getDecl());
6661 Operators.suppressDiagnostics();
6662
Mike Stump11289f42009-09-09 15:08:12 +00006663 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006664 OperEnd = Operators.end();
6665 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006666 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006667 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006668 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006669 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006670 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006671 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006672 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006673}
6674
Douglas Gregora11693b2008-11-12 17:17:38 +00006675/// AddBuiltinCandidate - Add a candidate for a built-in
6676/// operator. ResultTy and ParamTys are the result and parameter types
6677/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006678/// arguments being passed to the candidate. IsAssignmentOperator
6679/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006680/// operator. NumContextualBoolArguments is the number of arguments
6681/// (at the beginning of the argument list) that will be contextually
6682/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006683void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006684 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006685 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006686 bool IsAssignmentOperator,
6687 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006688 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006689 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006690
Douglas Gregora11693b2008-11-12 17:17:38 +00006691 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006692 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006693 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6694 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006695 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006696 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006697 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006698 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006699 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6700
6701 // Determine the implicit conversion sequences for each of the
6702 // arguments.
6703 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006704 Candidate.ExplicitCallArguments = Args.size();
6705 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006706 // C++ [over.match.oper]p4:
6707 // For the built-in assignment operators, conversions of the
6708 // left operand are restricted as follows:
6709 // -- no temporaries are introduced to hold the left operand, and
6710 // -- no user-defined conversions are applied to the left
6711 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006712 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006713 //
6714 // We block these conversions by turning off user-defined
6715 // conversions, since that is the only way that initialization of
6716 // a reference to a non-class type can occur from something that
6717 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006718 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006719 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006720 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006721 Candidate.Conversions[ArgIdx]
6722 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006723 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006724 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006725 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006726 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006727 /*InOverloadResolution=*/false,
6728 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006729 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006730 }
John McCall0d1da222010-01-12 00:44:57 +00006731 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006732 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006733 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006734 break;
6735 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006736 }
6737}
6738
Craig Toppercd7b0332013-07-01 06:29:40 +00006739namespace {
6740
Douglas Gregora11693b2008-11-12 17:17:38 +00006741/// BuiltinCandidateTypeSet - A set of types that will be used for the
6742/// candidate operator functions for built-in operators (C++
6743/// [over.built]). The types are separated into pointer types and
6744/// enumeration types.
6745class BuiltinCandidateTypeSet {
6746 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006747 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006748
6749 /// PointerTypes - The set of pointer types that will be used in the
6750 /// built-in candidates.
6751 TypeSet PointerTypes;
6752
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006753 /// MemberPointerTypes - The set of member pointer types that will be
6754 /// used in the built-in candidates.
6755 TypeSet MemberPointerTypes;
6756
Douglas Gregora11693b2008-11-12 17:17:38 +00006757 /// EnumerationTypes - The set of enumeration types that will be
6758 /// used in the built-in candidates.
6759 TypeSet EnumerationTypes;
6760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006762 /// candidates.
6763 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006764
6765 /// \brief A flag indicating non-record types are viable candidates
6766 bool HasNonRecordTypes;
6767
6768 /// \brief A flag indicating whether either arithmetic or enumeration types
6769 /// were present in the candidate set.
6770 bool HasArithmeticOrEnumeralTypes;
6771
Douglas Gregor80af3132011-05-21 23:15:46 +00006772 /// \brief A flag indicating whether the nullptr type was present in the
6773 /// candidate set.
6774 bool HasNullPtrType;
6775
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006776 /// Sema - The semantic analysis instance where we are building the
6777 /// candidate type set.
6778 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006779
Douglas Gregora11693b2008-11-12 17:17:38 +00006780 /// Context - The AST context in which we will build the type sets.
6781 ASTContext &Context;
6782
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006783 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6784 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006785 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006786
6787public:
6788 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006789 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006790
Mike Stump11289f42009-09-09 15:08:12 +00006791 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006792 : HasNonRecordTypes(false),
6793 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006794 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006795 SemaRef(SemaRef),
6796 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006797
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006798 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006799 SourceLocation Loc,
6800 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006801 bool AllowExplicitConversions,
6802 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006803
6804 /// pointer_begin - First pointer type found;
6805 iterator pointer_begin() { return PointerTypes.begin(); }
6806
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006807 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006808 iterator pointer_end() { return PointerTypes.end(); }
6809
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006810 /// member_pointer_begin - First member pointer type found;
6811 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6812
6813 /// member_pointer_end - Past the last member pointer type found;
6814 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6815
Douglas Gregora11693b2008-11-12 17:17:38 +00006816 /// enumeration_begin - First enumeration type found;
6817 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6818
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006819 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006820 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006822 iterator vector_begin() { return VectorTypes.begin(); }
6823 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006824
6825 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6826 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006827 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006828};
6829
Craig Toppercd7b0332013-07-01 06:29:40 +00006830} // end anonymous namespace
6831
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006832/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006833/// the set of pointer types along with any more-qualified variants of
6834/// that type. For example, if @p Ty is "int const *", this routine
6835/// will add "int const *", "int const volatile *", "int const
6836/// restrict *", and "int const volatile restrict *" to the set of
6837/// pointer types. Returns true if the add of @p Ty itself succeeded,
6838/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006839///
6840/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006841bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006842BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6843 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006844
Douglas Gregora11693b2008-11-12 17:17:38 +00006845 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006846 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006847 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006849 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006850 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006851 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006852 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006853 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6854 PointeeTy = PTy->getPointeeType();
6855 buildObjCPtr = true;
6856 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006857 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006858 }
6859
Sebastian Redl4990a632009-11-18 20:39:26 +00006860 // Don't add qualified variants of arrays. For one, they're not allowed
6861 // (the qualifier would sink to the element type), and for another, the
6862 // only overload situation where it matters is subscript or pointer +- int,
6863 // and those shouldn't have qualifier variants anyway.
6864 if (PointeeTy->isArrayType())
6865 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006866
John McCall8ccfcb52009-09-24 19:53:00 +00006867 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006868 bool hasVolatile = VisibleQuals.hasVolatile();
6869 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870
John McCall8ccfcb52009-09-24 19:53:00 +00006871 // Iterate through all strict supersets of BaseCVR.
6872 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6873 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006874 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006875 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006876
6877 // Skip over restrict if no restrict found anywhere in the types, or if
6878 // the type cannot be restrict-qualified.
6879 if ((CVR & Qualifiers::Restrict) &&
6880 (!hasRestrict ||
6881 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6882 continue;
6883
6884 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006885 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006886
6887 // Build qualified pointer type.
6888 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006889 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006890 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006891 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006892 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6893
6894 // Insert qualified pointer type.
6895 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006896 }
6897
6898 return true;
6899}
6900
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006901/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6902/// to the set of pointer types along with any more-qualified variants of
6903/// that type. For example, if @p Ty is "int const *", this routine
6904/// will add "int const *", "int const volatile *", "int const
6905/// restrict *", and "int const volatile restrict *" to the set of
6906/// pointer types. Returns true if the add of @p Ty itself succeeded,
6907/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006908///
6909/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006910bool
6911BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6912 QualType Ty) {
6913 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006914 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006915 return false;
6916
John McCall8ccfcb52009-09-24 19:53:00 +00006917 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6918 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006919
John McCall8ccfcb52009-09-24 19:53:00 +00006920 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006921 // Don't add qualified variants of arrays. For one, they're not allowed
6922 // (the qualifier would sink to the element type), and for another, the
6923 // only overload situation where it matters is subscript or pointer +- int,
6924 // and those shouldn't have qualifier variants anyway.
6925 if (PointeeTy->isArrayType())
6926 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006927 const Type *ClassTy = PointerTy->getClass();
6928
6929 // Iterate through all strict supersets of the pointee type's CVR
6930 // qualifiers.
6931 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6932 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6933 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
John McCall8ccfcb52009-09-24 19:53:00 +00006935 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006936 MemberPointerTypes.insert(
6937 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006938 }
6939
6940 return true;
6941}
6942
Douglas Gregora11693b2008-11-12 17:17:38 +00006943/// AddTypesConvertedFrom - Add each of the types to which the type @p
6944/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006945/// primarily interested in pointer types and enumeration types. We also
6946/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006947/// AllowUserConversions is true if we should look at the conversion
6948/// functions of a class type, and AllowExplicitConversions if we
6949/// should also include the explicit conversion functions of a class
6950/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006951void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006952BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006953 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006954 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006955 bool AllowExplicitConversions,
6956 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006957 // Only deal with canonical types.
6958 Ty = Context.getCanonicalType(Ty);
6959
6960 // Look through reference types; they aren't part of the type of an
6961 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006962 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006963 Ty = RefTy->getPointeeType();
6964
John McCall33ddac02011-01-19 10:06:00 +00006965 // If we're dealing with an array type, decay to the pointer.
6966 if (Ty->isArrayType())
6967 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6968
6969 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006970 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006971
Chandler Carruth00a38332010-12-13 01:44:01 +00006972 // Flag if we ever add a non-record type.
6973 const RecordType *TyRec = Ty->getAs<RecordType>();
6974 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6975
Chandler Carruth00a38332010-12-13 01:44:01 +00006976 // Flag if we encounter an arithmetic type.
6977 HasArithmeticOrEnumeralTypes =
6978 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6979
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006980 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6981 PointerTypes.insert(Ty);
6982 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006983 // Insert our type, and its more-qualified variants, into the set
6984 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006985 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006986 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006987 } else if (Ty->isMemberPointerType()) {
6988 // Member pointers are far easier, since the pointee can't be converted.
6989 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6990 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006991 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006992 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006993 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006994 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006995 // We treat vector types as arithmetic types in many contexts as an
6996 // extension.
6997 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006998 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006999 } else if (Ty->isNullPtrType()) {
7000 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007001 } else if (AllowUserConversions && TyRec) {
7002 // No conversion functions in incomplete types.
7003 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
7004 return;
Mike Stump11289f42009-09-09 15:08:12 +00007005
Chandler Carruth00a38332010-12-13 01:44:01 +00007006 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007007 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007008 if (isa<UsingShadowDecl>(D))
7009 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007010
Chandler Carruth00a38332010-12-13 01:44:01 +00007011 // Skip conversion function templates; they don't tell us anything
7012 // about which builtin types we can convert to.
7013 if (isa<FunctionTemplateDecl>(D))
7014 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007015
Chandler Carruth00a38332010-12-13 01:44:01 +00007016 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7017 if (AllowExplicitConversions || !Conv->isExplicit()) {
7018 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7019 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007020 }
7021 }
7022 }
7023}
7024
Douglas Gregor84605ae2009-08-24 13:43:27 +00007025/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7026/// the volatile- and non-volatile-qualified assignment operators for the
7027/// given type to the candidate set.
7028static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7029 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007030 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007031 OverloadCandidateSet &CandidateSet) {
7032 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007033
Douglas Gregor84605ae2009-08-24 13:43:27 +00007034 // T& operator=(T&, T)
7035 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7036 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007038 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007039
Douglas Gregor84605ae2009-08-24 13:43:27 +00007040 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7041 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007042 ParamTypes[0]
7043 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007044 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007046 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007047 }
7048}
Mike Stump11289f42009-09-09 15:08:12 +00007049
Sebastian Redl1054fae2009-10-25 17:03:50 +00007050/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7051/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007052static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7053 Qualifiers VRQuals;
7054 const RecordType *TyRec;
7055 if (const MemberPointerType *RHSMPType =
7056 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007057 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007058 else
7059 TyRec = ArgExpr->getType()->getAs<RecordType>();
7060 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007061 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007062 VRQuals.addVolatile();
7063 VRQuals.addRestrict();
7064 return VRQuals;
7065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007067 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007068 if (!ClassDecl->hasDefinition())
7069 return VRQuals;
7070
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007071 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007072 if (isa<UsingShadowDecl>(D))
7073 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7074 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007075 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7076 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7077 CanTy = ResTypeRef->getPointeeType();
7078 // Need to go down the pointer/mempointer chain and add qualifiers
7079 // as see them.
7080 bool done = false;
7081 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007082 if (CanTy.isRestrictQualified())
7083 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007084 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7085 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007087 CanTy->getAs<MemberPointerType>())
7088 CanTy = ResTypeMPtr->getPointeeType();
7089 else
7090 done = true;
7091 if (CanTy.isVolatileQualified())
7092 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007093 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7094 return VRQuals;
7095 }
7096 }
7097 }
7098 return VRQuals;
7099}
John McCall52872982010-11-13 05:51:15 +00007100
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007101namespace {
John McCall52872982010-11-13 05:51:15 +00007102
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007103/// \brief Helper class to manage the addition of builtin operator overload
7104/// candidates. It provides shared state and utility methods used throughout
7105/// the process, as well as a helper method to add each group of builtin
7106/// operator overloads from the standard to a candidate set.
7107class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007108 // Common instance state available to all overload candidate addition methods.
7109 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007110 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007111 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007112 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007113 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007114 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007115
Chandler Carruthc6586e52010-12-12 10:35:00 +00007116 // Define some constants used to index and iterate over the arithemetic types
7117 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007118 // The "promoted arithmetic types" are the arithmetic
7119 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007120 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007121 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007122 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007123 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007124 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007125 LastPromotedArithmeticType = 11;
7126 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007127
Chandler Carruthc6586e52010-12-12 10:35:00 +00007128 /// \brief Get the canonical type for a given arithmetic type index.
7129 CanQualType getArithmeticType(unsigned index) {
7130 assert(index < NumArithmeticTypes);
7131 static CanQualType ASTContext::* const
7132 ArithmeticTypes[NumArithmeticTypes] = {
7133 // Start of promoted types.
7134 &ASTContext::FloatTy,
7135 &ASTContext::DoubleTy,
7136 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007137
Chandler Carruthc6586e52010-12-12 10:35:00 +00007138 // Start of integral types.
7139 &ASTContext::IntTy,
7140 &ASTContext::LongTy,
7141 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007142 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007143 &ASTContext::UnsignedIntTy,
7144 &ASTContext::UnsignedLongTy,
7145 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007146 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007147 // End of promoted types.
7148
7149 &ASTContext::BoolTy,
7150 &ASTContext::CharTy,
7151 &ASTContext::WCharTy,
7152 &ASTContext::Char16Ty,
7153 &ASTContext::Char32Ty,
7154 &ASTContext::SignedCharTy,
7155 &ASTContext::ShortTy,
7156 &ASTContext::UnsignedCharTy,
7157 &ASTContext::UnsignedShortTy,
7158 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007159 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007160 };
7161 return S.Context.*ArithmeticTypes[index];
7162 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007163
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007164 /// \brief Gets the canonical type resulting from the usual arithemetic
7165 /// converions for the given arithmetic types.
7166 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7167 // Accelerator table for performing the usual arithmetic conversions.
7168 // The rules are basically:
7169 // - if either is floating-point, use the wider floating-point
7170 // - if same signedness, use the higher rank
7171 // - if same size, use unsigned of the higher rank
7172 // - use the larger type
7173 // These rules, together with the axiom that higher ranks are
7174 // never smaller, are sufficient to precompute all of these results
7175 // *except* when dealing with signed types of higher rank.
7176 // (we could precompute SLL x UI for all known platforms, but it's
7177 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007178 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007179 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007180 Dep=-1,
7181 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007182 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007183 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007184 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007185/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7186/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7187/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7188/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7189/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7190/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7191/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7192/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7193/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7194/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7195/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007196 };
7197
7198 assert(L < LastPromotedArithmeticType);
7199 assert(R < LastPromotedArithmeticType);
7200 int Idx = ConversionsTable[L][R];
7201
7202 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007203 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007204
7205 // Slow path: we need to compare widths.
7206 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007207 CanQualType LT = getArithmeticType(L),
7208 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007209 unsigned LW = S.Context.getIntWidth(LT),
7210 RW = S.Context.getIntWidth(RT);
7211
7212 // If they're different widths, use the signed type.
7213 if (LW > RW) return LT;
7214 else if (LW < RW) return RT;
7215
7216 // Otherwise, use the unsigned type of the signed type's rank.
7217 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7218 assert(L == SLL || R == SLL);
7219 return S.Context.UnsignedLongLongTy;
7220 }
7221
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007222 /// \brief Helper method to factor out the common pattern of adding overloads
7223 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007224 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007225 bool HasVolatile,
7226 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007227 QualType ParamTypes[2] = {
7228 S.Context.getLValueReferenceType(CandidateTy),
7229 S.Context.IntTy
7230 };
7231
7232 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007233 if (Args.size() == 1)
7234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007235 else
Richard Smithe54c3072013-05-05 15:51:06 +00007236 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237
7238 // Use a heuristic to reduce number of builtin candidates in the set:
7239 // add volatile version only if there are conversions to a volatile type.
7240 if (HasVolatile) {
7241 ParamTypes[0] =
7242 S.Context.getLValueReferenceType(
7243 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007244 if (Args.size() == 1)
7245 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007246 else
Richard Smithe54c3072013-05-05 15:51:06 +00007247 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007248 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007249
7250 // Add restrict version only if there are conversions to a restrict type
7251 // and our candidate type is a non-restrict-qualified pointer.
7252 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7253 !CandidateTy.isRestrictQualified()) {
7254 ParamTypes[0]
7255 = S.Context.getLValueReferenceType(
7256 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007257 if (Args.size() == 1)
7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007259 else
Richard Smithe54c3072013-05-05 15:51:06 +00007260 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007261
7262 if (HasVolatile) {
7263 ParamTypes[0]
7264 = S.Context.getLValueReferenceType(
7265 S.Context.getCVRQualifiedType(CandidateTy,
7266 (Qualifiers::Volatile |
7267 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007268 if (Args.size() == 1)
7269 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007270 else
Richard Smithe54c3072013-05-05 15:51:06 +00007271 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007272 }
7273 }
7274
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 }
7276
7277public:
7278 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007279 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007280 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007281 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007282 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007284 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007285 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007286 HasArithmeticOrEnumeralCandidateType(
7287 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007288 CandidateTypes(CandidateTypes),
7289 CandidateSet(CandidateSet) {
7290 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007291 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007292 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007293 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007294 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007295 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007296 assert(getArithmeticType(FirstPromotedArithmeticType)
7297 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007298 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007299 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007300 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007301 "Invalid last promoted arithmetic type");
7302 }
7303
7304 // C++ [over.built]p3:
7305 //
7306 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7307 // is either volatile or empty, there exist candidate operator
7308 // functions of the form
7309 //
7310 // VQ T& operator++(VQ T&);
7311 // T operator++(VQ T&, int);
7312 //
7313 // C++ [over.built]p4:
7314 //
7315 // For every pair (T, VQ), where T is an arithmetic type other
7316 // than bool, and VQ is either volatile or empty, there exist
7317 // candidate operator functions of the form
7318 //
7319 // VQ T& operator--(VQ T&);
7320 // T operator--(VQ T&, int);
7321 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007322 if (!HasArithmeticOrEnumeralCandidateType)
7323 return;
7324
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007325 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7326 Arith < NumArithmeticTypes; ++Arith) {
7327 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007328 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007329 VisibleTypeConversionsQuals.hasVolatile(),
7330 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 }
7332 }
7333
7334 // C++ [over.built]p5:
7335 //
7336 // For every pair (T, VQ), where T is a cv-qualified or
7337 // cv-unqualified object type, and VQ is either volatile or
7338 // empty, there exist candidate operator functions of the form
7339 //
7340 // T*VQ& operator++(T*VQ&);
7341 // T*VQ& operator--(T*VQ&);
7342 // T* operator++(T*VQ&, int);
7343 // T* operator--(T*VQ&, int);
7344 void addPlusPlusMinusMinusPointerOverloads() {
7345 for (BuiltinCandidateTypeSet::iterator
7346 Ptr = CandidateTypes[0].pointer_begin(),
7347 PtrEnd = CandidateTypes[0].pointer_end();
7348 Ptr != PtrEnd; ++Ptr) {
7349 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007350 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 continue;
7352
7353 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007354 (!(*Ptr).isVolatileQualified() &&
7355 VisibleTypeConversionsQuals.hasVolatile()),
7356 (!(*Ptr).isRestrictQualified() &&
7357 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 }
7359 }
7360
7361 // C++ [over.built]p6:
7362 // For every cv-qualified or cv-unqualified object type T, there
7363 // exist candidate operator functions of the form
7364 //
7365 // T& operator*(T*);
7366 //
7367 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007368 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007369 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007370 // T& operator*(T*);
7371 void addUnaryStarPointerOverloads() {
7372 for (BuiltinCandidateTypeSet::iterator
7373 Ptr = CandidateTypes[0].pointer_begin(),
7374 PtrEnd = CandidateTypes[0].pointer_end();
7375 Ptr != PtrEnd; ++Ptr) {
7376 QualType ParamTy = *Ptr;
7377 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007378 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7379 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007380
Douglas Gregor02824322011-01-26 19:30:28 +00007381 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7382 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7383 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007384
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007385 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007386 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007387 }
7388 }
7389
7390 // C++ [over.built]p9:
7391 // For every promoted arithmetic type T, there exist candidate
7392 // operator functions of the form
7393 //
7394 // T operator+(T);
7395 // T operator-(T);
7396 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007397 if (!HasArithmeticOrEnumeralCandidateType)
7398 return;
7399
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007400 for (unsigned Arith = FirstPromotedArithmeticType;
7401 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007402 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007403 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 }
7405
7406 // Extension: We also add these operators for vector types.
7407 for (BuiltinCandidateTypeSet::iterator
7408 Vec = CandidateTypes[0].vector_begin(),
7409 VecEnd = CandidateTypes[0].vector_end();
7410 Vec != VecEnd; ++Vec) {
7411 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007412 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007413 }
7414 }
7415
7416 // C++ [over.built]p8:
7417 // For every type T, there exist candidate operator functions of
7418 // the form
7419 //
7420 // T* operator+(T*);
7421 void addUnaryPlusPointerOverloads() {
7422 for (BuiltinCandidateTypeSet::iterator
7423 Ptr = CandidateTypes[0].pointer_begin(),
7424 PtrEnd = CandidateTypes[0].pointer_end();
7425 Ptr != PtrEnd; ++Ptr) {
7426 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007427 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 }
7429 }
7430
7431 // C++ [over.built]p10:
7432 // For every promoted integral type T, there exist candidate
7433 // operator functions of the form
7434 //
7435 // T operator~(T);
7436 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007437 if (!HasArithmeticOrEnumeralCandidateType)
7438 return;
7439
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007440 for (unsigned Int = FirstPromotedIntegralType;
7441 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007442 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007443 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007444 }
7445
7446 // Extension: We also add this operator for vector types.
7447 for (BuiltinCandidateTypeSet::iterator
7448 Vec = CandidateTypes[0].vector_begin(),
7449 VecEnd = CandidateTypes[0].vector_end();
7450 Vec != VecEnd; ++Vec) {
7451 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007452 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007453 }
7454 }
7455
7456 // C++ [over.match.oper]p16:
7457 // For every pointer to member type T, there exist candidate operator
7458 // functions of the form
7459 //
7460 // bool operator==(T,T);
7461 // bool operator!=(T,T);
7462 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7463 /// Set of (canonical) types that we've already handled.
7464 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7465
Richard Smithe54c3072013-05-05 15:51:06 +00007466 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 for (BuiltinCandidateTypeSet::iterator
7468 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7469 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7470 MemPtr != MemPtrEnd;
7471 ++MemPtr) {
7472 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007473 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 continue;
7475
7476 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007477 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007478 }
7479 }
7480 }
7481
7482 // C++ [over.built]p15:
7483 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007484 // For every T, where T is an enumeration type, a pointer type, or
7485 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007486 //
7487 // bool operator<(T, T);
7488 // bool operator>(T, T);
7489 // bool operator<=(T, T);
7490 // bool operator>=(T, T);
7491 // bool operator==(T, T);
7492 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007493 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007494 // C++ [over.match.oper]p3:
7495 // [...]the built-in candidates include all of the candidate operator
7496 // functions defined in 13.6 that, compared to the given operator, [...]
7497 // do not have the same parameter-type-list as any non-template non-member
7498 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007499 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007500 // Note that in practice, this only affects enumeration types because there
7501 // aren't any built-in candidates of record type, and a user-defined operator
7502 // must have an operand of record or enumeration type. Also, the only other
7503 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007504 // cannot be overloaded for enumeration types, so this is the only place
7505 // where we must suppress candidates like this.
7506 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7507 UserDefinedBinaryOperators;
7508
Richard Smithe54c3072013-05-05 15:51:06 +00007509 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007510 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7511 CandidateTypes[ArgIdx].enumeration_end()) {
7512 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7513 CEnd = CandidateSet.end();
7514 C != CEnd; ++C) {
7515 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7516 continue;
7517
Eli Friedman14f082b2012-09-18 21:52:24 +00007518 if (C->Function->isFunctionTemplateSpecialization())
7519 continue;
7520
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007521 QualType FirstParamType =
7522 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7523 QualType SecondParamType =
7524 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7525
7526 // Skip if either parameter isn't of enumeral type.
7527 if (!FirstParamType->isEnumeralType() ||
7528 !SecondParamType->isEnumeralType())
7529 continue;
7530
7531 // Add this operator to the set of known user-defined operators.
7532 UserDefinedBinaryOperators.insert(
7533 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7534 S.Context.getCanonicalType(SecondParamType)));
7535 }
7536 }
7537 }
7538
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007539 /// Set of (canonical) types that we've already handled.
7540 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7541
Richard Smithe54c3072013-05-05 15:51:06 +00007542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007543 for (BuiltinCandidateTypeSet::iterator
7544 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7545 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7546 Ptr != PtrEnd; ++Ptr) {
7547 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007548 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 continue;
7550
7551 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007552 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007553 }
7554 for (BuiltinCandidateTypeSet::iterator
7555 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7556 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7557 Enum != EnumEnd; ++Enum) {
7558 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7559
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007560 // Don't add the same builtin candidate twice, or if a user defined
7561 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007562 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007563 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7564 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007565 continue;
7566
7567 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007568 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007569 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007570
7571 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7572 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007573 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007574 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007575 NullPtrTy))) {
7576 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007577 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007578 CandidateSet);
7579 }
7580 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007581 }
7582 }
7583
7584 // C++ [over.built]p13:
7585 //
7586 // For every cv-qualified or cv-unqualified object type T
7587 // there exist candidate operator functions of the form
7588 //
7589 // T* operator+(T*, ptrdiff_t);
7590 // T& operator[](T*, ptrdiff_t); [BELOW]
7591 // T* operator-(T*, ptrdiff_t);
7592 // T* operator+(ptrdiff_t, T*);
7593 // T& operator[](ptrdiff_t, T*); [BELOW]
7594 //
7595 // C++ [over.built]p14:
7596 //
7597 // For every T, where T is a pointer to object type, there
7598 // exist candidate operator functions of the form
7599 //
7600 // ptrdiff_t operator-(T, T);
7601 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7602 /// Set of (canonical) types that we've already handled.
7603 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7604
7605 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007606 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007607 S.Context.getPointerDiffType(),
7608 S.Context.getPointerDiffType(),
7609 };
7610 for (BuiltinCandidateTypeSet::iterator
7611 Ptr = CandidateTypes[Arg].pointer_begin(),
7612 PtrEnd = CandidateTypes[Arg].pointer_end();
7613 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007614 QualType PointeeTy = (*Ptr)->getPointeeType();
7615 if (!PointeeTy->isObjectType())
7616 continue;
7617
Eric Christopher9207a522015-08-21 16:24:01 +00007618 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007619 if (Arg == 0 || Op == OO_Plus) {
7620 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7621 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007622 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 }
7624 if (Op == OO_Minus) {
7625 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007626 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 continue;
7628
7629 QualType ParamTypes[2] = { *Ptr, *Ptr };
7630 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007631 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 }
7633 }
7634 }
7635 }
7636
7637 // C++ [over.built]p12:
7638 //
7639 // For every pair of promoted arithmetic types L and R, there
7640 // exist candidate operator functions of the form
7641 //
7642 // LR operator*(L, R);
7643 // LR operator/(L, R);
7644 // LR operator+(L, R);
7645 // LR operator-(L, R);
7646 // bool operator<(L, R);
7647 // bool operator>(L, R);
7648 // bool operator<=(L, R);
7649 // bool operator>=(L, R);
7650 // bool operator==(L, R);
7651 // bool operator!=(L, R);
7652 //
7653 // where LR is the result of the usual arithmetic conversions
7654 // between types L and R.
7655 //
7656 // C++ [over.built]p24:
7657 //
7658 // For every pair of promoted arithmetic types L and R, there exist
7659 // candidate operator functions of the form
7660 //
7661 // LR operator?(bool, L, R);
7662 //
7663 // where LR is the result of the usual arithmetic conversions
7664 // between types L and R.
7665 // Our candidates ignore the first parameter.
7666 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007667 if (!HasArithmeticOrEnumeralCandidateType)
7668 return;
7669
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007670 for (unsigned Left = FirstPromotedArithmeticType;
7671 Left < LastPromotedArithmeticType; ++Left) {
7672 for (unsigned Right = FirstPromotedArithmeticType;
7673 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007674 QualType LandR[2] = { getArithmeticType(Left),
7675 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007676 QualType Result =
7677 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007678 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007679 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007680 }
7681 }
7682
7683 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7684 // conditional operator for vector types.
7685 for (BuiltinCandidateTypeSet::iterator
7686 Vec1 = CandidateTypes[0].vector_begin(),
7687 Vec1End = CandidateTypes[0].vector_end();
7688 Vec1 != Vec1End; ++Vec1) {
7689 for (BuiltinCandidateTypeSet::iterator
7690 Vec2 = CandidateTypes[1].vector_begin(),
7691 Vec2End = CandidateTypes[1].vector_end();
7692 Vec2 != Vec2End; ++Vec2) {
7693 QualType LandR[2] = { *Vec1, *Vec2 };
7694 QualType Result = S.Context.BoolTy;
7695 if (!isComparison) {
7696 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7697 Result = *Vec1;
7698 else
7699 Result = *Vec2;
7700 }
7701
Richard Smithe54c3072013-05-05 15:51:06 +00007702 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007703 }
7704 }
7705 }
7706
7707 // C++ [over.built]p17:
7708 //
7709 // For every pair of promoted integral types L and R, there
7710 // exist candidate operator functions of the form
7711 //
7712 // LR operator%(L, R);
7713 // LR operator&(L, R);
7714 // LR operator^(L, R);
7715 // LR operator|(L, R);
7716 // L operator<<(L, R);
7717 // L operator>>(L, R);
7718 //
7719 // where LR is the result of the usual arithmetic conversions
7720 // between types L and R.
7721 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007722 if (!HasArithmeticOrEnumeralCandidateType)
7723 return;
7724
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007725 for (unsigned Left = FirstPromotedIntegralType;
7726 Left < LastPromotedIntegralType; ++Left) {
7727 for (unsigned Right = FirstPromotedIntegralType;
7728 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007729 QualType LandR[2] = { getArithmeticType(Left),
7730 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7732 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007733 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007734 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007735 }
7736 }
7737 }
7738
7739 // C++ [over.built]p20:
7740 //
7741 // For every pair (T, VQ), where T is an enumeration or
7742 // pointer to member type and VQ is either volatile or
7743 // empty, there exist candidate operator functions of the form
7744 //
7745 // VQ T& operator=(VQ T&, T);
7746 void addAssignmentMemberPointerOrEnumeralOverloads() {
7747 /// Set of (canonical) types that we've already handled.
7748 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7749
7750 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7751 for (BuiltinCandidateTypeSet::iterator
7752 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7753 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7754 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007755 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007756 continue;
7757
Richard Smithe54c3072013-05-05 15:51:06 +00007758 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007759 }
7760
7761 for (BuiltinCandidateTypeSet::iterator
7762 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7763 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7764 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007765 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 continue;
7767
Richard Smithe54c3072013-05-05 15:51:06 +00007768 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 }
7770 }
7771 }
7772
7773 // C++ [over.built]p19:
7774 //
7775 // For every pair (T, VQ), where T is any type and VQ is either
7776 // volatile or empty, there exist candidate operator functions
7777 // of the form
7778 //
7779 // T*VQ& operator=(T*VQ&, T*);
7780 //
7781 // C++ [over.built]p21:
7782 //
7783 // For every pair (T, VQ), where T is a cv-qualified or
7784 // cv-unqualified object type and VQ is either volatile or
7785 // empty, there exist candidate operator functions of the form
7786 //
7787 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7788 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7789 void addAssignmentPointerOverloads(bool isEqualOp) {
7790 /// Set of (canonical) types that we've already handled.
7791 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7792
7793 for (BuiltinCandidateTypeSet::iterator
7794 Ptr = CandidateTypes[0].pointer_begin(),
7795 PtrEnd = CandidateTypes[0].pointer_end();
7796 Ptr != PtrEnd; ++Ptr) {
7797 // If this is operator=, keep track of the builtin candidates we added.
7798 if (isEqualOp)
7799 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007800 else if (!(*Ptr)->getPointeeType()->isObjectType())
7801 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007802
7803 // non-volatile version
7804 QualType ParamTypes[2] = {
7805 S.Context.getLValueReferenceType(*Ptr),
7806 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7807 };
Richard Smithe54c3072013-05-05 15:51:06 +00007808 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 /*IsAssigmentOperator=*/ isEqualOp);
7810
Douglas Gregor5bee2582012-06-04 00:15:09 +00007811 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7812 VisibleTypeConversionsQuals.hasVolatile();
7813 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007814 // volatile version
7815 ParamTypes[0] =
7816 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007818 /*IsAssigmentOperator=*/isEqualOp);
7819 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007820
7821 if (!(*Ptr).isRestrictQualified() &&
7822 VisibleTypeConversionsQuals.hasRestrict()) {
7823 // restrict version
7824 ParamTypes[0]
7825 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007826 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007827 /*IsAssigmentOperator=*/isEqualOp);
7828
7829 if (NeedVolatile) {
7830 // volatile restrict version
7831 ParamTypes[0]
7832 = S.Context.getLValueReferenceType(
7833 S.Context.getCVRQualifiedType(*Ptr,
7834 (Qualifiers::Volatile |
7835 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007836 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007837 /*IsAssigmentOperator=*/isEqualOp);
7838 }
7839 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007840 }
7841
7842 if (isEqualOp) {
7843 for (BuiltinCandidateTypeSet::iterator
7844 Ptr = CandidateTypes[1].pointer_begin(),
7845 PtrEnd = CandidateTypes[1].pointer_end();
7846 Ptr != PtrEnd; ++Ptr) {
7847 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007849 continue;
7850
Chandler Carruth8e543b32010-12-12 08:17:55 +00007851 QualType ParamTypes[2] = {
7852 S.Context.getLValueReferenceType(*Ptr),
7853 *Ptr,
7854 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007855
7856 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007857 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007858 /*IsAssigmentOperator=*/true);
7859
Douglas Gregor5bee2582012-06-04 00:15:09 +00007860 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7861 VisibleTypeConversionsQuals.hasVolatile();
7862 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007863 // volatile version
7864 ParamTypes[0] =
7865 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007866 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7867 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007868 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007869
7870 if (!(*Ptr).isRestrictQualified() &&
7871 VisibleTypeConversionsQuals.hasRestrict()) {
7872 // restrict version
7873 ParamTypes[0]
7874 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007875 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7876 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007877
7878 if (NeedVolatile) {
7879 // volatile restrict version
7880 ParamTypes[0]
7881 = S.Context.getLValueReferenceType(
7882 S.Context.getCVRQualifiedType(*Ptr,
7883 (Qualifiers::Volatile |
7884 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007885 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7886 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007887 }
7888 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007889 }
7890 }
7891 }
7892
7893 // C++ [over.built]p18:
7894 //
7895 // For every triple (L, VQ, R), where L is an arithmetic type,
7896 // VQ is either volatile or empty, and R is a promoted
7897 // arithmetic type, there exist candidate operator functions of
7898 // the form
7899 //
7900 // VQ L& operator=(VQ L&, R);
7901 // VQ L& operator*=(VQ L&, R);
7902 // VQ L& operator/=(VQ L&, R);
7903 // VQ L& operator+=(VQ L&, R);
7904 // VQ L& operator-=(VQ L&, R);
7905 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007906 if (!HasArithmeticOrEnumeralCandidateType)
7907 return;
7908
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007909 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7910 for (unsigned Right = FirstPromotedArithmeticType;
7911 Right < LastPromotedArithmeticType; ++Right) {
7912 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007913 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007914
7915 // Add this built-in operator as a candidate (VQ is empty).
7916 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007917 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007919 /*IsAssigmentOperator=*/isEqualOp);
7920
7921 // Add this built-in operator as a candidate (VQ is 'volatile').
7922 if (VisibleTypeConversionsQuals.hasVolatile()) {
7923 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007924 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007925 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007926 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007927 /*IsAssigmentOperator=*/isEqualOp);
7928 }
7929 }
7930 }
7931
7932 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7933 for (BuiltinCandidateTypeSet::iterator
7934 Vec1 = CandidateTypes[0].vector_begin(),
7935 Vec1End = CandidateTypes[0].vector_end();
7936 Vec1 != Vec1End; ++Vec1) {
7937 for (BuiltinCandidateTypeSet::iterator
7938 Vec2 = CandidateTypes[1].vector_begin(),
7939 Vec2End = CandidateTypes[1].vector_end();
7940 Vec2 != Vec2End; ++Vec2) {
7941 QualType ParamTypes[2];
7942 ParamTypes[1] = *Vec2;
7943 // Add this built-in operator as a candidate (VQ is empty).
7944 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007945 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946 /*IsAssigmentOperator=*/isEqualOp);
7947
7948 // Add this built-in operator as a candidate (VQ is 'volatile').
7949 if (VisibleTypeConversionsQuals.hasVolatile()) {
7950 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7951 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007952 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007953 /*IsAssigmentOperator=*/isEqualOp);
7954 }
7955 }
7956 }
7957 }
7958
7959 // C++ [over.built]p22:
7960 //
7961 // For every triple (L, VQ, R), where L is an integral type, VQ
7962 // is either volatile or empty, and R is a promoted integral
7963 // type, there exist candidate operator functions of the form
7964 //
7965 // VQ L& operator%=(VQ L&, R);
7966 // VQ L& operator<<=(VQ L&, R);
7967 // VQ L& operator>>=(VQ L&, R);
7968 // VQ L& operator&=(VQ L&, R);
7969 // VQ L& operator^=(VQ L&, R);
7970 // VQ L& operator|=(VQ L&, R);
7971 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007972 if (!HasArithmeticOrEnumeralCandidateType)
7973 return;
7974
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007975 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7976 for (unsigned Right = FirstPromotedIntegralType;
7977 Right < LastPromotedIntegralType; ++Right) {
7978 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007979 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007980
7981 // Add this built-in operator as a candidate (VQ is empty).
7982 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007983 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007985 if (VisibleTypeConversionsQuals.hasVolatile()) {
7986 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007987 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007988 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7989 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 }
7992 }
7993 }
7994 }
7995
7996 // C++ [over.operator]p23:
7997 //
7998 // There also exist candidate operator functions of the form
7999 //
8000 // bool operator!(bool);
8001 // bool operator&&(bool, bool);
8002 // bool operator||(bool, bool);
8003 void addExclaimOverload() {
8004 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008005 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008006 /*IsAssignmentOperator=*/false,
8007 /*NumContextualBoolArguments=*/1);
8008 }
8009 void addAmpAmpOrPipePipeOverload() {
8010 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008011 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008012 /*IsAssignmentOperator=*/false,
8013 /*NumContextualBoolArguments=*/2);
8014 }
8015
8016 // C++ [over.built]p13:
8017 //
8018 // For every cv-qualified or cv-unqualified object type T there
8019 // exist candidate operator functions of the form
8020 //
8021 // T* operator+(T*, ptrdiff_t); [ABOVE]
8022 // T& operator[](T*, ptrdiff_t);
8023 // T* operator-(T*, ptrdiff_t); [ABOVE]
8024 // T* operator+(ptrdiff_t, T*); [ABOVE]
8025 // T& operator[](ptrdiff_t, T*);
8026 void addSubscriptOverloads() {
8027 for (BuiltinCandidateTypeSet::iterator
8028 Ptr = CandidateTypes[0].pointer_begin(),
8029 PtrEnd = CandidateTypes[0].pointer_end();
8030 Ptr != PtrEnd; ++Ptr) {
8031 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8032 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008033 if (!PointeeType->isObjectType())
8034 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008036 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8037
8038 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008039 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 }
8041
8042 for (BuiltinCandidateTypeSet::iterator
8043 Ptr = CandidateTypes[1].pointer_begin(),
8044 PtrEnd = CandidateTypes[1].pointer_end();
8045 Ptr != PtrEnd; ++Ptr) {
8046 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8047 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008048 if (!PointeeType->isObjectType())
8049 continue;
8050
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8052
8053 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008054 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 }
8056 }
8057
8058 // C++ [over.built]p11:
8059 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8060 // C1 is the same type as C2 or is a derived class of C2, T is an object
8061 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8062 // there exist candidate operator functions of the form
8063 //
8064 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8065 //
8066 // where CV12 is the union of CV1 and CV2.
8067 void addArrowStarOverloads() {
8068 for (BuiltinCandidateTypeSet::iterator
8069 Ptr = CandidateTypes[0].pointer_begin(),
8070 PtrEnd = CandidateTypes[0].pointer_end();
8071 Ptr != PtrEnd; ++Ptr) {
8072 QualType C1Ty = (*Ptr);
8073 QualType C1;
8074 QualifierCollector Q1;
8075 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8076 if (!isa<RecordType>(C1))
8077 continue;
8078 // heuristic to reduce number of builtin candidates in the set.
8079 // Add volatile/restrict version only if there are conversions to a
8080 // volatile/restrict type.
8081 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8082 continue;
8083 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8084 continue;
8085 for (BuiltinCandidateTypeSet::iterator
8086 MemPtr = CandidateTypes[1].member_pointer_begin(),
8087 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8088 MemPtr != MemPtrEnd; ++MemPtr) {
8089 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8090 QualType C2 = QualType(mptr->getClass(), 0);
8091 C2 = C2.getUnqualifiedType();
8092 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8093 break;
8094 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8095 // build CV12 T&
8096 QualType T = mptr->getPointeeType();
8097 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8098 T.isVolatileQualified())
8099 continue;
8100 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8101 T.isRestrictQualified())
8102 continue;
8103 T = Q1.apply(S.Context, T);
8104 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008105 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008106 }
8107 }
8108 }
8109
8110 // Note that we don't consider the first argument, since it has been
8111 // contextually converted to bool long ago. The candidates below are
8112 // therefore added as binary.
8113 //
8114 // C++ [over.built]p25:
8115 // For every type T, where T is a pointer, pointer-to-member, or scoped
8116 // enumeration type, there exist candidate operator functions of the form
8117 //
8118 // T operator?(bool, T, T);
8119 //
8120 void addConditionalOperatorOverloads() {
8121 /// Set of (canonical) types that we've already handled.
8122 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8123
8124 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8125 for (BuiltinCandidateTypeSet::iterator
8126 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8127 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8128 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008129 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008130 continue;
8131
8132 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008133 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008134 }
8135
8136 for (BuiltinCandidateTypeSet::iterator
8137 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8138 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8139 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008140 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008141 continue;
8142
8143 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008144 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008145 }
8146
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008147 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008148 for (BuiltinCandidateTypeSet::iterator
8149 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8150 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8151 Enum != EnumEnd; ++Enum) {
8152 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8153 continue;
8154
David Blaikie82e95a32014-11-19 07:49:47 +00008155 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008156 continue;
8157
8158 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008159 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008160 }
8161 }
8162 }
8163 }
8164};
8165
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008166} // end anonymous namespace
8167
8168/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8169/// operator overloads to the candidate set (C++ [over.built]), based
8170/// on the operator @p Op and the arguments given. For example, if the
8171/// operator is a binary '+', this routine might add "int
8172/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008173void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8174 SourceLocation OpLoc,
8175 ArrayRef<Expr *> Args,
8176 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008177 // Find all of the types that the arguments can convert to, but only
8178 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008179 // that make use of these types. Also record whether we encounter non-record
8180 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008181 Qualifiers VisibleTypeConversionsQuals;
8182 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008183 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008184 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008185
8186 bool HasNonRecordCandidateType = false;
8187 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008188 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008189 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008190 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008191 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8192 OpLoc,
8193 true,
8194 (Op == OO_Exclaim ||
8195 Op == OO_AmpAmp ||
8196 Op == OO_PipePipe),
8197 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008198 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8199 CandidateTypes[ArgIdx].hasNonRecordTypes();
8200 HasArithmeticOrEnumeralCandidateType =
8201 HasArithmeticOrEnumeralCandidateType ||
8202 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008203 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008204
Chandler Carruth00a38332010-12-13 01:44:01 +00008205 // Exit early when no non-record types have been added to the candidate set
8206 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008207 //
8208 // We can't exit early for !, ||, or &&, since there we have always have
8209 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008210 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008211 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008212 return;
8213
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008214 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008215 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008217 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008218 CandidateTypes, CandidateSet);
8219
8220 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008221 switch (Op) {
8222 case OO_None:
8223 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008224 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008225
Chandler Carruth5184de02010-12-12 08:51:33 +00008226 case OO_New:
8227 case OO_Delete:
8228 case OO_Array_New:
8229 case OO_Array_Delete:
8230 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008231 llvm_unreachable(
8232 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008233
8234 case OO_Comma:
8235 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008236 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008237 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008238 // -- For the operator ',', the unary operator '&', the
8239 // operator '->', or the operator 'co_await', the
8240 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008241 break;
8242
8243 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008244 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008245 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008246 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008247
8248 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008249 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008250 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008251 } else {
8252 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8253 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8254 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008255 break;
8256
Chandler Carruth5184de02010-12-12 08:51:33 +00008257 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008258 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008259 OpBuilder.addUnaryStarPointerOverloads();
8260 else
8261 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8262 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263
Chandler Carruth5184de02010-12-12 08:51:33 +00008264 case OO_Slash:
8265 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008266 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008267
8268 case OO_PlusPlus:
8269 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008270 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8271 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008272 break;
8273
Douglas Gregor84605ae2009-08-24 13:43:27 +00008274 case OO_EqualEqual:
8275 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008276 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008277 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008278
Douglas Gregora11693b2008-11-12 17:17:38 +00008279 case OO_Less:
8280 case OO_Greater:
8281 case OO_LessEqual:
8282 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008283 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008284 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8285 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008286
Douglas Gregora11693b2008-11-12 17:17:38 +00008287 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008288 case OO_Caret:
8289 case OO_Pipe:
8290 case OO_LessLess:
8291 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008292 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008293 break;
8294
Chandler Carruth5184de02010-12-12 08:51:33 +00008295 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008296 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008297 // C++ [over.match.oper]p3:
8298 // -- For the operator ',', the unary operator '&', or the
8299 // operator '->', the built-in candidates set is empty.
8300 break;
8301
8302 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8303 break;
8304
8305 case OO_Tilde:
8306 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8307 break;
8308
Douglas Gregora11693b2008-11-12 17:17:38 +00008309 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008310 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008311 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008312
8313 case OO_PlusEqual:
8314 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008316 // Fall through.
8317
8318 case OO_StarEqual:
8319 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008320 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008321 break;
8322
8323 case OO_PercentEqual:
8324 case OO_LessLessEqual:
8325 case OO_GreaterGreaterEqual:
8326 case OO_AmpEqual:
8327 case OO_CaretEqual:
8328 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008329 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008330 break;
8331
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 case OO_Exclaim:
8333 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008334 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008335
Douglas Gregora11693b2008-11-12 17:17:38 +00008336 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337 case OO_PipePipe:
8338 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008339 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008340
8341 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008343 break;
8344
8345 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008347 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008348
8349 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008350 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008351 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8352 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008353 }
8354}
8355
Douglas Gregore254f902009-02-04 00:32:51 +00008356/// \brief Add function candidates found via argument-dependent lookup
8357/// to the set of overloading candidates.
8358///
8359/// This routine performs argument-dependent name lookup based on the
8360/// given function name (which may also be an operator name) and adds
8361/// all of the overload candidates found by ADL to the overload
8362/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008363void
Douglas Gregore254f902009-02-04 00:32:51 +00008364Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008365 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008366 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008367 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008368 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008369 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008370 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008371
John McCall91f61fc2010-01-26 06:04:06 +00008372 // FIXME: This approach for uniquing ADL results (and removing
8373 // redundant candidates from the set) relies on pointer-equality,
8374 // which means we need to key off the canonical decl. However,
8375 // always going back to the canonical decl might not get us the
8376 // right set of default arguments. What default arguments are
8377 // we supposed to consider on ADL candidates, anyway?
8378
Douglas Gregorcabea402009-09-22 15:41:20 +00008379 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008380 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008381
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008382 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008383 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8384 CandEnd = CandidateSet.end();
8385 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008386 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008387 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008388 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008389 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008390 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008391
8392 // For each of the ADL candidates we found, add it to the overload
8393 // set.
John McCall8fe68082010-01-26 07:16:45 +00008394 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008395 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008396 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008397 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008398 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008400 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8401 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008402 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008403 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008404 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008405 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008406 }
Douglas Gregore254f902009-02-04 00:32:51 +00008407}
8408
George Burgess IV2a6150d2015-10-16 01:17:38 +00008409// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8410// Cand2 for overloading. This function assumes that all of the enable_if attrs
8411// on Cand1 and Cand2 have conditions that evaluate to true.
8412//
8413// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8414// Cand1's first N enable_if attributes have precisely the same conditions as
8415// Cand2's first N enable_if attributes (where N = the number of enable_if
8416// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8417static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8418 const FunctionDecl *Cand2) {
8419
8420 // FIXME: The next several lines are just
8421 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8422 // instead of reverse order which is how they're stored in the AST.
8423 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8424 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8425
8426 // Candidate 1 is better if it has strictly more attributes and
8427 // the common sequence is identical.
8428 if (Cand1Attrs.size() <= Cand2Attrs.size())
8429 return false;
8430
8431 auto Cand1I = Cand1Attrs.begin();
8432 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8433 for (auto &Cand2A : Cand2Attrs) {
8434 Cand1ID.clear();
8435 Cand2ID.clear();
8436
8437 auto &Cand1A = *Cand1I++;
8438 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8439 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8440 if (Cand1ID != Cand2ID)
8441 return false;
8442 }
8443
8444 return true;
8445}
8446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008447/// isBetterOverloadCandidate - Determines whether the first overload
8448/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008449bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8450 const OverloadCandidate &Cand2,
8451 SourceLocation Loc,
8452 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008453 // Define viable functions to be better candidates than non-viable
8454 // functions.
8455 if (!Cand2.Viable)
8456 return Cand1.Viable;
8457 else if (!Cand1.Viable)
8458 return false;
8459
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008460 // C++ [over.match.best]p1:
8461 //
8462 // -- if F is a static member function, ICS1(F) is defined such
8463 // that ICS1(F) is neither better nor worse than ICS1(G) for
8464 // any function G, and, symmetrically, ICS1(G) is neither
8465 // better nor worse than ICS1(F).
8466 unsigned StartArg = 0;
8467 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8468 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008469
Douglas Gregord3cb3562009-07-07 23:38:56 +00008470 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008471 // A viable function F1 is defined to be a better function than another
8472 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008473 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008474 unsigned NumArgs = Cand1.NumConversions;
8475 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008476 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008477 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008478 switch (CompareImplicitConversionSequences(S,
8479 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008480 Cand2.Conversions[ArgIdx])) {
8481 case ImplicitConversionSequence::Better:
8482 // Cand1 has a better conversion sequence.
8483 HasBetterConversion = true;
8484 break;
8485
8486 case ImplicitConversionSequence::Worse:
8487 // Cand1 can't be better than Cand2.
8488 return false;
8489
8490 case ImplicitConversionSequence::Indistinguishable:
8491 // Do nothing.
8492 break;
8493 }
8494 }
8495
Mike Stump11289f42009-09-09 15:08:12 +00008496 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008497 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008498 if (HasBetterConversion)
8499 return true;
8500
Douglas Gregora1f013e2008-11-07 22:36:19 +00008501 // -- the context is an initialization by user-defined conversion
8502 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8503 // from the return type of F1 to the destination type (i.e.,
8504 // the type of the entity being initialized) is a better
8505 // conversion sequence than the standard conversion sequence
8506 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008507 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008508 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008509 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008510 // First check whether we prefer one of the conversion functions over the
8511 // other. This only distinguishes the results in non-standard, extension
8512 // cases such as the conversion from a lambda closure type to a function
8513 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008514 ImplicitConversionSequence::CompareKind Result =
8515 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8516 if (Result == ImplicitConversionSequence::Indistinguishable)
8517 Result = CompareStandardConversionSequences(S,
8518 Cand1.FinalConversion,
8519 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008520
Richard Smithec2748a2014-05-17 04:36:39 +00008521 if (Result != ImplicitConversionSequence::Indistinguishable)
8522 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008523
8524 // FIXME: Compare kind of reference binding if conversion functions
8525 // convert to a reference type used in direct reference binding, per
8526 // C++14 [over.match.best]p1 section 2 bullet 3.
8527 }
8528
8529 // -- F1 is a non-template function and F2 is a function template
8530 // specialization, or, if not that,
8531 bool Cand1IsSpecialization = Cand1.Function &&
8532 Cand1.Function->getPrimaryTemplate();
8533 bool Cand2IsSpecialization = Cand2.Function &&
8534 Cand2.Function->getPrimaryTemplate();
8535 if (Cand1IsSpecialization != Cand2IsSpecialization)
8536 return Cand2IsSpecialization;
8537
8538 // -- F1 and F2 are function template specializations, and the function
8539 // template for F1 is more specialized than the template for F2
8540 // according to the partial ordering rules described in 14.5.5.2, or,
8541 // if not that,
8542 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8543 if (FunctionTemplateDecl *BetterTemplate
8544 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8545 Cand2.Function->getPrimaryTemplate(),
8546 Loc,
8547 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8548 : TPOC_Call,
8549 Cand1.ExplicitCallArguments,
8550 Cand2.ExplicitCallArguments))
8551 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008552 }
8553
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008554 // Check for enable_if value-based overload resolution.
8555 if (Cand1.Function && Cand2.Function &&
8556 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008557 Cand2.Function->hasAttr<EnableIfAttr>()))
8558 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008559
Artem Belevich94a55e82015-09-22 17:22:59 +00008560 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8561 Cand1.Function && Cand2.Function) {
8562 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8563 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8564 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8565 }
8566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008567 return false;
8568}
8569
Richard Smith896c66e2015-10-21 07:13:52 +00008570/// Determine whether two function declarations are "equivalent" for overload
8571/// resolution purposes. This applies when the same internal linkage function
8572/// is defined by two modules (textually including the same header). In such
8573/// a case, we don't consider the declarations to declare the same entity, but
8574/// we also don't want lookups with both declarations visible to be ambiguous
8575/// in some cases (this happens when using a modularized libstdc++).
8576static bool isEquivalentCompatibleOverload(Sema &S,
8577 const OverloadCandidate &Best,
8578 const OverloadCandidate &Cand) {
8579 return Best.Function && Cand.Function &&
8580 Best.Function->getDeclContext()->getRedeclContext()->Equals(
8581 Cand.Function->getDeclContext()->getRedeclContext()) &&
8582 S.getOwningModule(Best.Function) != S.getOwningModule(Cand.Function) &&
8583 !Best.Function->isExternallyVisible() &&
8584 !Cand.Function->isExternallyVisible() &&
8585 !S.IsOverload(Best.Function, Cand.Function, /*UsingDecl*/false);
8586}
8587
8588static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8589 unsigned NumArgs);
8590
Mike Stump11289f42009-09-09 15:08:12 +00008591/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008592/// within an overload candidate set.
8593///
James Dennettffad8b72012-06-22 08:10:18 +00008594/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008595/// which overload resolution occurs.
8596///
James Dennettffad8b72012-06-22 08:10:18 +00008597/// \param Best If overload resolution was successful or found a deleted
8598/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008599///
8600/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008601OverloadingResult
8602OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008603 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008604 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008605 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008606 Best = end();
8607 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8608 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008609 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008610 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008611 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008612 }
8613
8614 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008615 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008616 return OR_No_Viable_Function;
8617
Richard Smith896c66e2015-10-21 07:13:52 +00008618 llvm::SmallVector<const OverloadCandidate *, 4> EquivalentCands;
8619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008620 // Make sure that this function is better than every other viable
8621 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008622 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008623 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008624 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008626 UserDefinedConversion)) {
Richard Smith896c66e2015-10-21 07:13:52 +00008627 if (isEquivalentCompatibleOverload(S, *Best, *Cand)) {
8628 EquivalentCands.push_back(Cand);
8629 continue;
8630 }
8631
John McCall5c32be02010-08-24 20:38:10 +00008632 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008633 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008634 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008635 }
Mike Stump11289f42009-09-09 15:08:12 +00008636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008637 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008638 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008639 (Best->Function->isDeleted() ||
8640 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008641 return OR_Deleted;
8642
Richard Smith896c66e2015-10-21 07:13:52 +00008643 if (!EquivalentCands.empty()) {
8644 S.Diag(Loc, diag::ext_ovl_equivalent_internal_linkage_functions_in_modules)
8645 << Best->Function;
8646 S.NoteOverloadCandidate(Best->Function);
8647 for (auto *Cand : EquivalentCands)
8648 S.NoteOverloadCandidate(Cand->Function);
8649 }
8650
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008651 return OR_Success;
8652}
8653
John McCall53262c92010-01-12 02:15:36 +00008654namespace {
8655
8656enum OverloadCandidateKind {
8657 oc_function,
8658 oc_method,
8659 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008660 oc_function_template,
8661 oc_method_template,
8662 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008663 oc_implicit_default_constructor,
8664 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008665 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008666 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008667 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008668 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008669};
8670
John McCalle1ac8d12010-01-13 00:25:19 +00008671OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8672 FunctionDecl *Fn,
8673 std::string &Description) {
8674 bool isTemplate = false;
8675
8676 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8677 isTemplate = true;
8678 Description = S.getTemplateArgumentBindingsText(
8679 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8680 }
John McCallfd0b2f82010-01-06 09:43:14 +00008681
8682 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008683 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008684 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008685
Sebastian Redl08905022011-02-05 19:23:19 +00008686 if (Ctor->getInheritedConstructor())
8687 return oc_implicit_inherited_constructor;
8688
Alexis Hunt119c10e2011-05-25 23:16:36 +00008689 if (Ctor->isDefaultConstructor())
8690 return oc_implicit_default_constructor;
8691
8692 if (Ctor->isMoveConstructor())
8693 return oc_implicit_move_constructor;
8694
8695 assert(Ctor->isCopyConstructor() &&
8696 "unexpected sort of implicit constructor");
8697 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008698 }
8699
8700 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8701 // This actually gets spelled 'candidate function' for now, but
8702 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008703 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008704 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008705
Alexis Hunt119c10e2011-05-25 23:16:36 +00008706 if (Meth->isMoveAssignmentOperator())
8707 return oc_implicit_move_assignment;
8708
Douglas Gregor12695102012-02-10 08:36:38 +00008709 if (Meth->isCopyAssignmentOperator())
8710 return oc_implicit_copy_assignment;
8711
8712 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8713 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008714 }
8715
John McCalle1ac8d12010-01-13 00:25:19 +00008716 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008717}
8718
Larisse Voufo98b20f12013-07-19 23:00:19 +00008719void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008720 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8721 if (!Ctor) return;
8722
8723 Ctor = Ctor->getInheritedConstructor();
8724 if (!Ctor) return;
8725
8726 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8727}
8728
John McCall53262c92010-01-12 02:15:36 +00008729} // end anonymous namespace
8730
George Burgess IV5f21c712015-10-12 19:57:04 +00008731static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8732 const FunctionDecl *FD) {
8733 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8734 bool AlwaysTrue;
8735 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8736 return false;
8737 if (!AlwaysTrue)
8738 return false;
8739 }
8740 return true;
8741}
8742
John McCall53262c92010-01-12 02:15:36 +00008743// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008744void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8745 bool TakingAddress) {
John McCalle1ac8d12010-01-13 00:25:19 +00008746 std::string FnDesc;
8747 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008748 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8749 << (unsigned) K << FnDesc;
George Burgess IV5f21c712015-10-12 19:57:04 +00008750 if (TakingAddress && !isFunctionAlwaysEnabled(Context, Fn))
8751 PD << ft_addr_enable_if;
8752 else
8753 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008754 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008755 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008756}
8757
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008758// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008759// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008760void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8761 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008762 assert(OverloadedExpr->getType() == Context.OverloadTy);
8763
8764 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8765 OverloadExpr *OvlExpr = Ovl.Expression;
8766
8767 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8768 IEnd = OvlExpr->decls_end();
8769 I != IEnd; ++I) {
8770 if (FunctionTemplateDecl *FunTmpl =
8771 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008772 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8773 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008774 } else if (FunctionDecl *Fun
8775 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008776 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008777 }
8778 }
8779}
8780
John McCall0d1da222010-01-12 00:44:57 +00008781/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8782/// "lead" diagnostic; it will be given two arguments, the source and
8783/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008784void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8785 Sema &S,
8786 SourceLocation CaretLoc,
8787 const PartialDiagnostic &PDiag) const {
8788 S.Diag(CaretLoc, PDiag)
8789 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008790 // FIXME: The note limiting machinery is borrowed from
8791 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8792 // refactoring here.
8793 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8794 unsigned CandsShown = 0;
8795 AmbiguousConversionSequence::const_iterator I, E;
8796 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8797 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8798 break;
8799 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008800 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008801 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008802 if (I != E)
8803 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008804}
8805
Richard Smith17c00b42014-11-12 01:24:00 +00008806static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8807 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008808 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8809 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008810 assert(Cand->Function && "for now, candidate must be a function");
8811 FunctionDecl *Fn = Cand->Function;
8812
8813 // There's a conversion slot for the object argument if this is a
8814 // non-constructor method. Note that 'I' corresponds the
8815 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008816 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008817 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008818 if (I == 0)
8819 isObjectArgument = true;
8820 else
8821 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008822 }
8823
John McCalle1ac8d12010-01-13 00:25:19 +00008824 std::string FnDesc;
8825 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8826
John McCall6a61b522010-01-13 09:16:55 +00008827 Expr *FromExpr = Conv.Bad.FromExpr;
8828 QualType FromTy = Conv.Bad.getFromType();
8829 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008830
John McCallfb7ad0f2010-02-02 02:42:52 +00008831 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008832 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008833 Expr *E = FromExpr->IgnoreParens();
8834 if (isa<UnaryOperator>(E))
8835 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008836 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008837
8838 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8839 << (unsigned) FnKind << FnDesc
8840 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8841 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008842 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008843 return;
8844 }
8845
John McCall6d174642010-01-23 08:10:49 +00008846 // Do some hand-waving analysis to see if the non-viability is due
8847 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008848 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8849 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8850 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8851 CToTy = RT->getPointeeType();
8852 else {
8853 // TODO: detect and diagnose the full richness of const mismatches.
8854 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8855 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8856 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8857 }
8858
8859 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8860 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008861 Qualifiers FromQs = CFromTy.getQualifiers();
8862 Qualifiers ToQs = CToTy.getQualifiers();
8863
8864 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8866 << (unsigned) FnKind << FnDesc
8867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8868 << FromTy
8869 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8870 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008871 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008872 return;
8873 }
8874
John McCall31168b02011-06-15 23:02:42 +00008875 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008877 << (unsigned) FnKind << FnDesc
8878 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8879 << FromTy
8880 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8881 << (unsigned) isObjectArgument << I+1;
8882 MaybeEmitInheritedConstructorNote(S, Fn);
8883 return;
8884 }
8885
Douglas Gregoraec25842011-04-26 23:16:46 +00008886 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8888 << (unsigned) FnKind << FnDesc
8889 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8890 << FromTy
8891 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8892 << (unsigned) isObjectArgument << I+1;
8893 MaybeEmitInheritedConstructorNote(S, Fn);
8894 return;
8895 }
8896
John McCall47000992010-01-14 03:28:57 +00008897 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8898 assert(CVR && "unexpected qualifiers mismatch");
8899
8900 if (isObjectArgument) {
8901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8902 << (unsigned) FnKind << FnDesc
8903 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8904 << FromTy << (CVR - 1);
8905 } else {
8906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8907 << (unsigned) FnKind << FnDesc
8908 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8909 << FromTy << (CVR - 1) << I+1;
8910 }
Sebastian Redl08905022011-02-05 19:23:19 +00008911 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008912 return;
8913 }
8914
Sebastian Redla72462c2011-09-24 17:48:32 +00008915 // Special diagnostic for failure to convert an initializer list, since
8916 // telling the user that it has type void is not useful.
8917 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8918 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8919 << (unsigned) FnKind << FnDesc
8920 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8921 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8922 MaybeEmitInheritedConstructorNote(S, Fn);
8923 return;
8924 }
8925
John McCall6d174642010-01-23 08:10:49 +00008926 // Diagnose references or pointers to incomplete types differently,
8927 // since it's far from impossible that the incompleteness triggered
8928 // the failure.
8929 QualType TempFromTy = FromTy.getNonReferenceType();
8930 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8931 TempFromTy = PTy->getPointeeType();
8932 if (TempFromTy->isIncompleteType()) {
8933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8934 << (unsigned) FnKind << FnDesc
8935 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8936 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008937 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008938 return;
8939 }
8940
Douglas Gregor56f2e342010-06-30 23:01:39 +00008941 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008942 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008943 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8944 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8945 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8946 FromPtrTy->getPointeeType()) &&
8947 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8948 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008950 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008951 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008952 }
8953 } else if (const ObjCObjectPointerType *FromPtrTy
8954 = FromTy->getAs<ObjCObjectPointerType>()) {
8955 if (const ObjCObjectPointerType *ToPtrTy
8956 = ToTy->getAs<ObjCObjectPointerType>())
8957 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8958 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8959 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8960 FromPtrTy->getPointeeType()) &&
8961 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008962 BaseToDerivedConversion = 2;
8963 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008964 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8965 !FromTy->isIncompleteType() &&
8966 !ToRefTy->getPointeeType()->isIncompleteType() &&
8967 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8968 BaseToDerivedConversion = 3;
8969 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8970 ToTy.getNonReferenceType().getCanonicalType() ==
8971 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008972 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8973 << (unsigned) FnKind << FnDesc
8974 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8975 << (unsigned) isObjectArgument << I + 1;
8976 MaybeEmitInheritedConstructorNote(S, Fn);
8977 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008978 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008980
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008981 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008982 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008983 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008984 << (unsigned) FnKind << FnDesc
8985 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008986 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008987 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008988 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008989 return;
8990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008991
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008992 if (isa<ObjCObjectPointerType>(CFromTy) &&
8993 isa<PointerType>(CToTy)) {
8994 Qualifiers FromQs = CFromTy.getQualifiers();
8995 Qualifiers ToQs = CToTy.getQualifiers();
8996 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8998 << (unsigned) FnKind << FnDesc
8999 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9000 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9001 MaybeEmitInheritedConstructorNote(S, Fn);
9002 return;
9003 }
9004 }
9005
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009006 // Emit the generic diagnostic and, optionally, add the hints to it.
9007 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9008 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009009 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009010 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9011 << (unsigned) (Cand->Fix.Kind);
9012
9013 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009014 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9015 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009016 FDiag << *HI;
9017 S.Diag(Fn->getLocation(), FDiag);
9018
Sebastian Redl08905022011-02-05 19:23:19 +00009019 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009020}
9021
Larisse Voufo98b20f12013-07-19 23:00:19 +00009022/// Additional arity mismatch diagnosis specific to a function overload
9023/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9024/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009025static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9026 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009027 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009028 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009029
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009030 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009031 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009032 // right number of arguments, because only overloaded operators have
9033 // the weird behavior of overloading member and non-member functions.
9034 // Just don't report anything.
9035 if (Fn->isInvalidDecl() &&
9036 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009037 return true;
9038
9039 if (NumArgs < MinParams) {
9040 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9041 (Cand->FailureKind == ovl_fail_bad_deduction &&
9042 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9043 } else {
9044 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9045 (Cand->FailureKind == ovl_fail_bad_deduction &&
9046 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9047 }
9048
9049 return false;
9050}
9051
9052/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009053static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009054 assert(isa<FunctionDecl>(D) &&
9055 "The templated declaration should at least be a function"
9056 " when diagnosing bad template argument deduction due to too many"
9057 " or too few arguments");
9058
9059 FunctionDecl *Fn = cast<FunctionDecl>(D);
9060
9061 // TODO: treat calls to a missing default constructor as a special case
9062 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9063 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009064
John McCall6a61b522010-01-13 09:16:55 +00009065 // at least / at most / exactly
9066 unsigned mode, modeCount;
9067 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009068 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9069 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009070 mode = 0; // "at least"
9071 else
9072 mode = 2; // "exactly"
9073 modeCount = MinParams;
9074 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009075 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009076 mode = 1; // "at most"
9077 else
9078 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009079 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009080 }
9081
9082 std::string Description;
9083 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9084
Richard Smith10ff50d2012-05-11 05:16:41 +00009085 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009087 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9088 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009089 else
9090 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009091 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9092 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009093 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009094}
9095
Larisse Voufo98b20f12013-07-19 23:00:19 +00009096/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009097static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9098 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009099 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9100 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9101}
Larisse Voufo47c08452013-07-19 22:53:23 +00009102
Richard Smith17c00b42014-11-12 01:24:00 +00009103static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9105 return FD->getDescribedFunctionTemplate();
9106 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9107 return RD->getDescribedClassTemplate();
9108
9109 llvm_unreachable("Unsupported: Getting the described template declaration"
9110 " for bad deduction diagnosis");
9111}
9112
9113/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009114static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9115 DeductionFailureInfo &DeductionFailure,
9116 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009117 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009118 NamedDecl *ParamD;
9119 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9120 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9121 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009122 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009123 case Sema::TDK_Success:
9124 llvm_unreachable("TDK_success while diagnosing bad deduction");
9125
9126 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009127 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009128 S.Diag(Templated->getLocation(),
9129 diag::note_ovl_candidate_incomplete_deduction)
9130 << ParamD->getDeclName();
9131 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009132 return;
9133 }
9134
John McCall42d7d192010-08-05 09:05:08 +00009135 case Sema::TDK_Underqualified: {
9136 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9137 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9138
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009140
9141 // Param will have been canonicalized, but it should just be a
9142 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009143 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009144 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009145 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009146 assert(S.Context.hasSameType(Param, NonCanonParam));
9147
9148 // Arg has also been canonicalized, but there's nothing we can do
9149 // about that. It also doesn't matter as much, because it won't
9150 // have any template parameters in it (because deduction isn't
9151 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009152 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009153
Larisse Voufo98b20f12013-07-19 23:00:19 +00009154 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9155 << ParamD->getDeclName() << Arg << NonCanonParam;
9156 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009157 return;
9158 }
9159
9160 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009161 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009162 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009163 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009164 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009165 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009166 which = 1;
9167 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009168 which = 2;
9169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009170
Larisse Voufo98b20f12013-07-19 23:00:19 +00009171 S.Diag(Templated->getLocation(),
9172 diag::note_ovl_candidate_inconsistent_deduction)
9173 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9174 << *DeductionFailure.getSecondArg();
9175 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009176 return;
9177 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009178
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009179 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009180 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009181 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009182 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009183 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009184 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009185 else {
9186 int index = 0;
9187 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9188 index = TTP->getIndex();
9189 else if (NonTypeTemplateParmDecl *NTTP
9190 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9191 index = NTTP->getIndex();
9192 else
9193 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009194 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009195 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009196 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009197 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009198 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009199 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200
Douglas Gregor02eb4832010-05-08 18:13:28 +00009201 case Sema::TDK_TooManyArguments:
9202 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009203 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009204 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009205
9206 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009207 S.Diag(Templated->getLocation(),
9208 diag::note_ovl_candidate_instantiation_depth);
9209 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009210 return;
9211
9212 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009213 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009214 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009215 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009216 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009217 TemplateArgString = " ";
9218 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009219 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009220 }
9221
Richard Smith6f8d2c62012-05-09 05:17:00 +00009222 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009223 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009224 if (PDiag && PDiag->second.getDiagID() ==
9225 diag::err_typename_nested_not_found_enable_if) {
9226 // FIXME: Use the source range of the condition, and the fully-qualified
9227 // name of the enable_if template. These are both present in PDiag.
9228 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9229 << "'enable_if'" << TemplateArgString;
9230 return;
9231 }
9232
Richard Smith9ca64612012-05-07 09:03:25 +00009233 // Format the SFINAE diagnostic into the argument string.
9234 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9235 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009236 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009237 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009238 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009239 SFINAEArgString = ": ";
9240 R = SourceRange(PDiag->first, PDiag->first);
9241 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9242 }
9243
Larisse Voufo98b20f12013-07-19 23:00:19 +00009244 S.Diag(Templated->getLocation(),
9245 diag::note_ovl_candidate_substitution_failure)
9246 << TemplateArgString << SFINAEArgString << R;
9247 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009248 return;
9249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009250
Richard Smith8c6eeb92013-01-31 04:03:12 +00009251 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009252 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9253 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009254 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009255 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009256 return;
9257 }
9258
Richard Trieue3732352013-04-08 21:11:40 +00009259 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009260 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009261 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9262 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009263 if (FirstTA.getKind() == TemplateArgument::Template &&
9264 SecondTA.getKind() == TemplateArgument::Template) {
9265 TemplateName FirstTN = FirstTA.getAsTemplate();
9266 TemplateName SecondTN = SecondTA.getAsTemplate();
9267 if (FirstTN.getKind() == TemplateName::Template &&
9268 SecondTN.getKind() == TemplateName::Template) {
9269 if (FirstTN.getAsTemplateDecl()->getName() ==
9270 SecondTN.getAsTemplateDecl()->getName()) {
9271 // FIXME: This fixes a bad diagnostic where both templates are named
9272 // the same. This particular case is a bit difficult since:
9273 // 1) It is passed as a string to the diagnostic printer.
9274 // 2) The diagnostic printer only attempts to find a better
9275 // name for types, not decls.
9276 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009277 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009278 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9279 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9280 return;
9281 }
9282 }
9283 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009284 // FIXME: For generic lambda parameters, check if the function is a lambda
9285 // call operator, and if so, emit a prettier and more informative
9286 // diagnostic that mentions 'auto' and lambda in addition to
9287 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009288 S.Diag(Templated->getLocation(),
9289 diag::note_ovl_candidate_non_deduced_mismatch)
9290 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009291 return;
Richard Trieue3732352013-04-08 21:11:40 +00009292 }
John McCall8b9ed552010-02-01 18:53:26 +00009293 // TODO: diagnose these individually, then kill off
9294 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009295 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009296 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9297 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009298 return;
9299 }
9300}
9301
Larisse Voufo98b20f12013-07-19 23:00:19 +00009302/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009303static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9304 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009305 unsigned TDK = Cand->DeductionFailure.Result;
9306 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9307 if (CheckArityMismatch(S, Cand, NumArgs))
9308 return;
9309 }
9310 DiagnoseBadDeduction(S, Cand->Function, // pattern
9311 Cand->DeductionFailure, NumArgs);
9312}
9313
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009314/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009315static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009316 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9317 FunctionDecl *Callee = Cand->Function;
9318
9319 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9320 CalleeTarget = S.IdentifyCUDATarget(Callee);
9321
9322 std::string FnDesc;
9323 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9324
9325 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009326 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9327
9328 // This could be an implicit constructor for which we could not infer the
9329 // target due to a collsion. Diagnose that case.
9330 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9331 if (Meth != nullptr && Meth->isImplicit()) {
9332 CXXRecordDecl *ParentClass = Meth->getParent();
9333 Sema::CXXSpecialMember CSM;
9334
9335 switch (FnKind) {
9336 default:
9337 return;
9338 case oc_implicit_default_constructor:
9339 CSM = Sema::CXXDefaultConstructor;
9340 break;
9341 case oc_implicit_copy_constructor:
9342 CSM = Sema::CXXCopyConstructor;
9343 break;
9344 case oc_implicit_move_constructor:
9345 CSM = Sema::CXXMoveConstructor;
9346 break;
9347 case oc_implicit_copy_assignment:
9348 CSM = Sema::CXXCopyAssignment;
9349 break;
9350 case oc_implicit_move_assignment:
9351 CSM = Sema::CXXMoveAssignment;
9352 break;
9353 };
9354
9355 bool ConstRHS = false;
9356 if (Meth->getNumParams()) {
9357 if (const ReferenceType *RT =
9358 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9359 ConstRHS = RT->getPointeeType().isConstQualified();
9360 }
9361 }
9362
9363 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9364 /* ConstRHS */ ConstRHS,
9365 /* Diagnose */ true);
9366 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009367}
9368
Richard Smith17c00b42014-11-12 01:24:00 +00009369static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009370 FunctionDecl *Callee = Cand->Function;
9371 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9372
9373 S.Diag(Callee->getLocation(),
9374 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9375 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9376}
9377
John McCall8b9ed552010-02-01 18:53:26 +00009378/// Generates a 'note' diagnostic for an overload candidate. We've
9379/// already generated a primary error at the call site.
9380///
9381/// It really does need to be a single diagnostic with its caret
9382/// pointed at the candidate declaration. Yes, this creates some
9383/// major challenges of technical writing. Yes, this makes pointing
9384/// out problems with specific arguments quite awkward. It's still
9385/// better than generating twenty screens of text for every failed
9386/// overload.
9387///
9388/// It would be great to be able to express per-candidate problems
9389/// more richly for those diagnostic clients that cared, but we'd
9390/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009391static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9392 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009393 FunctionDecl *Fn = Cand->Function;
9394
John McCall12f97bc2010-01-08 04:41:39 +00009395 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009396 if (Cand->Viable && (Fn->isDeleted() ||
9397 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009398 std::string FnDesc;
9399 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009400
9401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009402 << FnKind << FnDesc
9403 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009404 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009405 return;
John McCall12f97bc2010-01-08 04:41:39 +00009406 }
9407
John McCalle1ac8d12010-01-13 00:25:19 +00009408 // We don't really have anything else to say about viable candidates.
9409 if (Cand->Viable) {
9410 S.NoteOverloadCandidate(Fn);
9411 return;
9412 }
John McCall0d1da222010-01-12 00:44:57 +00009413
John McCall6a61b522010-01-13 09:16:55 +00009414 switch (Cand->FailureKind) {
9415 case ovl_fail_too_many_arguments:
9416 case ovl_fail_too_few_arguments:
9417 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009418
John McCall6a61b522010-01-13 09:16:55 +00009419 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009420 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009421
John McCall578a1f82014-12-14 01:46:53 +00009422 case ovl_fail_illegal_constructor: {
9423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9424 << (Fn->getPrimaryTemplate() ? 1 : 0);
9425 MaybeEmitInheritedConstructorNote(S, Fn);
9426 return;
9427 }
9428
John McCallfe796dd2010-01-23 05:17:32 +00009429 case ovl_fail_trivial_conversion:
9430 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009431 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009432 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009433
John McCall65eb8792010-02-25 01:37:24 +00009434 case ovl_fail_bad_conversion: {
9435 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009436 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009437 if (Cand->Conversions[I].isBad())
9438 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009439
John McCall6a61b522010-01-13 09:16:55 +00009440 // FIXME: this currently happens when we're called from SemaInit
9441 // when user-conversion overload fails. Figure out how to handle
9442 // those conditions and diagnose them well.
9443 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009444 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009445
9446 case ovl_fail_bad_target:
9447 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009448
9449 case ovl_fail_enable_if:
9450 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009451 }
John McCalld3224162010-01-08 00:58:21 +00009452}
9453
Richard Smith17c00b42014-11-12 01:24:00 +00009454static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009455 // Desugar the type of the surrogate down to a function type,
9456 // retaining as many typedefs as possible while still showing
9457 // the function type (and, therefore, its parameter types).
9458 QualType FnType = Cand->Surrogate->getConversionType();
9459 bool isLValueReference = false;
9460 bool isRValueReference = false;
9461 bool isPointer = false;
9462 if (const LValueReferenceType *FnTypeRef =
9463 FnType->getAs<LValueReferenceType>()) {
9464 FnType = FnTypeRef->getPointeeType();
9465 isLValueReference = true;
9466 } else if (const RValueReferenceType *FnTypeRef =
9467 FnType->getAs<RValueReferenceType>()) {
9468 FnType = FnTypeRef->getPointeeType();
9469 isRValueReference = true;
9470 }
9471 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9472 FnType = FnTypePtr->getPointeeType();
9473 isPointer = true;
9474 }
9475 // Desugar down to a function type.
9476 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9477 // Reconstruct the pointer/reference as appropriate.
9478 if (isPointer) FnType = S.Context.getPointerType(FnType);
9479 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9480 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9481
9482 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9483 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009484 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009485}
9486
Richard Smith17c00b42014-11-12 01:24:00 +00009487static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9488 SourceLocation OpLoc,
9489 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009490 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009491 std::string TypeStr("operator");
9492 TypeStr += Opc;
9493 TypeStr += "(";
9494 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009495 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009496 TypeStr += ")";
9497 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9498 } else {
9499 TypeStr += ", ";
9500 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9501 TypeStr += ")";
9502 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9503 }
9504}
9505
Richard Smith17c00b42014-11-12 01:24:00 +00009506static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9507 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009508 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009509 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9510 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009511 if (ICS.isBad()) break; // all meaningless after first invalid
9512 if (!ICS.isAmbiguous()) continue;
9513
John McCall5c32be02010-08-24 20:38:10 +00009514 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009515 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009516 }
9517}
9518
Larisse Voufo98b20f12013-07-19 23:00:19 +00009519static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009520 if (Cand->Function)
9521 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009522 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009523 return Cand->Surrogate->getLocation();
9524 return SourceLocation();
9525}
9526
Larisse Voufo98b20f12013-07-19 23:00:19 +00009527static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009528 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009529 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009530 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009531
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009532 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009533 case Sema::TDK_Incomplete:
9534 return 1;
9535
9536 case Sema::TDK_Underqualified:
9537 case Sema::TDK_Inconsistent:
9538 return 2;
9539
9540 case Sema::TDK_SubstitutionFailure:
9541 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009542 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009543 return 3;
9544
9545 case Sema::TDK_InstantiationDepth:
9546 case Sema::TDK_FailedOverloadResolution:
9547 return 4;
9548
9549 case Sema::TDK_InvalidExplicitArguments:
9550 return 5;
9551
9552 case Sema::TDK_TooManyArguments:
9553 case Sema::TDK_TooFewArguments:
9554 return 6;
9555 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009556 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009557}
9558
Richard Smith17c00b42014-11-12 01:24:00 +00009559namespace {
John McCallad2587a2010-01-12 00:48:53 +00009560struct CompareOverloadCandidatesForDisplay {
9561 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009562 size_t NumArgs;
9563
9564 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9565 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009566
9567 bool operator()(const OverloadCandidate *L,
9568 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009569 // Fast-path this check.
9570 if (L == R) return false;
9571
John McCall12f97bc2010-01-08 04:41:39 +00009572 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009573 if (L->Viable) {
9574 if (!R->Viable) return true;
9575
9576 // TODO: introduce a tri-valued comparison for overload
9577 // candidates. Would be more worthwhile if we had a sort
9578 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009579 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9580 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009581 } else if (R->Viable)
9582 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009583
John McCall3712d9e2010-01-15 23:32:50 +00009584 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009585
John McCall3712d9e2010-01-15 23:32:50 +00009586 // Criteria by which we can sort non-viable candidates:
9587 if (!L->Viable) {
9588 // 1. Arity mismatches come after other candidates.
9589 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009590 L->FailureKind == ovl_fail_too_few_arguments) {
9591 if (R->FailureKind == ovl_fail_too_many_arguments ||
9592 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009593 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9594 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9595 if (LDist == RDist) {
9596 if (L->FailureKind == R->FailureKind)
9597 // Sort non-surrogates before surrogates.
9598 return !L->IsSurrogate && R->IsSurrogate;
9599 // Sort candidates requiring fewer parameters than there were
9600 // arguments given after candidates requiring more parameters
9601 // than there were arguments given.
9602 return L->FailureKind == ovl_fail_too_many_arguments;
9603 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009604 return LDist < RDist;
9605 }
John McCall3712d9e2010-01-15 23:32:50 +00009606 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009607 }
John McCall3712d9e2010-01-15 23:32:50 +00009608 if (R->FailureKind == ovl_fail_too_many_arguments ||
9609 R->FailureKind == ovl_fail_too_few_arguments)
9610 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009611
John McCallfe796dd2010-01-23 05:17:32 +00009612 // 2. Bad conversions come first and are ordered by the number
9613 // of bad conversions and quality of good conversions.
9614 if (L->FailureKind == ovl_fail_bad_conversion) {
9615 if (R->FailureKind != ovl_fail_bad_conversion)
9616 return true;
9617
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009618 // The conversion that can be fixed with a smaller number of changes,
9619 // comes first.
9620 unsigned numLFixes = L->Fix.NumConversionsFixed;
9621 unsigned numRFixes = R->Fix.NumConversionsFixed;
9622 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9623 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009624 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009625 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009626 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009627
John McCallfe796dd2010-01-23 05:17:32 +00009628 // If there's any ordering between the defined conversions...
9629 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009630 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009631
9632 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009633 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009634 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009635 switch (CompareImplicitConversionSequences(S,
9636 L->Conversions[I],
9637 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009638 case ImplicitConversionSequence::Better:
9639 leftBetter++;
9640 break;
9641
9642 case ImplicitConversionSequence::Worse:
9643 leftBetter--;
9644 break;
9645
9646 case ImplicitConversionSequence::Indistinguishable:
9647 break;
9648 }
9649 }
9650 if (leftBetter > 0) return true;
9651 if (leftBetter < 0) return false;
9652
9653 } else if (R->FailureKind == ovl_fail_bad_conversion)
9654 return false;
9655
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009656 if (L->FailureKind == ovl_fail_bad_deduction) {
9657 if (R->FailureKind != ovl_fail_bad_deduction)
9658 return true;
9659
9660 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9661 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009662 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009663 } else if (R->FailureKind == ovl_fail_bad_deduction)
9664 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009665
John McCall3712d9e2010-01-15 23:32:50 +00009666 // TODO: others?
9667 }
9668
9669 // Sort everything else by location.
9670 SourceLocation LLoc = GetLocationForCandidate(L);
9671 SourceLocation RLoc = GetLocationForCandidate(R);
9672
9673 // Put candidates without locations (e.g. builtins) at the end.
9674 if (LLoc.isInvalid()) return false;
9675 if (RLoc.isInvalid()) return true;
9676
9677 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009678 }
9679};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009680}
John McCall12f97bc2010-01-08 04:41:39 +00009681
John McCallfe796dd2010-01-23 05:17:32 +00009682/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009683/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009684static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9685 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009686 assert(!Cand->Viable);
9687
9688 // Don't do anything on failures other than bad conversion.
9689 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9690
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009691 // We only want the FixIts if all the arguments can be corrected.
9692 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009693 // Use a implicit copy initialization to check conversion fixes.
9694 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009695
John McCallfe796dd2010-01-23 05:17:32 +00009696 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009697 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009698 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009699 while (true) {
9700 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9701 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009702 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009703 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009704 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009705 }
John McCallfe796dd2010-01-23 05:17:32 +00009706 }
9707
9708 if (ConvIdx == ConvCount)
9709 return;
9710
John McCall65eb8792010-02-25 01:37:24 +00009711 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9712 "remaining conversion is initialized?");
9713
Douglas Gregoradc7a702010-04-16 17:45:54 +00009714 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009715 // operation somehow.
9716 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009717
9718 const FunctionProtoType* Proto;
9719 unsigned ArgIdx = ConvIdx;
9720
9721 if (Cand->IsSurrogate) {
9722 QualType ConvType
9723 = Cand->Surrogate->getConversionType().getNonReferenceType();
9724 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9725 ConvType = ConvPtrType->getPointeeType();
9726 Proto = ConvType->getAs<FunctionProtoType>();
9727 ArgIdx--;
9728 } else if (Cand->Function) {
9729 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9730 if (isa<CXXMethodDecl>(Cand->Function) &&
9731 !isa<CXXConstructorDecl>(Cand->Function))
9732 ArgIdx--;
9733 } else {
9734 // Builtin binary operator with a bad first conversion.
9735 assert(ConvCount <= 3);
9736 for (; ConvIdx != ConvCount; ++ConvIdx)
9737 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009738 = TryCopyInitialization(S, Args[ConvIdx],
9739 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009740 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009741 /*InOverloadResolution*/ true,
9742 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009743 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009744 return;
9745 }
9746
9747 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009748 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009749 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009750 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009751 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9752 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9753 /*InOverloadResolution=*/true,
9754 /*AllowObjCWritebackConversion=*/
9755 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009756 // Store the FixIt in the candidate if it exists.
9757 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009758 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009759 }
John McCallfe796dd2010-01-23 05:17:32 +00009760 else
9761 Cand->Conversions[ConvIdx].setEllipsis();
9762 }
9763}
9764
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009765/// PrintOverloadCandidates - When overload resolution fails, prints
9766/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009767/// set.
John McCall5c32be02010-08-24 20:38:10 +00009768void OverloadCandidateSet::NoteCandidates(Sema &S,
9769 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009770 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009771 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009772 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009773 // Sort the candidates by viability and position. Sorting directly would
9774 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009775 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009776 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9777 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009778 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009779 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009780 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009781 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009782 if (Cand->Function || Cand->IsSurrogate)
9783 Cands.push_back(Cand);
9784 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9785 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009786 }
9787 }
9788
John McCallad2587a2010-01-12 00:48:53 +00009789 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009790 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009791
John McCall0d1da222010-01-12 00:44:57 +00009792 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009793
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009794 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009795 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009796 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009797 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9798 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009799
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009800 // Set an arbitrary limit on the number of candidate functions we'll spam
9801 // the user with. FIXME: This limit should depend on details of the
9802 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009803 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009804 break;
9805 }
9806 ++CandsShown;
9807
John McCalld3224162010-01-08 00:58:21 +00009808 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009809 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009810 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009811 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009812 else {
9813 assert(Cand->Viable &&
9814 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009815 // Generally we only see ambiguities including viable builtin
9816 // operators if overload resolution got screwed up by an
9817 // ambiguous user-defined conversion.
9818 //
9819 // FIXME: It's quite possible for different conversions to see
9820 // different ambiguities, though.
9821 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009822 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009823 ReportedAmbiguousConversions = true;
9824 }
John McCalld3224162010-01-08 00:58:21 +00009825
John McCall0d1da222010-01-12 00:44:57 +00009826 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009827 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009828 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009829 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009830
9831 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009832 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009833}
9834
Larisse Voufo98b20f12013-07-19 23:00:19 +00009835static SourceLocation
9836GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9837 return Cand->Specialization ? Cand->Specialization->getLocation()
9838 : SourceLocation();
9839}
9840
Richard Smith17c00b42014-11-12 01:24:00 +00009841namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009842struct CompareTemplateSpecCandidatesForDisplay {
9843 Sema &S;
9844 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9845
9846 bool operator()(const TemplateSpecCandidate *L,
9847 const TemplateSpecCandidate *R) {
9848 // Fast-path this check.
9849 if (L == R)
9850 return false;
9851
9852 // Assuming that both candidates are not matches...
9853
9854 // Sort by the ranking of deduction failures.
9855 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9856 return RankDeductionFailure(L->DeductionFailure) <
9857 RankDeductionFailure(R->DeductionFailure);
9858
9859 // Sort everything else by location.
9860 SourceLocation LLoc = GetLocationForCandidate(L);
9861 SourceLocation RLoc = GetLocationForCandidate(R);
9862
9863 // Put candidates without locations (e.g. builtins) at the end.
9864 if (LLoc.isInvalid())
9865 return false;
9866 if (RLoc.isInvalid())
9867 return true;
9868
9869 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9870 }
9871};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009872}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009873
9874/// Diagnose a template argument deduction failure.
9875/// We are treating these failures as overload failures due to bad
9876/// deductions.
9877void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9878 DiagnoseBadDeduction(S, Specialization, // pattern
9879 DeductionFailure, /*NumArgs=*/0);
9880}
9881
9882void TemplateSpecCandidateSet::destroyCandidates() {
9883 for (iterator i = begin(), e = end(); i != e; ++i) {
9884 i->DeductionFailure.Destroy();
9885 }
9886}
9887
9888void TemplateSpecCandidateSet::clear() {
9889 destroyCandidates();
9890 Candidates.clear();
9891}
9892
9893/// NoteCandidates - When no template specialization match is found, prints
9894/// diagnostic messages containing the non-matching specializations that form
9895/// the candidate set.
9896/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9897/// OCD == OCD_AllCandidates and Cand->Viable == false.
9898void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9899 // Sort the candidates by position (assuming no candidate is a match).
9900 // Sorting directly would be prohibitive, so we make a set of pointers
9901 // and sort those.
9902 SmallVector<TemplateSpecCandidate *, 32> Cands;
9903 Cands.reserve(size());
9904 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9905 if (Cand->Specialization)
9906 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009907 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009908 // in general, want to list every possible builtin candidate.
9909 }
9910
9911 std::sort(Cands.begin(), Cands.end(),
9912 CompareTemplateSpecCandidatesForDisplay(S));
9913
9914 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9915 // for generalization purposes (?).
9916 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9917
9918 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9919 unsigned CandsShown = 0;
9920 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9921 TemplateSpecCandidate *Cand = *I;
9922
9923 // Set an arbitrary limit on the number of candidates we'll spam
9924 // the user with. FIXME: This limit should depend on details of the
9925 // candidate list.
9926 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9927 break;
9928 ++CandsShown;
9929
9930 assert(Cand->Specialization &&
9931 "Non-matching built-in candidates are not added to Cands.");
9932 Cand->NoteDeductionFailure(S);
9933 }
9934
9935 if (I != E)
9936 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9937}
9938
Douglas Gregorb491ed32011-02-19 21:32:49 +00009939// [PossiblyAFunctionType] --> [Return]
9940// NonFunctionType --> NonFunctionType
9941// R (A) --> R(A)
9942// R (*)(A) --> R (A)
9943// R (&)(A) --> R (A)
9944// R (S::*)(A) --> R (A)
9945QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9946 QualType Ret = PossiblyAFunctionType;
9947 if (const PointerType *ToTypePtr =
9948 PossiblyAFunctionType->getAs<PointerType>())
9949 Ret = ToTypePtr->getPointeeType();
9950 else if (const ReferenceType *ToTypeRef =
9951 PossiblyAFunctionType->getAs<ReferenceType>())
9952 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009953 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009954 PossiblyAFunctionType->getAs<MemberPointerType>())
9955 Ret = MemTypePtr->getPointeeType();
9956 Ret =
9957 Context.getCanonicalType(Ret).getUnqualifiedType();
9958 return Ret;
9959}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009960
Richard Smith17c00b42014-11-12 01:24:00 +00009961namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009962// A helper class to help with address of function resolution
9963// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009964class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009965 Sema& S;
9966 Expr* SourceExpr;
9967 const QualType& TargetType;
9968 QualType TargetFunctionType; // Extracted function type from target type
9969
9970 bool Complain;
9971 //DeclAccessPair& ResultFunctionAccessPair;
9972 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009973
Douglas Gregorb491ed32011-02-19 21:32:49 +00009974 bool TargetTypeIsNonStaticMemberFunction;
9975 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009976 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +00009977 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009978
Douglas Gregorb491ed32011-02-19 21:32:49 +00009979 OverloadExpr::FindResult OvlExprInfo;
9980 OverloadExpr *OvlExpr;
9981 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009982 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009983 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009984
Douglas Gregorb491ed32011-02-19 21:32:49 +00009985public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009986 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9987 const QualType &TargetType, bool Complain)
9988 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9989 Complain(Complain), Context(S.getASTContext()),
9990 TargetTypeIsNonStaticMemberFunction(
9991 !!TargetType->getAs<MemberPointerType>()),
9992 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009993 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +00009994 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009995 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9996 OvlExpr(OvlExprInfo.Expression),
9997 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009998 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009999
David Majnemera4f7c7a2013-08-01 06:13:59 +000010000 if (TargetFunctionType->isFunctionType()) {
10001 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10002 if (!UME->isImplicitAccess() &&
10003 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10004 StaticMemberFunctionFromBoundPointer = true;
10005 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10006 DeclAccessPair dap;
10007 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10008 OvlExpr, false, &dap)) {
10009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10010 if (!Method->isStatic()) {
10011 // If the target type is a non-function type and the function found
10012 // is a non-static member function, pretend as if that was the
10013 // target, it's the only possible type to end up with.
10014 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010015
David Majnemera4f7c7a2013-08-01 06:13:59 +000010016 // And skip adding the function if its not in the proper form.
10017 // We'll diagnose this due to an empty set of functions.
10018 if (!OvlExprInfo.HasFormOfMemberPointer)
10019 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010020 }
10021
David Majnemera4f7c7a2013-08-01 06:13:59 +000010022 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010023 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010024 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010025 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010026
10027 if (OvlExpr->hasExplicitTemplateArgs())
10028 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010029
Douglas Gregorb491ed32011-02-19 21:32:49 +000010030 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10031 // C++ [over.over]p4:
10032 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010033 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010034 if (FoundNonTemplateFunction)
10035 EliminateAllTemplateMatches();
10036 else
10037 EliminateAllExceptMostSpecializedTemplate();
10038 }
10039 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010040
10041 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10042 Matches.size() > 1)
10043 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010044 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010045
10046 bool hasComplained() const { return HasComplained; }
10047
Douglas Gregorb491ed32011-02-19 21:32:49 +000010048private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010049 // Is A considered a better overload candidate for the desired type than B?
10050 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10051 return hasBetterEnableIfAttrs(S, A, B);
10052 }
10053
10054 // Returns true if we've eliminated any (read: all but one) candidates, false
10055 // otherwise.
10056 bool eliminiateSuboptimalOverloadCandidates() {
10057 // Same algorithm as overload resolution -- one pass to pick the "best",
10058 // another pass to be sure that nothing is better than the best.
10059 auto Best = Matches.begin();
10060 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10061 if (isBetterCandidate(I->second, Best->second))
10062 Best = I;
10063
10064 const FunctionDecl *BestFn = Best->second;
10065 auto IsBestOrInferiorToBest = [this, BestFn](
10066 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10067 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10068 };
10069
10070 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10071 // option, so we can potentially give the user a better error
10072 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10073 return false;
10074 Matches[0] = *Best;
10075 Matches.resize(1);
10076 return true;
10077 }
10078
Douglas Gregorb491ed32011-02-19 21:32:49 +000010079 bool isTargetTypeAFunction() const {
10080 return TargetFunctionType->isFunctionType();
10081 }
10082
10083 // [ToType] [Return]
10084
10085 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10086 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10087 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10088 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10089 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10090 }
10091
10092 // return true if any matching specializations were found
10093 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10094 const DeclAccessPair& CurAccessFunPair) {
10095 if (CXXMethodDecl *Method
10096 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10097 // Skip non-static function templates when converting to pointer, and
10098 // static when converting to member pointer.
10099 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10100 return false;
10101 }
10102 else if (TargetTypeIsNonStaticMemberFunction)
10103 return false;
10104
10105 // C++ [over.over]p2:
10106 // If the name is a function template, template argument deduction is
10107 // done (14.8.2.2), and if the argument deduction succeeds, the
10108 // resulting template argument list is used to generate a single
10109 // function template specialization, which is added to the set of
10110 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010111 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010112 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010113 if (Sema::TemplateDeductionResult Result
10114 = S.DeduceTemplateArguments(FunctionTemplate,
10115 &OvlExplicitTemplateArgs,
10116 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010117 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010118 // Make a note of the failed deduction for diagnostics.
10119 FailedCandidates.addCandidate()
10120 .set(FunctionTemplate->getTemplatedDecl(),
10121 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010122 return false;
10123 }
10124
Douglas Gregor19a41f12013-04-17 08:45:07 +000010125 // Template argument deduction ensures that we have an exact match or
10126 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010127 // This function template specicalization works.
10128 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010129 assert(S.isSameOrCompatibleFunctionType(
10130 Context.getCanonicalType(Specialization->getType()),
George Burgess IV5f21c712015-10-12 19:57:04 +000010131 Context.getCanonicalType(TargetFunctionType)) ||
10132 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType()));
10133
10134 if (!isFunctionAlwaysEnabled(S.Context, Specialization))
10135 return false;
10136
Douglas Gregorb491ed32011-02-19 21:32:49 +000010137 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10138 return true;
10139 }
10140
10141 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10142 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010143 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010144 // Skip non-static functions when converting to pointer, and static
10145 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010146 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10147 return false;
10148 }
10149 else if (TargetTypeIsNonStaticMemberFunction)
10150 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010151
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010152 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010153 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010154 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010155 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010156 return false;
10157
Richard Smith2a7d4812013-05-04 07:00:32 +000010158 // If any candidate has a placeholder return type, trigger its deduction
10159 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010160 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010161 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010162 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10163 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010164 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010165 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010166
George Burgess IV5f21c712015-10-12 19:57:04 +000010167 if (!isFunctionAlwaysEnabled(S.Context, FunDecl))
10168 return false;
10169
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010170 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010171 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10172 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010173 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010174 ResultTy) ||
10175 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10176 Matches.push_back(std::make_pair(
10177 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010178 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010179 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010180 }
Mike Stump11289f42009-09-09 15:08:12 +000010181 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010182
10183 return false;
10184 }
10185
10186 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10187 bool Ret = false;
10188
10189 // If the overload expression doesn't have the form of a pointer to
10190 // member, don't try to convert it to a pointer-to-member type.
10191 if (IsInvalidFormOfPointerToMemberFunction())
10192 return false;
10193
10194 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10195 E = OvlExpr->decls_end();
10196 I != E; ++I) {
10197 // Look through any using declarations to find the underlying function.
10198 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10199
10200 // C++ [over.over]p3:
10201 // Non-member functions and static member functions match
10202 // targets of type "pointer-to-function" or "reference-to-function."
10203 // Nonstatic member functions match targets of
10204 // type "pointer-to-member-function."
10205 // Note that according to DR 247, the containing class does not matter.
10206 if (FunctionTemplateDecl *FunctionTemplate
10207 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10208 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10209 Ret = true;
10210 }
10211 // If we have explicit template arguments supplied, skip non-templates.
10212 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10213 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10214 Ret = true;
10215 }
10216 assert(Ret || Matches.empty());
10217 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010218 }
10219
Douglas Gregorb491ed32011-02-19 21:32:49 +000010220 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010221 // [...] and any given function template specialization F1 is
10222 // eliminated if the set contains a second function template
10223 // specialization whose function template is more specialized
10224 // than the function template of F1 according to the partial
10225 // ordering rules of 14.5.5.2.
10226
10227 // The algorithm specified above is quadratic. We instead use a
10228 // two-pass algorithm (similar to the one used to identify the
10229 // best viable function in an overload set) that identifies the
10230 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010231
10232 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10233 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10234 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010235
Larisse Voufo98b20f12013-07-19 23:00:19 +000010236 // TODO: It looks like FailedCandidates does not serve much purpose
10237 // here, since the no_viable diagnostic has index 0.
10238 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010239 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010240 SourceExpr->getLocStart(), S.PDiag(),
10241 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10242 .second->getDeclName(),
10243 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10244 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010245
Douglas Gregorb491ed32011-02-19 21:32:49 +000010246 if (Result != MatchesCopy.end()) {
10247 // Make it the first and only element
10248 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10249 Matches[0].second = cast<FunctionDecl>(*Result);
10250 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010251 } else
10252 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010254
Douglas Gregorb491ed32011-02-19 21:32:49 +000010255 void EliminateAllTemplateMatches() {
10256 // [...] any function template specializations in the set are
10257 // eliminated if the set also contains a non-template function, [...]
10258 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010259 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010260 ++I;
10261 else {
10262 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010263 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010264 }
10265 }
10266 }
10267
Artem Belevich94a55e82015-09-22 17:22:59 +000010268 void EliminateSuboptimalCudaMatches() {
10269 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10270 }
10271
Douglas Gregorb491ed32011-02-19 21:32:49 +000010272public:
10273 void ComplainNoMatchesFound() const {
10274 assert(Matches.empty());
10275 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10276 << OvlExpr->getName() << TargetFunctionType
10277 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010278 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010279 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10280 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010281 else {
10282 // We have some deduction failure messages. Use them to diagnose
10283 // the function templates, and diagnose the non-template candidates
10284 // normally.
10285 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10286 IEnd = OvlExpr->decls_end();
10287 I != IEnd; ++I)
10288 if (FunctionDecl *Fun =
10289 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV5f21c712015-10-12 19:57:04 +000010290 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10291 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010292 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10293 }
10294 }
10295
Douglas Gregorb491ed32011-02-19 21:32:49 +000010296 bool IsInvalidFormOfPointerToMemberFunction() const {
10297 return TargetTypeIsNonStaticMemberFunction &&
10298 !OvlExprInfo.HasFormOfMemberPointer;
10299 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010300
Douglas Gregorb491ed32011-02-19 21:32:49 +000010301 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10302 // TODO: Should we condition this on whether any functions might
10303 // have matched, or is it more appropriate to do that in callers?
10304 // TODO: a fixit wouldn't hurt.
10305 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10306 << TargetType << OvlExpr->getSourceRange();
10307 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010308
10309 bool IsStaticMemberFunctionFromBoundPointer() const {
10310 return StaticMemberFunctionFromBoundPointer;
10311 }
10312
10313 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10314 S.Diag(OvlExpr->getLocStart(),
10315 diag::err_invalid_form_pointer_member_function)
10316 << OvlExpr->getSourceRange();
10317 }
10318
Douglas Gregorb491ed32011-02-19 21:32:49 +000010319 void ComplainOfInvalidConversion() const {
10320 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10321 << OvlExpr->getName() << TargetType;
10322 }
10323
10324 void ComplainMultipleMatchesFound() const {
10325 assert(Matches.size() > 1);
10326 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10327 << OvlExpr->getName()
10328 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010329 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10330 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010331 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010332
10333 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10334
Douglas Gregorb491ed32011-02-19 21:32:49 +000010335 int getNumMatches() const { return Matches.size(); }
10336
10337 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010338 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010339 return Matches[0].second;
10340 }
10341
10342 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010343 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010344 return &Matches[0].first;
10345 }
10346};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010347}
Richard Smith17c00b42014-11-12 01:24:00 +000010348
Douglas Gregorb491ed32011-02-19 21:32:49 +000010349/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10350/// an overloaded function (C++ [over.over]), where @p From is an
10351/// expression with overloaded function type and @p ToType is the type
10352/// we're trying to resolve to. For example:
10353///
10354/// @code
10355/// int f(double);
10356/// int f(int);
10357///
10358/// int (*pfd)(double) = f; // selects f(double)
10359/// @endcode
10360///
10361/// This routine returns the resulting FunctionDecl if it could be
10362/// resolved, and NULL otherwise. When @p Complain is true, this
10363/// routine will emit diagnostics if there is an error.
10364FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010365Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10366 QualType TargetType,
10367 bool Complain,
10368 DeclAccessPair &FoundResult,
10369 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010370 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010371
10372 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10373 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010374 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010375 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010376 bool ShouldComplain = Complain && !Resolver.hasComplained();
10377 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010378 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10379 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10380 else
10381 Resolver.ComplainNoMatchesFound();
10382 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010383 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010384 Resolver.ComplainMultipleMatchesFound();
10385 else if (NumMatches == 1) {
10386 Fn = Resolver.getMatchingFunctionDecl();
10387 assert(Fn);
10388 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010389 if (Complain) {
10390 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10391 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10392 else
10393 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10394 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010395 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010396
10397 if (pHadMultipleCandidates)
10398 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010399 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010400}
10401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010402/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010403/// resolve that overloaded function expression down to a single function.
10404///
10405/// This routine can only resolve template-ids that refer to a single function
10406/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010407/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010408/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010409///
10410/// If no template-ids are found, no diagnostics are emitted and NULL is
10411/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010412FunctionDecl *
10413Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10414 bool Complain,
10415 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010416 // C++ [over.over]p1:
10417 // [...] [Note: any redundant set of parentheses surrounding the
10418 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010419 // C++ [over.over]p1:
10420 // [...] The overloaded function name can be preceded by the &
10421 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010422
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010423 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010424 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010425 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010426
10427 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010428 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010429 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010430
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010431 // Look through all of the overloaded functions, searching for one
10432 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010433 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010434 for (UnresolvedSetIterator I = ovl->decls_begin(),
10435 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010436 // C++0x [temp.arg.explicit]p3:
10437 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010438 // where deduction is not done, if a template argument list is
10439 // specified and it, along with any default template arguments,
10440 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010441 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010442 FunctionTemplateDecl *FunctionTemplate
10443 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010444
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010445 // C++ [over.over]p2:
10446 // If the name is a function template, template argument deduction is
10447 // done (14.8.2.2), and if the argument deduction succeeds, the
10448 // resulting template argument list is used to generate a single
10449 // function template specialization, which is added to the set of
10450 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010451 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010452 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010453 if (TemplateDeductionResult Result
10454 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010455 Specialization, Info,
10456 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010457 // Make a note of the failed deduction for diagnostics.
10458 // TODO: Actually use the failed-deduction info?
10459 FailedCandidates.addCandidate()
10460 .set(FunctionTemplate->getTemplatedDecl(),
10461 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010462 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010463 }
10464
John McCall0009fcc2011-04-26 20:42:42 +000010465 assert(Specialization && "no specialization and no error?");
10466
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010467 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010468 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010469 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010470 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10471 << ovl->getName();
10472 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010473 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010474 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010475 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010476
John McCall0009fcc2011-04-26 20:42:42 +000010477 Matched = Specialization;
10478 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010480
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010481 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010482 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010483 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010484 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010485
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010486 return Matched;
10487}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010488
Douglas Gregor1beec452011-03-12 01:48:56 +000010489
10490
10491
John McCall50a2c2c2011-10-11 23:14:30 +000010492// Resolve and fix an overloaded expression that can be resolved
10493// because it identifies a single function template specialization.
10494//
Douglas Gregor1beec452011-03-12 01:48:56 +000010495// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010496//
10497// Return true if it was logically possible to so resolve the
10498// expression, regardless of whether or not it succeeded. Always
10499// returns true if 'complain' is set.
10500bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10501 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010502 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010503 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010504 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010505 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010506
John McCall50a2c2c2011-10-11 23:14:30 +000010507 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010508
John McCall0009fcc2011-04-26 20:42:42 +000010509 DeclAccessPair found;
10510 ExprResult SingleFunctionExpression;
10511 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10512 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010513 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010514 SrcExpr = ExprError();
10515 return true;
10516 }
John McCall0009fcc2011-04-26 20:42:42 +000010517
10518 // It is only correct to resolve to an instance method if we're
10519 // resolving a form that's permitted to be a pointer to member.
10520 // Otherwise we'll end up making a bound member expression, which
10521 // is illegal in all the contexts we resolve like this.
10522 if (!ovl.HasFormOfMemberPointer &&
10523 isa<CXXMethodDecl>(fn) &&
10524 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010525 if (!complain) return false;
10526
10527 Diag(ovl.Expression->getExprLoc(),
10528 diag::err_bound_member_function)
10529 << 0 << ovl.Expression->getSourceRange();
10530
10531 // TODO: I believe we only end up here if there's a mix of
10532 // static and non-static candidates (otherwise the expression
10533 // would have 'bound member' type, not 'overload' type).
10534 // Ideally we would note which candidate was chosen and why
10535 // the static candidates were rejected.
10536 SrcExpr = ExprError();
10537 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010538 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010539
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010540 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010541 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010542 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010543
10544 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010545 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010546 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010547 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010548 if (SingleFunctionExpression.isInvalid()) {
10549 SrcExpr = ExprError();
10550 return true;
10551 }
10552 }
John McCall0009fcc2011-04-26 20:42:42 +000010553 }
10554
10555 if (!SingleFunctionExpression.isUsable()) {
10556 if (complain) {
10557 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10558 << ovl.Expression->getName()
10559 << DestTypeForComplaining
10560 << OpRangeForComplaining
10561 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010562 NoteAllOverloadCandidates(SrcExpr.get());
10563
10564 SrcExpr = ExprError();
10565 return true;
10566 }
10567
10568 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010569 }
10570
John McCall50a2c2c2011-10-11 23:14:30 +000010571 SrcExpr = SingleFunctionExpression;
10572 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010573}
10574
Douglas Gregorcabea402009-09-22 15:41:20 +000010575/// \brief Add a single candidate to the overload set.
10576static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010577 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010578 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010579 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010580 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010581 bool PartialOverloading,
10582 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010583 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010584 if (isa<UsingShadowDecl>(Callee))
10585 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10586
Douglas Gregorcabea402009-09-22 15:41:20 +000010587 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010588 if (ExplicitTemplateArgs) {
10589 assert(!KnownValid && "Explicit template arguments?");
10590 return;
10591 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010592 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10593 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010594 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010595 return;
John McCalld14a8642009-11-21 08:51:07 +000010596 }
10597
10598 if (FunctionTemplateDecl *FuncTemplate
10599 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010600 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010601 ExplicitTemplateArgs, Args, CandidateSet,
10602 /*SuppressUsedConversions=*/false,
10603 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010604 return;
10605 }
10606
Richard Smith95ce4f62011-06-26 22:19:54 +000010607 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010608}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010609
Douglas Gregorcabea402009-09-22 15:41:20 +000010610/// \brief Add the overload candidates named by callee and/or found by argument
10611/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010612void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010613 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010614 OverloadCandidateSet &CandidateSet,
10615 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010616
10617#ifndef NDEBUG
10618 // Verify that ArgumentDependentLookup is consistent with the rules
10619 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010620 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010621 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10622 // and let Y be the lookup set produced by argument dependent
10623 // lookup (defined as follows). If X contains
10624 //
10625 // -- a declaration of a class member, or
10626 //
10627 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010628 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010629 //
10630 // -- a declaration that is neither a function or a function
10631 // template
10632 //
10633 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010634
John McCall57500772009-12-16 12:17:52 +000010635 if (ULE->requiresADL()) {
10636 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10637 E = ULE->decls_end(); I != E; ++I) {
10638 assert(!(*I)->getDeclContext()->isRecord());
10639 assert(isa<UsingShadowDecl>(*I) ||
10640 !(*I)->getDeclContext()->isFunctionOrMethod());
10641 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010642 }
10643 }
10644#endif
10645
John McCall57500772009-12-16 12:17:52 +000010646 // It would be nice to avoid this copy.
10647 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010648 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010649 if (ULE->hasExplicitTemplateArgs()) {
10650 ULE->copyTemplateArgumentsInto(TABuffer);
10651 ExplicitTemplateArgs = &TABuffer;
10652 }
10653
10654 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10655 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010656 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10657 CandidateSet, PartialOverloading,
10658 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010659
John McCall57500772009-12-16 12:17:52 +000010660 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010661 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010662 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010663 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010664}
John McCalld681c392009-12-16 08:11:27 +000010665
Richard Smith0603bbb2013-06-12 22:56:54 +000010666/// Determine whether a declaration with the specified name could be moved into
10667/// a different namespace.
10668static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10669 switch (Name.getCXXOverloadedOperator()) {
10670 case OO_New: case OO_Array_New:
10671 case OO_Delete: case OO_Array_Delete:
10672 return false;
10673
10674 default:
10675 return true;
10676 }
10677}
10678
Richard Smith998a5912011-06-05 22:42:48 +000010679/// Attempt to recover from an ill-formed use of a non-dependent name in a
10680/// template, where the non-dependent name was declared after the template
10681/// was defined. This is common in code written for a compilers which do not
10682/// correctly implement two-stage name lookup.
10683///
10684/// Returns true if a viable candidate was found and a diagnostic was issued.
10685static bool
10686DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10687 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010688 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010689 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010690 ArrayRef<Expr *> Args,
10691 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010692 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10693 return false;
10694
10695 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010696 if (DC->isTransparentContext())
10697 continue;
10698
Richard Smith998a5912011-06-05 22:42:48 +000010699 SemaRef.LookupQualifiedName(R, DC);
10700
10701 if (!R.empty()) {
10702 R.suppressDiagnostics();
10703
10704 if (isa<CXXRecordDecl>(DC)) {
10705 // Don't diagnose names we find in classes; we get much better
10706 // diagnostics for these from DiagnoseEmptyLookup.
10707 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010708 if (DoDiagnoseEmptyLookup)
10709 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010710 return false;
10711 }
10712
Richard Smith100b24a2014-04-17 01:52:14 +000010713 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010714 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10715 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010716 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010717 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010718
10719 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010720 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010721 // No viable functions. Don't bother the user with notes for functions
10722 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010723 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010724 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010725 }
Richard Smith998a5912011-06-05 22:42:48 +000010726
10727 // Find the namespaces where ADL would have looked, and suggest
10728 // declaring the function there instead.
10729 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10730 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010731 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010732 AssociatedNamespaces,
10733 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010734 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010735 if (canBeDeclaredInNamespace(R.getLookupName())) {
10736 DeclContext *Std = SemaRef.getStdNamespace();
10737 for (Sema::AssociatedNamespaceSet::iterator
10738 it = AssociatedNamespaces.begin(),
10739 end = AssociatedNamespaces.end(); it != end; ++it) {
10740 // Never suggest declaring a function within namespace 'std'.
10741 if (Std && Std->Encloses(*it))
10742 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010743
Richard Smith0603bbb2013-06-12 22:56:54 +000010744 // Never suggest declaring a function within a namespace with a
10745 // reserved name, like __gnu_cxx.
10746 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10747 if (NS &&
10748 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10749 continue;
10750
10751 SuggestedNamespaces.insert(*it);
10752 }
Richard Smith998a5912011-06-05 22:42:48 +000010753 }
10754
10755 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10756 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010757 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010758 SemaRef.Diag(Best->Function->getLocation(),
10759 diag::note_not_found_by_two_phase_lookup)
10760 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010761 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010762 SemaRef.Diag(Best->Function->getLocation(),
10763 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010764 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010765 } else {
10766 // FIXME: It would be useful to list the associated namespaces here,
10767 // but the diagnostics infrastructure doesn't provide a way to produce
10768 // a localized representation of a list of items.
10769 SemaRef.Diag(Best->Function->getLocation(),
10770 diag::note_not_found_by_two_phase_lookup)
10771 << R.getLookupName() << 2;
10772 }
10773
10774 // Try to recover by calling this function.
10775 return true;
10776 }
10777
10778 R.clear();
10779 }
10780
10781 return false;
10782}
10783
10784/// Attempt to recover from ill-formed use of a non-dependent operator in a
10785/// template, where the non-dependent operator was declared after the template
10786/// was defined.
10787///
10788/// Returns true if a viable candidate was found and a diagnostic was issued.
10789static bool
10790DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10791 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010792 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010793 DeclarationName OpName =
10794 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10795 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10796 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010797 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010798 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010799}
10800
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010801namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010802class BuildRecoveryCallExprRAII {
10803 Sema &SemaRef;
10804public:
10805 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10806 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10807 SemaRef.IsBuildingRecoveryCallExpr = true;
10808 }
10809
10810 ~BuildRecoveryCallExprRAII() {
10811 SemaRef.IsBuildingRecoveryCallExpr = false;
10812 }
10813};
10814
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010815}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010816
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010817static std::unique_ptr<CorrectionCandidateCallback>
10818MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10819 bool HasTemplateArgs, bool AllowTypoCorrection) {
10820 if (!AllowTypoCorrection)
10821 return llvm::make_unique<NoTypoCorrectionCCC>();
10822 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10823 HasTemplateArgs, ME);
10824}
10825
John McCalld681c392009-12-16 08:11:27 +000010826/// Attempts to recover from a call where no functions were found.
10827///
10828/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010829static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010830BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010831 UnresolvedLookupExpr *ULE,
10832 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010833 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010834 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010835 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010836 // Do not try to recover if it is already building a recovery call.
10837 // This stops infinite loops for template instantiations like
10838 //
10839 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10840 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10841 //
10842 if (SemaRef.IsBuildingRecoveryCallExpr)
10843 return ExprError();
10844 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010845
10846 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010847 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010848 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010849
John McCall57500772009-12-16 12:17:52 +000010850 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010851 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010852 if (ULE->hasExplicitTemplateArgs()) {
10853 ULE->copyTemplateArgumentsInto(TABuffer);
10854 ExplicitTemplateArgs = &TABuffer;
10855 }
10856
John McCalld681c392009-12-16 08:11:27 +000010857 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10858 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000010859 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000010860 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010861 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000010862 ExplicitTemplateArgs, Args,
10863 &DoDiagnoseEmptyLookup) &&
10864 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10865 S, SS, R,
10866 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10867 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10868 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010869 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010870
John McCall57500772009-12-16 12:17:52 +000010871 assert(!R.empty() && "lookup results empty despite recovery");
10872
10873 // Build an implicit member call if appropriate. Just drop the
10874 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010875 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010876 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010877 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10878 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010879 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010880 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010881 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010882 else
10883 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10884
10885 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010886 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010887
10888 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010889 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010890 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010891 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010892 MultiExprArg(Args.data(), Args.size()),
10893 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010894}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010895
Sam Panzer0f384432012-08-21 00:52:01 +000010896/// \brief Constructs and populates an OverloadedCandidateSet from
10897/// the given function.
10898/// \returns true when an the ExprResult output parameter has been set.
10899bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10900 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010901 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010902 SourceLocation RParenLoc,
10903 OverloadCandidateSet *CandidateSet,
10904 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010905#ifndef NDEBUG
10906 if (ULE->requiresADL()) {
10907 // To do ADL, we must have found an unqualified name.
10908 assert(!ULE->getQualifier() && "qualified name with ADL");
10909
10910 // We don't perform ADL for implicit declarations of builtins.
10911 // Verify that this was correctly set up.
10912 FunctionDecl *F;
10913 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10914 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10915 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010916 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010917
John McCall57500772009-12-16 12:17:52 +000010918 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010919 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010920 }
John McCall57500772009-12-16 12:17:52 +000010921#endif
10922
John McCall4124c492011-10-17 18:40:02 +000010923 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010924 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010925 *Result = ExprError();
10926 return true;
10927 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010928
John McCall57500772009-12-16 12:17:52 +000010929 // Add the functions denoted by the callee to the set of candidate
10930 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010931 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010932
Hans Wennborgb2747382015-06-12 21:23:23 +000010933 if (getLangOpts().MSVCCompat &&
10934 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000010935 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10936
10937 OverloadCandidateSet::iterator Best;
10938 if (CandidateSet->empty() ||
10939 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10940 OR_No_Viable_Function) {
10941 // In Microsoft mode, if we are inside a template class member function then
10942 // create a type dependent CallExpr. The goal is to postpone name lookup
10943 // to instantiation time to be able to search into type dependent base
10944 // classes.
10945 CallExpr *CE = new (Context) CallExpr(
10946 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010947 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000010948 CE->setValueDependent(true);
10949 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010950 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010951 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010952 }
Francois Pichetbcf64712011-09-07 00:14:57 +000010953 }
John McCalld681c392009-12-16 08:11:27 +000010954
Hans Wennborg64937c62015-06-11 21:21:57 +000010955 if (CandidateSet->empty())
10956 return false;
10957
John McCall4124c492011-10-17 18:40:02 +000010958 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010959 return false;
10960}
John McCall4124c492011-10-17 18:40:02 +000010961
Sam Panzer0f384432012-08-21 00:52:01 +000010962/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10963/// the completed call expression. If overload resolution fails, emits
10964/// diagnostics and returns ExprError()
10965static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10966 UnresolvedLookupExpr *ULE,
10967 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010968 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010969 SourceLocation RParenLoc,
10970 Expr *ExecConfig,
10971 OverloadCandidateSet *CandidateSet,
10972 OverloadCandidateSet::iterator *Best,
10973 OverloadingResult OverloadResult,
10974 bool AllowTypoCorrection) {
10975 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010976 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010977 RParenLoc, /*EmptyLookup=*/true,
10978 AllowTypoCorrection);
10979
10980 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010981 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010982 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010983 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010984 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10985 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010986 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010987 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10988 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010989 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010990
Richard Smith998a5912011-06-05 22:42:48 +000010991 case OR_No_Viable_Function: {
10992 // Try to recover by looking for viable functions which the user might
10993 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010994 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010995 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010996 /*EmptyLookup=*/false,
10997 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010998 if (!Recovery.isInvalid())
10999 return Recovery;
11000
Sam Panzer0f384432012-08-21 00:52:01 +000011001 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011002 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000011003 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011004 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011005 break;
Richard Smith998a5912011-06-05 22:42:48 +000011006 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011007
11008 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011009 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011010 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011011 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011012 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011013
Sam Panzer0f384432012-08-21 00:52:01 +000011014 case OR_Deleted: {
11015 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11016 << (*Best)->Function->isDeleted()
11017 << ULE->getName()
11018 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11019 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011020 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011021
Sam Panzer0f384432012-08-21 00:52:01 +000011022 // We emitted an error for the unvailable/deleted function call but keep
11023 // the call in the AST.
11024 FunctionDecl *FDecl = (*Best)->Function;
11025 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011026 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11027 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011028 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011029 }
11030
Douglas Gregorb412e172010-07-25 18:17:45 +000011031 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011032 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011033}
11034
Sam Panzer0f384432012-08-21 00:52:01 +000011035/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11036/// (which eventually refers to the declaration Func) and the call
11037/// arguments Args/NumArgs, attempt to resolve the function call down
11038/// to a specific function. If overload resolution succeeds, returns
11039/// the call expression produced by overload resolution.
11040/// Otherwise, emits diagnostics and returns ExprError.
11041ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11042 UnresolvedLookupExpr *ULE,
11043 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011044 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011045 SourceLocation RParenLoc,
11046 Expr *ExecConfig,
11047 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000011048 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11049 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011050 ExprResult result;
11051
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011052 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11053 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011054 return result;
11055
11056 OverloadCandidateSet::iterator Best;
11057 OverloadingResult OverloadResult =
11058 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11059
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011060 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011061 RParenLoc, ExecConfig, &CandidateSet,
11062 &Best, OverloadResult,
11063 AllowTypoCorrection);
11064}
11065
John McCall4c4c1df2010-01-26 03:27:55 +000011066static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011067 return Functions.size() > 1 ||
11068 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11069}
11070
Douglas Gregor084d8552009-03-13 23:49:33 +000011071/// \brief Create a unary operation that may resolve to an overloaded
11072/// operator.
11073///
11074/// \param OpLoc The location of the operator itself (e.g., '*').
11075///
11076/// \param OpcIn The UnaryOperator::Opcode that describes this
11077/// operator.
11078///
James Dennett18348b62012-06-22 08:52:37 +000011079/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011080/// considered by overload resolution. The caller needs to build this
11081/// set based on the context using, e.g.,
11082/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11083/// set should not contain any member functions; those will be added
11084/// by CreateOverloadedUnaryOp().
11085///
James Dennett91738ff2012-06-22 10:32:46 +000011086/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011087ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000011088Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
11089 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011090 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011091 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000011092
11093 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11094 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11095 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011096 // TODO: provide better source location info.
11097 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011098
John McCall4124c492011-10-17 18:40:02 +000011099 if (checkPlaceholderForOverload(*this, Input))
11100 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011101
Craig Topperc3ec1492014-05-26 06:22:03 +000011102 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011103 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011104
Douglas Gregor084d8552009-03-13 23:49:33 +000011105 // For post-increment and post-decrement, add the implicit '0' as
11106 // the second argument, so that we know this is a post-increment or
11107 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011108 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011109 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011110 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11111 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011112 NumArgs = 2;
11113 }
11114
Richard Smithe54c3072013-05-05 15:51:06 +000011115 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11116
Douglas Gregor084d8552009-03-13 23:49:33 +000011117 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011118 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011119 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11120 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011121
Craig Topperc3ec1492014-05-26 06:22:03 +000011122 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011123 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011124 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011125 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011126 /*ADL*/ true, IsOverloaded(Fns),
11127 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011128 return new (Context)
11129 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11130 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011131 }
11132
11133 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011134 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011135
11136 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011137 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011138
11139 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011140 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011141
John McCall4c4c1df2010-01-26 03:27:55 +000011142 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011143 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011144 /*ExplicitTemplateArgs*/nullptr,
11145 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011146
Douglas Gregor084d8552009-03-13 23:49:33 +000011147 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011148 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011149
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011150 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11151
Douglas Gregor084d8552009-03-13 23:49:33 +000011152 // Perform overload resolution.
11153 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011154 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011155 case OR_Success: {
11156 // We found a built-in operator or an overloaded operator.
11157 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011158
Douglas Gregor084d8552009-03-13 23:49:33 +000011159 if (FnDecl) {
11160 // We matched an overloaded operator. Build a call to that
11161 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011162
Douglas Gregor084d8552009-03-13 23:49:33 +000011163 // Convert the arguments.
11164 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011165 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011166
John Wiegley01296292011-04-08 18:41:53 +000011167 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011168 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011169 Best->FoundDecl, Method);
11170 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011171 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011172 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011173 } else {
11174 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011175 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011176 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011177 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011178 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011179 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011180 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011181 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011182 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011183 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011184 }
11185
Douglas Gregor084d8552009-03-13 23:49:33 +000011186 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011187 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011188 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011189 if (FnExpr.isInvalid())
11190 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011191
Richard Smithc1564702013-11-15 02:58:23 +000011192 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011193 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011194 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11195 ResultTy = ResultTy.getNonLValueExprType(Context);
11196
Eli Friedman030eee42009-11-18 03:58:17 +000011197 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011198 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011199 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011200 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011201
Alp Toker314cc812014-01-25 16:55:45 +000011202 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011203 return ExprError();
11204
John McCallb268a282010-08-23 23:25:46 +000011205 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011206 } else {
11207 // We matched a built-in operator. Convert the arguments, then
11208 // break out so that we will build the appropriate built-in
11209 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011210 ExprResult InputRes =
11211 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11212 Best->Conversions[0], AA_Passing);
11213 if (InputRes.isInvalid())
11214 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011215 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011216 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011217 }
John Wiegley01296292011-04-08 18:41:53 +000011218 }
11219
11220 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011221 // This is an erroneous use of an operator which can be overloaded by
11222 // a non-member function. Check for non-member operators which were
11223 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011224 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011225 // FIXME: Recover by calling the found function.
11226 return ExprError();
11227
John Wiegley01296292011-04-08 18:41:53 +000011228 // No viable function; fall through to handling this as a
11229 // built-in operator, which will produce an error message for us.
11230 break;
11231
11232 case OR_Ambiguous:
11233 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11234 << UnaryOperator::getOpcodeStr(Opc)
11235 << Input->getType()
11236 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011237 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011238 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11239 return ExprError();
11240
11241 case OR_Deleted:
11242 Diag(OpLoc, diag::err_ovl_deleted_oper)
11243 << Best->Function->isDeleted()
11244 << UnaryOperator::getOpcodeStr(Opc)
11245 << getDeletedOrUnavailableSuffix(Best->Function)
11246 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011247 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011248 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011249 return ExprError();
11250 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011251
11252 // Either we found no viable overloaded operator or we matched a
11253 // built-in operator. In either case, fall through to trying to
11254 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011255 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011256}
11257
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011258/// \brief Create a binary operation that may resolve to an overloaded
11259/// operator.
11260///
11261/// \param OpLoc The location of the operator itself (e.g., '+').
11262///
11263/// \param OpcIn The BinaryOperator::Opcode that describes this
11264/// operator.
11265///
James Dennett18348b62012-06-22 08:52:37 +000011266/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011267/// considered by overload resolution. The caller needs to build this
11268/// set based on the context using, e.g.,
11269/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11270/// set should not contain any member functions; those will be added
11271/// by CreateOverloadedBinOp().
11272///
11273/// \param LHS Left-hand argument.
11274/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011275ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011276Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011277 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011278 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011279 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011280 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011281 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011282
11283 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11284 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11285 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11286
11287 // If either side is type-dependent, create an appropriate dependent
11288 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011289 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011290 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011291 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011292 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011293 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011294 return new (Context) BinaryOperator(
11295 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11296 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011297
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011298 return new (Context) CompoundAssignOperator(
11299 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11300 Context.DependentTy, Context.DependentTy, OpLoc,
11301 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011302 }
John McCall4c4c1df2010-01-26 03:27:55 +000011303
11304 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011305 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011306 // TODO: provide better source location info in DNLoc component.
11307 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011308 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011309 = UnresolvedLookupExpr::Create(Context, NamingClass,
11310 NestedNameSpecifierLoc(), OpNameInfo,
11311 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011312 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011313 return new (Context)
11314 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11315 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011316 }
11317
John McCall4124c492011-10-17 18:40:02 +000011318 // Always do placeholder-like conversions on the RHS.
11319 if (checkPlaceholderForOverload(*this, Args[1]))
11320 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011321
John McCall526ab472011-10-25 17:37:35 +000011322 // Do placeholder-like conversion on the LHS; note that we should
11323 // not get here with a PseudoObject LHS.
11324 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011325 if (checkPlaceholderForOverload(*this, Args[0]))
11326 return ExprError();
11327
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011328 // If this is the assignment operator, we only perform overload resolution
11329 // if the left-hand side is a class or enumeration type. This is actually
11330 // a hack. The standard requires that we do overload resolution between the
11331 // various built-in candidates, but as DR507 points out, this can lead to
11332 // problems. So we do it this way, which pretty much follows what GCC does.
11333 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011334 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011335 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011336
John McCalle26a8722010-12-04 08:14:53 +000011337 // If this is the .* operator, which is not overloadable, just
11338 // create a built-in binary operator.
11339 if (Opc == BO_PtrMemD)
11340 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11341
Douglas Gregor084d8552009-03-13 23:49:33 +000011342 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011343 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011344
11345 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011346 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011347
11348 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011349 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011350
Richard Smith0daabd72014-09-23 20:31:39 +000011351 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11352 // performed for an assignment operator (nor for operator[] nor operator->,
11353 // which don't get here).
11354 if (Opc != BO_Assign)
11355 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11356 /*ExplicitTemplateArgs*/ nullptr,
11357 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011358
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011359 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011360 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011361
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011362 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11363
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011364 // Perform overload resolution.
11365 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011366 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011367 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011368 // We found a built-in operator or an overloaded operator.
11369 FunctionDecl *FnDecl = Best->Function;
11370
11371 if (FnDecl) {
11372 // We matched an overloaded operator. Build a call to that
11373 // operator.
11374
11375 // Convert the arguments.
11376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011377 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011378 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011379
Chandler Carruth8e543b32010-12-12 08:17:55 +000011380 ExprResult Arg1 =
11381 PerformCopyInitialization(
11382 InitializedEntity::InitializeParameter(Context,
11383 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011384 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011385 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011386 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011387
John Wiegley01296292011-04-08 18:41:53 +000011388 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011389 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011390 Best->FoundDecl, Method);
11391 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011392 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011393 Args[0] = Arg0.getAs<Expr>();
11394 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011395 } else {
11396 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011397 ExprResult Arg0 = PerformCopyInitialization(
11398 InitializedEntity::InitializeParameter(Context,
11399 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011400 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011401 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011402 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011403
Chandler Carruth8e543b32010-12-12 08:17:55 +000011404 ExprResult Arg1 =
11405 PerformCopyInitialization(
11406 InitializedEntity::InitializeParameter(Context,
11407 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011408 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011409 if (Arg1.isInvalid())
11410 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011411 Args[0] = LHS = Arg0.getAs<Expr>();
11412 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011413 }
11414
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011415 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011416 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011417 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011418 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011419 if (FnExpr.isInvalid())
11420 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011421
Richard Smithc1564702013-11-15 02:58:23 +000011422 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011423 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011424 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11425 ResultTy = ResultTy.getNonLValueExprType(Context);
11426
John McCallb268a282010-08-23 23:25:46 +000011427 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011428 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011429 Args, ResultTy, VK, OpLoc,
11430 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011431
Alp Toker314cc812014-01-25 16:55:45 +000011432 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011433 FnDecl))
11434 return ExprError();
11435
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011436 ArrayRef<const Expr *> ArgsArray(Args, 2);
11437 // Cut off the implicit 'this'.
11438 if (isa<CXXMethodDecl>(FnDecl))
11439 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011440
11441 // Check for a self move.
11442 if (Op == OO_Equal)
11443 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11444
Douglas Gregorb4866e82015-06-19 18:13:19 +000011445 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011446 TheCall->getSourceRange(), VariadicDoesNotApply);
11447
John McCallb268a282010-08-23 23:25:46 +000011448 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011449 } else {
11450 // We matched a built-in operator. Convert the arguments, then
11451 // break out so that we will build the appropriate built-in
11452 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011453 ExprResult ArgsRes0 =
11454 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11455 Best->Conversions[0], AA_Passing);
11456 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011457 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011458 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011459
John Wiegley01296292011-04-08 18:41:53 +000011460 ExprResult ArgsRes1 =
11461 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11462 Best->Conversions[1], AA_Passing);
11463 if (ArgsRes1.isInvalid())
11464 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011465 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011466 break;
11467 }
11468 }
11469
Douglas Gregor66950a32009-09-30 21:46:01 +000011470 case OR_No_Viable_Function: {
11471 // C++ [over.match.oper]p9:
11472 // If the operator is the operator , [...] and there are no
11473 // viable functions, then the operator is assumed to be the
11474 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011475 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011476 break;
11477
Chandler Carruth8e543b32010-12-12 08:17:55 +000011478 // For class as left operand for assignment or compound assigment
11479 // operator do not fall through to handling in built-in, but report that
11480 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011481 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011482 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011483 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011484 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11485 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011486 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011487 if (Args[0]->getType()->isIncompleteType()) {
11488 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11489 << Args[0]->getType()
11490 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11491 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011492 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011493 // This is an erroneous use of an operator which can be overloaded by
11494 // a non-member function. Check for non-member operators which were
11495 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011496 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011497 // FIXME: Recover by calling the found function.
11498 return ExprError();
11499
Douglas Gregor66950a32009-09-30 21:46:01 +000011500 // No viable function; try to create a built-in operation, which will
11501 // produce an error. Then, show the non-viable candidates.
11502 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011504 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011505 "C++ binary operator overloading is missing candidates!");
11506 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011507 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011508 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011509 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011510 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011511
11512 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011513 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011514 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011515 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011517 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011518 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011519 return ExprError();
11520
11521 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011522 if (isImplicitlyDeleted(Best->Function)) {
11523 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11524 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011525 << Context.getRecordType(Method->getParent())
11526 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011527
Richard Smithde1a4872012-12-28 12:23:24 +000011528 // The user probably meant to call this special member. Just
11529 // explain why it's deleted.
11530 NoteDeletedFunction(Method);
11531 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011532 } else {
11533 Diag(OpLoc, diag::err_ovl_deleted_oper)
11534 << Best->Function->isDeleted()
11535 << BinaryOperator::getOpcodeStr(Opc)
11536 << getDeletedOrUnavailableSuffix(Best->Function)
11537 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11538 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011539 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011540 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011541 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011542 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011543
Douglas Gregor66950a32009-09-30 21:46:01 +000011544 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011545 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011546}
11547
John McCalldadc5752010-08-24 06:29:42 +000011548ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011549Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11550 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011551 Expr *Base, Expr *Idx) {
11552 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011553 DeclarationName OpName =
11554 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11555
11556 // If either side is type-dependent, create an appropriate dependent
11557 // expression.
11558 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11559
Craig Topperc3ec1492014-05-26 06:22:03 +000011560 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011561 // CHECKME: no 'operator' keyword?
11562 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11563 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011564 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011565 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011566 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011567 /*ADL*/ true, /*Overloaded*/ false,
11568 UnresolvedSetIterator(),
11569 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011570 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011571
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011572 return new (Context)
11573 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11574 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011575 }
11576
John McCall4124c492011-10-17 18:40:02 +000011577 // Handle placeholders on both operands.
11578 if (checkPlaceholderForOverload(*this, Args[0]))
11579 return ExprError();
11580 if (checkPlaceholderForOverload(*this, Args[1]))
11581 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011582
Sebastian Redladba46e2009-10-29 20:17:01 +000011583 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011584 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011585
11586 // Subscript can only be overloaded as a member function.
11587
11588 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011589 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011590
11591 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011592 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011593
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011594 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11595
Sebastian Redladba46e2009-10-29 20:17:01 +000011596 // Perform overload resolution.
11597 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011598 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011599 case OR_Success: {
11600 // We found a built-in operator or an overloaded operator.
11601 FunctionDecl *FnDecl = Best->Function;
11602
11603 if (FnDecl) {
11604 // We matched an overloaded operator. Build a call to that
11605 // operator.
11606
John McCalla0296f72010-03-19 07:35:19 +000011607 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011608
Sebastian Redladba46e2009-10-29 20:17:01 +000011609 // Convert the arguments.
11610 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011611 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011612 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011613 Best->FoundDecl, Method);
11614 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011615 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011616 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011617
Anders Carlssona68e51e2010-01-29 18:37:50 +000011618 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011619 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011620 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011621 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011622 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011623 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011624 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011625 if (InputInit.isInvalid())
11626 return ExprError();
11627
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011628 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011629
Sebastian Redladba46e2009-10-29 20:17:01 +000011630 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011631 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11632 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011633 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011634 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011635 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011636 OpLocInfo.getLoc(),
11637 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011638 if (FnExpr.isInvalid())
11639 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011640
Richard Smithc1564702013-11-15 02:58:23 +000011641 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011642 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011643 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11644 ResultTy = ResultTy.getNonLValueExprType(Context);
11645
John McCallb268a282010-08-23 23:25:46 +000011646 CXXOperatorCallExpr *TheCall =
11647 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011648 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011649 ResultTy, VK, RLoc,
11650 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011651
Alp Toker314cc812014-01-25 16:55:45 +000011652 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011653 return ExprError();
11654
John McCallb268a282010-08-23 23:25:46 +000011655 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011656 } else {
11657 // We matched a built-in operator. Convert the arguments, then
11658 // break out so that we will build the appropriate built-in
11659 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011660 ExprResult ArgsRes0 =
11661 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11662 Best->Conversions[0], AA_Passing);
11663 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011664 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011665 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011666
11667 ExprResult ArgsRes1 =
11668 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11669 Best->Conversions[1], AA_Passing);
11670 if (ArgsRes1.isInvalid())
11671 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011672 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011673
11674 break;
11675 }
11676 }
11677
11678 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011679 if (CandidateSet.empty())
11680 Diag(LLoc, diag::err_ovl_no_oper)
11681 << Args[0]->getType() << /*subscript*/ 0
11682 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11683 else
11684 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11685 << Args[0]->getType()
11686 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011687 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011688 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011689 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011690 }
11691
11692 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011693 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011694 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011695 << Args[0]->getType() << Args[1]->getType()
11696 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011697 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011698 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011699 return ExprError();
11700
11701 case OR_Deleted:
11702 Diag(LLoc, diag::err_ovl_deleted_oper)
11703 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011704 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011705 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011706 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011707 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011708 return ExprError();
11709 }
11710
11711 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011712 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011713}
11714
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011715/// BuildCallToMemberFunction - Build a call to a member
11716/// function. MemExpr is the expression that refers to the member
11717/// function (and includes the object parameter), Args/NumArgs are the
11718/// arguments to the function call (not including the object
11719/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011720/// expression refers to a non-static member function or an overloaded
11721/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011722ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011723Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011724 SourceLocation LParenLoc,
11725 MultiExprArg Args,
11726 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011727 assert(MemExprE->getType() == Context.BoundMemberTy ||
11728 MemExprE->getType() == Context.OverloadTy);
11729
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011730 // Dig out the member expression. This holds both the object
11731 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011732 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011733
John McCall0009fcc2011-04-26 20:42:42 +000011734 // Determine whether this is a call to a pointer-to-member function.
11735 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11736 assert(op->getType() == Context.BoundMemberTy);
11737 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11738
11739 QualType fnType =
11740 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11741
11742 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11743 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011744 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011745
11746 // Check that the object type isn't more qualified than the
11747 // member function we're calling.
11748 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11749
11750 QualType objectType = op->getLHS()->getType();
11751 if (op->getOpcode() == BO_PtrMemI)
11752 objectType = objectType->castAs<PointerType>()->getPointeeType();
11753 Qualifiers objectQuals = objectType.getQualifiers();
11754
11755 Qualifiers difference = objectQuals - funcQuals;
11756 difference.removeObjCGCAttr();
11757 difference.removeAddressSpace();
11758 if (difference) {
11759 std::string qualsString = difference.getAsString();
11760 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11761 << fnType.getUnqualifiedType()
11762 << qualsString
11763 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11764 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011765
John McCall0009fcc2011-04-26 20:42:42 +000011766 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011767 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011768 resultType, valueKind, RParenLoc);
11769
Alp Toker314cc812014-01-25 16:55:45 +000011770 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011771 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011772 return ExprError();
11773
Craig Topperc3ec1492014-05-26 06:22:03 +000011774 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011775 return ExprError();
11776
Richard Trieu9be9c682013-06-22 02:30:38 +000011777 if (CheckOtherCall(call, proto))
11778 return ExprError();
11779
John McCall0009fcc2011-04-26 20:42:42 +000011780 return MaybeBindToTemporary(call);
11781 }
11782
David Majnemerced8bdf2015-02-25 17:36:15 +000011783 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11784 return new (Context)
11785 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11786
John McCall4124c492011-10-17 18:40:02 +000011787 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011788 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011789 return ExprError();
11790
John McCall10eae182009-11-30 22:42:35 +000011791 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011792 CXXMethodDecl *Method = nullptr;
11793 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11794 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011795 if (isa<MemberExpr>(NakedMemExpr)) {
11796 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011797 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011798 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011799 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011800 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011801 } else {
11802 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011803 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011804
John McCall6e9f8f62009-12-03 04:06:58 +000011805 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011806 Expr::Classification ObjectClassification
11807 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11808 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011809
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011810 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011811 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11812 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011813
John McCall2d74de92009-12-01 22:10:20 +000011814 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011815 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011816 if (UnresExpr->hasExplicitTemplateArgs()) {
11817 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11818 TemplateArgs = &TemplateArgsBuffer;
11819 }
11820
John McCall10eae182009-11-30 22:42:35 +000011821 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11822 E = UnresExpr->decls_end(); I != E; ++I) {
11823
John McCall6e9f8f62009-12-03 04:06:58 +000011824 NamedDecl *Func = *I;
11825 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11826 if (isa<UsingShadowDecl>(Func))
11827 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11828
Douglas Gregor02824322011-01-26 19:30:28 +000011829
Francois Pichet64225792011-01-18 05:04:39 +000011830 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011831 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011832 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011833 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011834 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011835 // If explicit template arguments were provided, we can't call a
11836 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011837 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011838 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011839
John McCalla0296f72010-03-19 07:35:19 +000011840 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011841 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011842 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011843 } else {
John McCall10eae182009-11-30 22:42:35 +000011844 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011845 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011846 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011847 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011848 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011849 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011850 }
Mike Stump11289f42009-09-09 15:08:12 +000011851
John McCall10eae182009-11-30 22:42:35 +000011852 DeclarationName DeclName = UnresExpr->getMemberName();
11853
John McCall4124c492011-10-17 18:40:02 +000011854 UnbridgedCasts.restore();
11855
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011856 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011857 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011858 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011859 case OR_Success:
11860 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011861 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011862 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011863 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11864 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011865 // If FoundDecl is different from Method (such as if one is a template
11866 // and the other a specialization), make sure DiagnoseUseOfDecl is
11867 // called on both.
11868 // FIXME: This would be more comprehensively addressed by modifying
11869 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11870 // being used.
11871 if (Method != FoundDecl.getDecl() &&
11872 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11873 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011874 break;
11875
11876 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011877 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011878 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011879 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011880 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011881 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011882 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011883
11884 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011885 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011886 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011887 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011888 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011889 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011890
11891 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011892 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011893 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011894 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011895 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011896 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011897 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011898 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011899 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011900 }
11901
John McCall16df1e52010-03-30 21:47:33 +000011902 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011903
John McCall2d74de92009-12-01 22:10:20 +000011904 // If overload resolution picked a static member, build a
11905 // non-member call based on that function.
11906 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011907 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11908 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011909 }
11910
John McCall10eae182009-11-30 22:42:35 +000011911 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011912 }
11913
Alp Toker314cc812014-01-25 16:55:45 +000011914 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011915 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11916 ResultType = ResultType.getNonLValueExprType(Context);
11917
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011918 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011919 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011920 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011921 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011922
Eli Bendersky291a57e2014-09-25 23:59:08 +000011923 // (CUDA B.1): Check for invalid calls between targets.
11924 if (getLangOpts().CUDA) {
11925 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11926 if (CheckCUDATarget(Caller, Method)) {
11927 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11928 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11929 << IdentifyCUDATarget(Caller);
11930 return ExprError();
11931 }
11932 }
11933 }
11934
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011935 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011936 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011937 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011938 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011939
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011940 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011941 // We only need to do this if there was actually an overload; otherwise
11942 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011943 if (!Method->isStatic()) {
11944 ExprResult ObjectArg =
11945 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11946 FoundDecl, Method);
11947 if (ObjectArg.isInvalid())
11948 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011949 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011950 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011951
11952 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011953 const FunctionProtoType *Proto =
11954 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011955 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011956 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011957 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011958
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011959 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011960
Richard Smith55ce3522012-06-25 20:30:08 +000011961 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011962 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011963
George Burgess IVaea6ade2015-09-25 17:53:16 +000011964 // In the case the method to call was not selected by the overloading
11965 // resolution process, we still need to handle the enable_if attribute. Do
11966 // that here, so it will not hide previous -- and more relevant -- errors
11967 if (isa<MemberExpr>(NakedMemExpr)) {
11968 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11969 Diag(MemExprE->getLocStart(),
11970 diag::err_ovl_no_viable_member_function_in_call)
11971 << Method << Method->getSourceRange();
11972 Diag(Method->getLocation(),
11973 diag::note_ovl_candidate_disabled_by_enable_if_attr)
11974 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11975 return ExprError();
11976 }
11977 }
11978
Anders Carlsson47061ee2011-05-06 14:25:31 +000011979 if ((isa<CXXConstructorDecl>(CurContext) ||
11980 isa<CXXDestructorDecl>(CurContext)) &&
11981 TheCall->getMethodDecl()->isPure()) {
11982 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11983
Davide Italianoccb37382015-07-14 23:36:10 +000011984 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11985 MemExpr->performsVirtualDispatch(getLangOpts())) {
11986 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000011987 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11988 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11989 << MD->getParent()->getDeclName();
11990
11991 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000011992 if (getLangOpts().AppleKext)
11993 Diag(MemExpr->getLocStart(),
11994 diag::note_pure_qualified_call_kext)
11995 << MD->getParent()->getDeclName()
11996 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011997 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011998 }
John McCallb268a282010-08-23 23:25:46 +000011999 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012000}
12001
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012002/// BuildCallToObjectOfClassType - Build a call to an object of class
12003/// type (C++ [over.call.object]), which can end up invoking an
12004/// overloaded function call operator (@c operator()) or performing a
12005/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012006ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012007Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012008 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012009 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012010 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012011 if (checkPlaceholderForOverload(*this, Obj))
12012 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012013 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012014
12015 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012016 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012017 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012018
Nico Weberb58e51c2014-11-19 05:21:39 +000012019 assert(Object.get()->getType()->isRecordType() &&
12020 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012021 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012022
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012023 // C++ [over.call.object]p1:
12024 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012025 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012026 // candidate functions includes at least the function call
12027 // operators of T. The function call operators of T are obtained by
12028 // ordinary lookup of the name operator() in the context of
12029 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012030 OverloadCandidateSet CandidateSet(LParenLoc,
12031 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012032 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012033
John Wiegley01296292011-04-08 18:41:53 +000012034 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012035 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012037
John McCall27b18f82009-11-17 02:14:36 +000012038 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12039 LookupQualifiedName(R, Record->getDecl());
12040 R.suppressDiagnostics();
12041
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012042 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012043 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012044 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012045 Object.get()->Classify(Context),
12046 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012047 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012049
Douglas Gregorab7897a2008-11-19 22:57:39 +000012050 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012051 // In addition, for each (non-explicit in C++0x) conversion function
12052 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012053 //
12054 // operator conversion-type-id () cv-qualifier;
12055 //
12056 // where cv-qualifier is the same cv-qualification as, or a
12057 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012058 // denotes the type "pointer to function of (P1,...,Pn) returning
12059 // R", or the type "reference to pointer to function of
12060 // (P1,...,Pn) returning R", or the type "reference to function
12061 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012062 // is also considered as a candidate function. Similarly,
12063 // surrogate call functions are added to the set of candidate
12064 // functions for each conversion function declared in an
12065 // accessible base class provided the function is not hidden
12066 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012067 const auto &Conversions =
12068 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12069 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012070 NamedDecl *D = *I;
12071 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12072 if (isa<UsingShadowDecl>(D))
12073 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012074
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012075 // Skip over templated conversion functions; they aren't
12076 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012077 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012078 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012079
John McCall6e9f8f62009-12-03 04:06:58 +000012080 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012081 if (!Conv->isExplicit()) {
12082 // Strip the reference type (if any) and then the pointer type (if
12083 // any) to get down to what might be a function type.
12084 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12085 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12086 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012087
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012088 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12089 {
12090 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012091 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012092 }
12093 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012094 }
Mike Stump11289f42009-09-09 15:08:12 +000012095
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012096 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12097
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012098 // Perform overload resolution.
12099 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012100 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012101 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012102 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012103 // Overload resolution succeeded; we'll build the appropriate call
12104 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012105 break;
12106
12107 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012108 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012109 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012110 << Object.get()->getType() << /*call*/ 1
12111 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012112 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012113 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012114 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012115 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012116 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012117 break;
12118
12119 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012120 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012121 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012122 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012123 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012124 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012125
12126 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012127 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012128 diag::err_ovl_deleted_object_call)
12129 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012130 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012131 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012132 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012133 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012134 break;
Mike Stump11289f42009-09-09 15:08:12 +000012135 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012136
Douglas Gregorb412e172010-07-25 18:17:45 +000012137 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012138 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012139
John McCall4124c492011-10-17 18:40:02 +000012140 UnbridgedCasts.restore();
12141
Craig Topperc3ec1492014-05-26 06:22:03 +000012142 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012143 // Since there is no function declaration, this is one of the
12144 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012145 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012146 = cast<CXXConversionDecl>(
12147 Best->Conversions[0].UserDefined.ConversionFunction);
12148
Craig Topperc3ec1492014-05-26 06:22:03 +000012149 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12150 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012151 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12152 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012153 assert(Conv == Best->FoundDecl.getDecl() &&
12154 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012155 // We selected one of the surrogate functions that converts the
12156 // object parameter to a function pointer. Perform the conversion
12157 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012158
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012159 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012160 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012161 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12162 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012163 if (Call.isInvalid())
12164 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012165 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012166 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12167 CK_UserDefinedConversion, Call.get(),
12168 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012169
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012170 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012171 }
12172
Craig Topperc3ec1492014-05-26 06:22:03 +000012173 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012174
Douglas Gregorab7897a2008-11-19 22:57:39 +000012175 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12176 // that calls this method, using Object for the implicit object
12177 // parameter and passing along the remaining arguments.
12178 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012179
12180 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012181 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012182 return ExprError();
12183
Chandler Carruth8e543b32010-12-12 08:17:55 +000012184 const FunctionProtoType *Proto =
12185 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012186
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012187 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012188
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012189 DeclarationNameInfo OpLocInfo(
12190 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12191 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012192 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012193 HadMultipleCandidates,
12194 OpLocInfo.getLoc(),
12195 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012196 if (NewFn.isInvalid())
12197 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012198
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012199 // Build the full argument list for the method call (the implicit object
12200 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012201 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012202 MethodArgs[0] = Object.get();
12203 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12204
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012205 // Once we've built TheCall, all of the expressions are properly
12206 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012207 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012208 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12209 ResultTy = ResultTy.getNonLValueExprType(Context);
12210
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012211 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012212 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012213 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12214 ResultTy, VK, RParenLoc, false);
12215 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012216
Alp Toker314cc812014-01-25 16:55:45 +000012217 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012218 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012219
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012220 // We may have default arguments. If so, we need to allocate more
12221 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012222 if (Args.size() < NumParams)
12223 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012224
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012225 bool IsError = false;
12226
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012227 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012228 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012229 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012230 Best->FoundDecl, Method);
12231 if (ObjRes.isInvalid())
12232 IsError = true;
12233 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012234 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012235 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012236
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012237 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012238 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012239 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012240 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012241 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012242
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012243 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012244
John McCalldadc5752010-08-24 06:29:42 +000012245 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012246 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012247 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012248 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012249 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012250
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012251 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012252 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012253 } else {
John McCalldadc5752010-08-24 06:29:42 +000012254 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012255 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12256 if (DefArg.isInvalid()) {
12257 IsError = true;
12258 break;
12259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012260
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012261 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012262 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012263
12264 TheCall->setArg(i + 1, Arg);
12265 }
12266
12267 // If this is a variadic call, handle args passed through "...".
12268 if (Proto->isVariadic()) {
12269 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012270 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012271 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12272 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012273 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012274 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012275 }
12276 }
12277
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012278 if (IsError) return true;
12279
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012280 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012281
Richard Smith55ce3522012-06-25 20:30:08 +000012282 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012283 return true;
12284
John McCalle172be52010-08-24 06:09:16 +000012285 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012286}
12287
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012288/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012289/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012290/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012291ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012292Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12293 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012294 assert(Base->getType()->isRecordType() &&
12295 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012296
John McCall4124c492011-10-17 18:40:02 +000012297 if (checkPlaceholderForOverload(*this, Base))
12298 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012299
John McCallbc077cf2010-02-08 23:07:23 +000012300 SourceLocation Loc = Base->getExprLoc();
12301
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012302 // C++ [over.ref]p1:
12303 //
12304 // [...] An expression x->m is interpreted as (x.operator->())->m
12305 // for a class object x of type T if T::operator->() exists and if
12306 // the operator is selected as the best match function by the
12307 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012308 DeclarationName OpName =
12309 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012310 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012311 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012312
John McCallbc077cf2010-02-08 23:07:23 +000012313 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012314 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012315 return ExprError();
12316
John McCall27b18f82009-11-17 02:14:36 +000012317 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12318 LookupQualifiedName(R, BaseRecord->getDecl());
12319 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012320
12321 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012322 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012323 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012324 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012325 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012326
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012327 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12328
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012329 // Perform overload resolution.
12330 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012331 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012332 case OR_Success:
12333 // Overload resolution succeeded; we'll build the call below.
12334 break;
12335
12336 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012337 if (CandidateSet.empty()) {
12338 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012339 if (NoArrowOperatorFound) {
12340 // Report this specific error to the caller instead of emitting a
12341 // diagnostic, as requested.
12342 *NoArrowOperatorFound = true;
12343 return ExprError();
12344 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012345 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12346 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012347 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012348 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012349 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012350 }
12351 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012352 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012353 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012354 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012355 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012356
12357 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012358 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12359 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012360 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012361 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012362
12363 case OR_Deleted:
12364 Diag(OpLoc, diag::err_ovl_deleted_oper)
12365 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012366 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012367 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012368 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012369 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012370 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012371 }
12372
Craig Topperc3ec1492014-05-26 06:22:03 +000012373 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012374
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012375 // Convert the object parameter.
12376 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012377 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012378 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012379 Best->FoundDecl, Method);
12380 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012381 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012382 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012383
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012384 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012385 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012386 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012387 if (FnExpr.isInvalid())
12388 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012389
Alp Toker314cc812014-01-25 16:55:45 +000012390 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012391 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12392 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012393 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012394 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012395 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012396
Alp Toker314cc812014-01-25 16:55:45 +000012397 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012398 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012399
12400 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012401}
12402
Richard Smithbcc22fc2012-03-09 08:00:36 +000012403/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12404/// a literal operator described by the provided lookup results.
12405ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12406 DeclarationNameInfo &SuffixInfo,
12407 ArrayRef<Expr*> Args,
12408 SourceLocation LitEndLoc,
12409 TemplateArgumentListInfo *TemplateArgs) {
12410 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012411
Richard Smith100b24a2014-04-17 01:52:14 +000012412 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12413 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012414 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12415 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012416
Richard Smithbcc22fc2012-03-09 08:00:36 +000012417 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12418
Richard Smithbcc22fc2012-03-09 08:00:36 +000012419 // Perform overload resolution. This will usually be trivial, but might need
12420 // to perform substitutions for a literal operator template.
12421 OverloadCandidateSet::iterator Best;
12422 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12423 case OR_Success:
12424 case OR_Deleted:
12425 break;
12426
12427 case OR_No_Viable_Function:
12428 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12429 << R.getLookupName();
12430 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12431 return ExprError();
12432
12433 case OR_Ambiguous:
12434 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12435 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12436 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012437 }
12438
Richard Smithbcc22fc2012-03-09 08:00:36 +000012439 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012440 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12441 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012442 SuffixInfo.getLoc(),
12443 SuffixInfo.getInfo());
12444 if (Fn.isInvalid())
12445 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012446
12447 // Check the argument types. This should almost always be a no-op, except
12448 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012449 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012450 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012451 ExprResult InputInit = PerformCopyInitialization(
12452 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12453 SourceLocation(), Args[ArgIdx]);
12454 if (InputInit.isInvalid())
12455 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012456 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012457 }
12458
Alp Toker314cc812014-01-25 16:55:45 +000012459 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012460 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12461 ResultTy = ResultTy.getNonLValueExprType(Context);
12462
Richard Smithc67fdd42012-03-07 08:35:16 +000012463 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012464 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012465 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012466 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12467
Alp Toker314cc812014-01-25 16:55:45 +000012468 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012469 return ExprError();
12470
Craig Topperc3ec1492014-05-26 06:22:03 +000012471 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012472 return ExprError();
12473
12474 return MaybeBindToTemporary(UDL);
12475}
12476
Sam Panzer0f384432012-08-21 00:52:01 +000012477/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12478/// given LookupResult is non-empty, it is assumed to describe a member which
12479/// will be invoked. Otherwise, the function will be found via argument
12480/// dependent lookup.
12481/// CallExpr is set to a valid expression and FRS_Success returned on success,
12482/// otherwise CallExpr is set to ExprError() and some non-success value
12483/// is returned.
12484Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012485Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12486 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012487 const DeclarationNameInfo &NameInfo,
12488 LookupResult &MemberLookup,
12489 OverloadCandidateSet *CandidateSet,
12490 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012491 Scope *S = nullptr;
12492
Sam Panzer0f384432012-08-21 00:52:01 +000012493 CandidateSet->clear();
12494 if (!MemberLookup.empty()) {
12495 ExprResult MemberRef =
12496 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12497 /*IsPtr=*/false, CXXScopeSpec(),
12498 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012499 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012500 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012501 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012502 if (MemberRef.isInvalid()) {
12503 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012504 return FRS_DiagnosticIssued;
12505 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012506 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012507 if (CallExpr->isInvalid()) {
12508 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012509 return FRS_DiagnosticIssued;
12510 }
12511 } else {
12512 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012513 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012514 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012515 NestedNameSpecifierLoc(), NameInfo,
12516 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012517 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012518
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012519 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012520 CandidateSet, CallExpr);
12521 if (CandidateSet->empty() || CandidateSetError) {
12522 *CallExpr = ExprError();
12523 return FRS_NoViableFunction;
12524 }
12525 OverloadCandidateSet::iterator Best;
12526 OverloadingResult OverloadResult =
12527 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12528
12529 if (OverloadResult == OR_No_Viable_Function) {
12530 *CallExpr = ExprError();
12531 return FRS_NoViableFunction;
12532 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012533 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012534 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012535 OverloadResult,
12536 /*AllowTypoCorrection=*/false);
12537 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12538 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012539 return FRS_DiagnosticIssued;
12540 }
12541 }
12542 return FRS_Success;
12543}
12544
12545
Douglas Gregorcd695e52008-11-10 20:40:00 +000012546/// FixOverloadedFunctionReference - E is an expression that refers to
12547/// a C++ overloaded function (possibly with some parentheses and
12548/// perhaps a '&' around it). We have resolved the overloaded function
12549/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012550/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012551Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012552 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012553 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012554 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12555 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012556 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012557 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012558
Douglas Gregor51c538b2009-11-20 19:42:02 +000012559 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012560 }
12561
Douglas Gregor51c538b2009-11-20 19:42:02 +000012562 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012563 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12564 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012565 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012566 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012567 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012568 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012569 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012570 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012571
12572 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012573 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012574 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012575 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012576 }
12577
Douglas Gregor51c538b2009-11-20 19:42:02 +000012578 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012579 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012580 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12582 if (Method->isStatic()) {
12583 // Do nothing: static member functions aren't any different
12584 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012585 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012586 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012587 // UnresolvedLookupExpr holding an overloaded member function
12588 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012589 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12590 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012591 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012592 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012593
John McCalld14a8642009-11-21 08:51:07 +000012594 assert(isa<DeclRefExpr>(SubExpr)
12595 && "fixed to something other than a decl ref");
12596 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12597 && "fixed to a member ref with no nested name qualifier");
12598
12599 // We have taken the address of a pointer to member
12600 // function. Perform the computation here so that we get the
12601 // appropriate pointer to member type.
12602 QualType ClassType
12603 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12604 QualType MemPtrType
12605 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12606
John McCall7decc9e2010-11-18 06:31:45 +000012607 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12608 VK_RValue, OK_Ordinary,
12609 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012610 }
12611 }
John McCall16df1e52010-03-30 21:47:33 +000012612 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12613 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012614 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012615 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012616
John McCalle3027922010-08-25 11:45:40 +000012617 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012618 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012619 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012620 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012621 }
John McCalld14a8642009-11-21 08:51:07 +000012622
12623 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012624 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012625 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012626 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012627 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12628 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012629 }
12630
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012631 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12632 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012633 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012634 Fn,
John McCall113bee02012-03-10 09:33:50 +000012635 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012636 ULE->getNameLoc(),
12637 Fn->getType(),
12638 VK_LValue,
12639 Found.getDecl(),
12640 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012641 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012642 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12643 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012644 }
12645
John McCall10eae182009-11-30 22:42:35 +000012646 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012647 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012648 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012649 if (MemExpr->hasExplicitTemplateArgs()) {
12650 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12651 TemplateArgs = &TemplateArgsBuffer;
12652 }
John McCall6b51f282009-11-23 01:53:49 +000012653
John McCall2d74de92009-12-01 22:10:20 +000012654 Expr *Base;
12655
John McCall7decc9e2010-11-18 06:31:45 +000012656 // If we're filling in a static method where we used to have an
12657 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012658 if (MemExpr->isImplicitAccess()) {
12659 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012660 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12661 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012662 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012663 Fn,
John McCall113bee02012-03-10 09:33:50 +000012664 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012665 MemExpr->getMemberLoc(),
12666 Fn->getType(),
12667 VK_LValue,
12668 Found.getDecl(),
12669 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012670 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012671 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12672 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012673 } else {
12674 SourceLocation Loc = MemExpr->getMemberLoc();
12675 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012676 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012677 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012678 Base = new (Context) CXXThisExpr(Loc,
12679 MemExpr->getBaseType(),
12680 /*isImplicit=*/true);
12681 }
John McCall2d74de92009-12-01 22:10:20 +000012682 } else
John McCallc3007a22010-10-26 07:05:15 +000012683 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012684
John McCall4adb38c2011-04-27 00:36:17 +000012685 ExprValueKind valueKind;
12686 QualType type;
12687 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12688 valueKind = VK_LValue;
12689 type = Fn->getType();
12690 } else {
12691 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012692 type = Context.BoundMemberTy;
12693 }
12694
12695 MemberExpr *ME = MemberExpr::Create(
12696 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12697 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12698 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12699 OK_Ordinary);
12700 ME->setHadMultipleCandidates(true);
12701 MarkMemberReferenced(ME);
12702 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012704
John McCallc3007a22010-10-26 07:05:15 +000012705 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012706}
12707
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012708ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012709 DeclAccessPair Found,
12710 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012711 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012712}