blob: 2129729dab9f3119164f63c9446687ca501ec5c4 [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
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000063 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000065 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000066 VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000069
70 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000071 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000073}
74
John McCall5c32be02010-08-24 20:38:10 +000075static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000077 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000078 bool CStyle,
79 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000080
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000081static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82 QualType &ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000086static OverloadingResult
87IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000090 bool AllowExplicit,
91 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000092
93
94static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000095CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000096 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000105CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000119 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 ICR_Promotion,
121 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000122 ICR_Promotion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000130 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000131 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000132 ICR_Conversion,
133 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000134 ICR_Complex_Real_Conversion,
135 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000136 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000141 ICR_C_Conversion,
142 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143 };
144 return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000149static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "No conversion",
152 "Lvalue-to-rvalue",
153 "Array-to-pointer",
154 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000155 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Qualification",
157 "Integral promotion",
158 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000159 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Integral conversion",
161 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000162 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000166 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000167 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000168 "Derived-to-base conversion",
169 "Vector conversion",
170 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000171 "Complex-real conversion",
172 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000173 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000176 "C specific type conversion",
177 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000178 };
179 return Name[Kind];
180}
181
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000188 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000189 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000190 ReferenceBinding = false;
191 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000196 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000197 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000198}
199
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200/// getRank - Retrieve the rank of this standard conversion sequence
201/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202/// implicit conversions.
203ImplicitConversionRank StandardConversionSequence::getRank() const {
204 ImplicitConversionRank Rank = ICR_Exact_Match;
205 if (GetConversionRank(First) > Rank)
206 Rank = GetConversionRank(First);
207 if (GetConversionRank(Second) > Rank)
208 Rank = GetConversionRank(Second);
209 if (GetConversionRank(Third) > Rank)
210 Rank = GetConversionRank(Third);
211 return Rank;
212}
213
214/// isPointerConversionToBool - Determines whether this conversion is
215/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000216/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000218bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 // Note that FromType has not necessarily been transformed by the
220 // array-to-pointer or function-to-pointer implicit conversions, so
221 // check for their presence as well as checking whether FromType is
222 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000224 (getFromType()->isPointerType() ||
225 getFromType()->isObjCObjectPointerType() ||
226 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000227 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229 return true;
230
231 return false;
232}
233
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234/// isPointerConversionToVoidPointer - Determines whether this
235/// conversion is a conversion of a pointer to a void pointer. This is
236/// used as part of the ranking of standard conversion sequences (C++
237/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000238bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000240isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000241 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000242 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243
244 // Note that FromType has not necessarily been transformed by the
245 // array-to-pointer implicit conversion, so check for its presence
246 // and redo the conversion to get a pointer.
247 if (First == ICK_Array_To_Pointer)
248 FromType = Context.getArrayDecayedType(FromType);
249
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000252 return ToPtrType->getPointeeType()->isVoidType();
253
254 return false;
255}
256
Richard Smith66e05fe2012-01-18 05:21:49 +0000257/// Skip any implicit casts which could be either part of a narrowing conversion
258/// or after one in an implicit conversion.
259static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261 switch (ICE->getCastKind()) {
262 case CK_NoOp:
263 case CK_IntegralCast:
264 case CK_IntegralToBoolean:
265 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000266 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000267 case CK_FloatingToIntegral:
268 case CK_FloatingToBoolean:
269 case CK_FloatingCast:
270 Converted = ICE->getSubExpr();
271 continue;
272
273 default:
274 return Converted;
275 }
276 }
277
278 return Converted;
279}
280
281/// Check if this standard conversion sequence represents a narrowing
282/// conversion, according to C++11 [dcl.init.list]p7.
283///
284/// \param Ctx The AST context.
285/// \param Converted The result of applying this standard conversion sequence.
286/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
287/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000288/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
289/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000290NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000291StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000293 APValue &ConstantValue,
294 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000301
302 // A conversion to an enumeration type is narrowing if the conversion to
303 // the underlying type is narrowing. This only arises for expressions of
304 // the form 'Enum{init}'.
305 if (auto *ET = ToType->getAs<EnumType>())
306 ToType = ET->getDecl()->getIntegerType();
307
Richard Smith66e05fe2012-01-18 05:21:49 +0000308 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000309 // 'bool' is an integral type; dispatch to the right place to handle it.
310 case ICK_Boolean_Conversion:
311 if (FromType->isRealFloatingType())
312 goto FloatingIntegralConversion;
313 if (FromType->isIntegralOrUnscopedEnumerationType())
314 goto IntegralConversion;
315 // Boolean conversions can be from pointers and pointers to members
316 // [conv.bool], and those aren't considered narrowing conversions.
317 return NK_Not_Narrowing;
318
Richard Smith66e05fe2012-01-18 05:21:49 +0000319 // -- from a floating-point type to an integer type, or
320 //
321 // -- from an integer type or unscoped enumeration type to a floating-point
322 // type, except where the source is a constant expression and the actual
323 // value after conversion will fit into the target type and will produce
324 // the original value when converted back to the original type, or
325 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000326 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000379 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000391 case ICK_Integral_Conversion:
392 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000393 assert(FromType->isIntegralOrUnscopedEnumerationType());
394 assert(ToType->isIntegralOrUnscopedEnumerationType());
395 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
396 const unsigned FromWidth = Ctx.getIntWidth(FromType);
397 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
398 const unsigned ToWidth = Ctx.getIntWidth(ToType);
399
400 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000401 (FromWidth == ToWidth && FromSigned != ToSigned) ||
402 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 // Not all values of FromType can be represented in ToType.
404 llvm::APSInt InitializerValue;
405 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000406 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
407 // Such conversions on variables are always narrowing.
408 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000409 }
410 bool Narrowing = false;
411 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000412 // Negative -> unsigned is narrowing. Otherwise, more bits is never
413 // narrowing.
414 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000415 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000416 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000417 // Add a bit to the InitializerValue so we don't have to worry about
418 // signed vs. unsigned comparisons.
419 InitializerValue = InitializerValue.extend(
420 InitializerValue.getBitWidth() + 1);
421 // Convert the initializer to and from the target width and signed-ness.
422 llvm::APSInt ConvertedValue = InitializerValue;
423 ConvertedValue = ConvertedValue.trunc(ToWidth);
424 ConvertedValue.setIsSigned(ToSigned);
425 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
426 ConvertedValue.setIsSigned(InitializerValue.isSigned());
427 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000428 if (ConvertedValue != InitializerValue)
429 Narrowing = true;
430 }
431 if (Narrowing) {
432 ConstantType = Initializer->getType();
433 ConstantValue = APValue(InitializerValue);
434 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000435 }
436 }
437 return NK_Not_Narrowing;
438 }
439
440 default:
441 // Other kinds of conversions are not narrowings.
442 return NK_Not_Narrowing;
443 }
444}
445
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000446/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000448LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000449 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 bool PrintedSomething = false;
451 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000453 PrintedSomething = true;
454 }
455
456 if (Second != ICK_Identity) {
457 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000459 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000461
462 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000464 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000466 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Third != ICK_Identity) {
473 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 PrintedSomething = true;
478 }
479
480 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
483}
484
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000487void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000493 if (ConversionFunction)
494 OS << '\'' << *ConversionFunction << '\'';
495 else
496 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000499 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 }
501}
502
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000507 if (isStdInitializerListElement())
508 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 switch (ConversionKind) {
510 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 break;
514 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000516 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 break;
518 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
John McCall0d1da222010-01-12 00:44:57 +0000521 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000523 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000525 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526 break;
527 }
528
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530}
531
John McCall0d1da222010-01-12 00:44:57 +0000532void AmbiguousConversionSequence::construct() {
533 new (&conversions()) ConversionSet();
534}
535
536void AmbiguousConversionSequence::destruct() {
537 conversions().~ConversionSet();
538}
539
540void
541AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
542 FromTypePtr = O.FromTypePtr;
543 ToTypePtr = O.ToTypePtr;
544 new (&conversions()) ConversionSet(O.conversions());
545}
546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000548 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000549 // template argument information.
550 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 TemplateArgument FirstArg;
552 TemplateArgument SecondArg;
553 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000554 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000555 // template parameter and template argument information.
556 struct DFIParamWithArguments : DFIArguments {
557 TemplateParameter Param;
558 };
Richard Smith9b534542015-12-31 02:02:54 +0000559 // Structure used by DeductionFailureInfo to store template argument
560 // information and the index of the problematic call argument.
561 struct DFIDeducedMismatchArgs : DFIArguments {
562 TemplateArgumentList *TemplateArgs;
563 unsigned CallArgIndex;
564 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000565}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567/// \brief Convert from Sema's representation of template deduction information
568/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000569DeductionFailureInfo
570clang::MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 switch (TDK) {
577 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000578 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000580 case Sema::TDK_TooManyArguments:
581 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000582 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000583 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000584 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000588 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 Result.Data = Info.Param.getOpaqueValue();
590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Richard Smith9b534542015-12-31 02:02:54 +0000592 case Sema::TDK_DeducedMismatch: {
593 // FIXME: Should allocate from normal heap so that we can free this later.
594 auto *Saved = new (Context) DFIDeducedMismatchArgs;
595 Saved->FirstArg = Info.FirstArg;
596 Saved->SecondArg = Info.SecondArg;
597 Saved->TemplateArgs = Info.take();
598 Saved->CallArgIndex = Info.CallArgIndex;
599 Result.Data = Saved;
600 break;
601 }
602
Richard Smith44ecdbd2013-01-31 05:19:49 +0000603 case Sema::TDK_NonDeducedMismatch: {
604 // FIXME: Should allocate from normal heap so that we can free this later.
605 DFIArguments *Saved = new (Context) DFIArguments;
606 Saved->FirstArg = Info.FirstArg;
607 Saved->SecondArg = Info.SecondArg;
608 Result.Data = Saved;
609 break;
610 }
611
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000612 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000613 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000614 // FIXME: Should allocate from normal heap so that we can free this later.
615 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 Saved->Param = Info.Param;
617 Saved->FirstArg = Info.FirstArg;
618 Saved->SecondArg = Info.SecondArg;
619 Result.Data = Saved;
620 break;
621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000624 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000625 if (Info.hasSFINAEDiagnostic()) {
626 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
627 SourceLocation(), PartialDiagnostic::NullDiagnostic());
628 Info.takeSFINAEDiagnostic(*Diag);
629 Result.HasDiagnostic = true;
630 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000634 Result.Data = Info.Expression;
635 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 return Result;
639}
John McCall0d1da222010-01-12 00:44:57 +0000640
Larisse Voufo98b20f12013-07-19 23:00:19 +0000641void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
643 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000644 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 case Sema::TDK_InstantiationDepth:
646 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000647 case Sema::TDK_TooManyArguments:
648 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000649 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000650 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000651 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000656 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000657 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000658 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000659 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000661
662 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000663 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000664 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000665 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
666 Diag->~PartialDiagnosticAt();
667 HasDiagnostic = false;
668 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor461761d2010-05-08 18:20:53 +0000671 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000672 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 break;
674 }
675}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676
Larisse Voufo98b20f12013-07-19 23:00:19 +0000677PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000678 if (HasDiagnostic)
679 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000681}
682
Larisse Voufo98b20f12013-07-19 23:00:19 +0000683TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
685 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000686 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000688 case Sema::TDK_TooManyArguments:
689 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000690 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000691 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000692 case Sema::TDK_NonDeducedMismatch:
693 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000694 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000698 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700
701 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000702 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000706 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 break;
708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 return TemplateParameter();
711}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000712
Larisse Voufo98b20f12013-07-19 23:00:19 +0000713TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000715 case Sema::TDK_Success:
716 case Sema::TDK_Invalid:
717 case Sema::TDK_InstantiationDepth:
718 case Sema::TDK_TooManyArguments:
719 case Sema::TDK_TooFewArguments:
720 case Sema::TDK_Incomplete:
721 case Sema::TDK_InvalidExplicitArguments:
722 case Sema::TDK_Inconsistent:
723 case Sema::TDK_Underqualified:
724 case Sema::TDK_NonDeducedMismatch:
725 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000726 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000727 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000728
Richard Smith9b534542015-12-31 02:02:54 +0000729 case Sema::TDK_DeducedMismatch:
730 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
731
Richard Smith44ecdbd2013-01-31 05:19:49 +0000732 case Sema::TDK_SubstitutionFailure:
733 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000738 }
739
Craig Topperc3ec1492014-05-26 06:22:03 +0000740 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000741}
742
Larisse Voufo98b20f12013-07-19 23:00:19 +0000743const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000746 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000749 case Sema::TDK_TooManyArguments:
750 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000751 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000752 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000753 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000754 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000758 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000759 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000760 case Sema::TDK_NonDeducedMismatch:
761 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762
Douglas Gregor461761d2010-05-08 18:20:53 +0000763 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000764 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 break;
766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000770
Larisse Voufo98b20f12013-07-19 23:00:19 +0000771const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000774 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000779 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000780 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000781 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000782 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000786 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000787 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000788 case Sema::TDK_NonDeducedMismatch:
789 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790
Douglas Gregor461761d2010-05-08 18:20:53 +0000791 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000792 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000793 break;
794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000797}
798
Larisse Voufo98b20f12013-07-19 23:00:19 +0000799Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000800 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
801 Sema::TDK_FailedOverloadResolution)
802 return static_cast<Expr*>(Data);
803
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000805}
806
Richard Smith9b534542015-12-31 02:02:54 +0000807llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
808 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
809 Sema::TDK_DeducedMismatch)
810 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
811
812 return llvm::None;
813}
814
Benjamin Kramer97e59492012-10-09 15:52:25 +0000815void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000816 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000817 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
818 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000819 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
820 i->DeductionFailure.Destroy();
821 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000822}
823
824void OverloadCandidateSet::clear() {
825 destroyCandidates();
George Burgess IVbc7f44c2016-12-02 21:00:12 +0000826 ConversionSequenceAllocator.Reset();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000827 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000828 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000829 Functions.clear();
830}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
John McCall4124c492011-10-17 18:40:02 +0000832namespace {
833 class UnbridgedCastsSet {
834 struct Entry {
835 Expr **Addr;
836 Expr *Saved;
837 };
838 SmallVector<Entry, 2> Entries;
839
840 public:
841 void save(Sema &S, Expr *&E) {
842 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
843 Entry entry = { &E, E };
844 Entries.push_back(entry);
845 E = S.stripARCUnbridgedCast(E);
846 }
847
848 void restore() {
849 for (SmallVectorImpl<Entry>::iterator
850 i = Entries.begin(), e = Entries.end(); i != e; ++i)
851 *i->Addr = i->Saved;
852 }
853 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000854}
John McCall4124c492011-10-17 18:40:02 +0000855
856/// checkPlaceholderForOverload - Do any interesting placeholder-like
857/// preprocessing on the given expression.
858///
859/// \param unbridgedCasts a collection to which to add unbridged casts;
860/// without this, they will be immediately diagnosed as errors
861///
862/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000863static bool
864checkPlaceholderForOverload(Sema &S, Expr *&E,
865 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000866 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
867 // We can't handle overloaded expressions here because overload
868 // resolution might reasonably tweak them.
869 if (placeholder->getKind() == BuiltinType::Overload) return false;
870
871 // If the context potentially accepts unbridged ARC casts, strip
872 // the unbridged cast and add it to the collection for later restoration.
873 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
874 unbridgedCasts) {
875 unbridgedCasts->save(S, E);
876 return false;
877 }
878
879 // Go ahead and check everything else.
880 ExprResult result = S.CheckPlaceholderExpr(E);
881 if (result.isInvalid())
882 return true;
883
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000884 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000885 return false;
886 }
887
888 // Nothing to do.
889 return false;
890}
891
892/// checkArgPlaceholdersForOverload - Check a set of call operands for
893/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000894static bool checkArgPlaceholdersForOverload(Sema &S,
895 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000896 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000897 for (unsigned i = 0, e = Args.size(); i != e; ++i)
898 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000899 return true;
900
901 return false;
902}
903
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000904// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000905// overload of the declarations in Old. This routine returns false if
906// New and Old cannot be overloaded, e.g., if New has the same
907// signature as some function in Old (C++ 1.3.10) or if the Old
908// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000909// it does return false, MatchedDecl will point to the decl that New
910// cannot be overloaded with. This decl may be a UsingShadowDecl on
911// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912//
913// Example: Given the following input:
914//
915// void f(int, float); // #1
916// void f(int, int); // #2
917// int f(int, int); // #3
918//
919// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000920// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000921//
John McCall3d988d92009-12-02 08:47:38 +0000922// When we process #2, Old contains only the FunctionDecl for #1. By
923// comparing the parameter types, we see that #1 and #2 are overloaded
924// (since they have different signatures), so this routine returns
925// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000926//
John McCall3d988d92009-12-02 08:47:38 +0000927// When we process #3, Old is an overload set containing #1 and #2. We
928// compare the signatures of #3 to #1 (they're overloaded, so we do
929// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
930// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000931// signature), IsOverload returns false and MatchedDecl will be set to
932// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000933//
934// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
935// into a class by a using declaration. The rules for whether to hide
936// shadow declarations ignore some properties which otherwise figure
937// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000938Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000939Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
940 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000941 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000942 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000943 NamedDecl *OldD = *I;
944
945 bool OldIsUsingDecl = false;
946 if (isa<UsingShadowDecl>(OldD)) {
947 OldIsUsingDecl = true;
948
949 // We can always introduce two using declarations into the same
950 // context, even if they have identical signatures.
951 if (NewIsUsingDecl) continue;
952
953 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
954 }
955
Richard Smithf091e122015-09-15 01:28:55 +0000956 // A using-declaration does not conflict with another declaration
957 // if one of them is hidden.
958 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
959 continue;
960
John McCalle9cccd82010-06-16 08:42:20 +0000961 // If either declaration was introduced by a using declaration,
962 // we'll need to use slightly different rules for matching.
963 // Essentially, these rules are the normal rules, except that
964 // function templates hide function templates with different
965 // return types or template parameter lists.
966 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000967 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
968 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000969
Alp Tokera2794f92014-01-22 07:29:52 +0000970 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000971 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
972 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
973 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
974 continue;
975 }
976
Alp Tokera2794f92014-01-22 07:29:52 +0000977 if (!isa<FunctionTemplateDecl>(OldD) &&
978 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000979 continue;
980
John McCalldaa3d6b2009-12-09 03:35:25 +0000981 Match = *I;
982 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000983 }
Richard Smith22a250c2016-12-19 04:08:53 +0000984 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000985 // We can overload with these, which can show up when doing
986 // redeclaration checks for UsingDecls.
987 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000988 } else if (isa<TagDecl>(OldD)) {
989 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +0000990 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000991 // Optimistically assume that an unresolved using decl will
992 // overload; if it doesn't, we'll have to diagnose during
993 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +0000994 //
995 // Exception: if the scope is dependent and this is not a class
996 // member, the using declaration can only introduce an enumerator.
997 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
998 Match = *I;
999 return Ovl_NonFunction;
1000 }
John McCall84d87672009-12-10 09:41:52 +00001001 } else {
John McCall1f82f242009-11-18 22:49:29 +00001002 // (C++ 13p1):
1003 // Only function declarations can be overloaded; object and type
1004 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001005 Match = *I;
1006 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001007 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 }
John McCall1f82f242009-11-18 22:49:29 +00001009
John McCalldaa3d6b2009-12-09 03:35:25 +00001010 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001011}
1012
Richard Smithac974a32013-06-30 09:48:50 +00001013bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001014 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001015 // C++ [basic.start.main]p2: This function shall not be overloaded.
1016 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001017 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001018
David Majnemerc729b0b2013-09-16 22:44:20 +00001019 // MSVCRT user defined entry points cannot be overloaded.
1020 if (New->isMSVCRTEntryPoint())
1021 return false;
1022
John McCall1f82f242009-11-18 22:49:29 +00001023 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1024 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1025
1026 // C++ [temp.fct]p2:
1027 // A function template can be overloaded with other function templates
1028 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001029 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001030 return true;
1031
1032 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001033 QualType OldQType = Context.getCanonicalType(Old->getType());
1034 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001035
1036 // Compare the signatures (C++ 1.3.10) of the two functions to
1037 // determine whether they are overloads. If we find any mismatch
1038 // in the signature, they are overloads.
1039
1040 // If either of these functions is a K&R-style function (no
1041 // prototype), then we consider them to have matching signatures.
1042 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1043 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1044 return false;
1045
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001046 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1047 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001048
1049 // The signature of a function includes the types of its
1050 // parameters (C++ 1.3.10), which includes the presence or absence
1051 // of the ellipsis; see C++ DR 357).
1052 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001053 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001054 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001055 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001056 return true;
1057
1058 // C++ [temp.over.link]p4:
1059 // The signature of a function template consists of its function
1060 // signature, its return type and its template parameter list. The names
1061 // of the template parameters are significant only for establishing the
1062 // relationship between the template parameters and the rest of the
1063 // signature.
1064 //
1065 // We check the return type and template parameter lists for function
1066 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001067 //
1068 // However, we don't consider either of these when deciding whether
1069 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001070 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001071 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1072 OldTemplate->getTemplateParameters(),
1073 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001074 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001075 return true;
1076
1077 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001078 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001079 //
1080 // As part of this, also check whether one of the member functions
1081 // is static, in which case they are not overloads (C++
1082 // 13.1p2). While not part of the definition of the signature,
1083 // this check is important to determine whether these functions
1084 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001085 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1086 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001087 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001088 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1089 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001090 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001091 (OldMethod->getRefQualifier() == RQ_None ||
1092 NewMethod->getRefQualifier() == RQ_None)) {
1093 // C++0x [over.load]p2:
1094 // - Member function declarations with the same name and the same
1095 // parameter-type-list as well as member function template
1096 // declarations with the same name, the same parameter-type-list, and
1097 // the same template parameter lists cannot be overloaded if any of
1098 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001099 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001100 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001101 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001102 }
1103 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Richard Smith574f4f62013-01-14 05:37:29 +00001106 // We may not have applied the implicit const for a constexpr member
1107 // function yet (because we haven't yet resolved whether this is a static
1108 // or non-static member function). Add it now, on the assumption that this
1109 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001110 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001111 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001112 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001113 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001114 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001115
1116 // We do not allow overloading based off of '__restrict'.
1117 OldQuals &= ~Qualifiers::Restrict;
1118 NewQuals &= ~Qualifiers::Restrict;
1119 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001120 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001123 // Though pass_object_size is placed on parameters and takes an argument, we
1124 // consider it to be a function-level modifier for the sake of function
1125 // identity. Either the function has one or more parameters with
1126 // pass_object_size or it doesn't.
1127 if (functionHasPassObjectSizeParams(New) !=
1128 functionHasPassObjectSizeParams(Old))
1129 return true;
1130
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001131 // enable_if attributes are an order-sensitive part of the signature.
1132 for (specific_attr_iterator<EnableIfAttr>
1133 NewI = New->specific_attr_begin<EnableIfAttr>(),
1134 NewE = New->specific_attr_end<EnableIfAttr>(),
1135 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1136 OldE = Old->specific_attr_end<EnableIfAttr>();
1137 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1138 if (NewI == NewE || OldI == OldE)
1139 return true;
1140 llvm::FoldingSetNodeID NewID, OldID;
1141 NewI->getCond()->Profile(NewID, Context, true);
1142 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001143 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001144 return true;
1145 }
1146
Justin Lebarba122ab2016-03-30 23:30:21 +00001147 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001148 // Don't allow overloading of destructors. (In theory we could, but it
1149 // would be a giant change to clang.)
1150 if (isa<CXXDestructorDecl>(New))
1151 return false;
1152
Artem Belevich94a55e82015-09-22 17:22:59 +00001153 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1154 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001155 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001156 return false;
1157
1158 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1159
Justin Lebar53b000af2016-10-03 16:48:27 +00001160 // Allow overloading of functions with same signature and different CUDA
1161 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001162 return NewTarget != OldTarget;
1163 }
1164
John McCall1f82f242009-11-18 22:49:29 +00001165 // The signatures match; this is not an overload.
1166 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001167}
1168
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001169/// \brief Checks availability of the function depending on the current
1170/// function context. Inside an unavailable function, unavailability is ignored.
1171///
1172/// \returns true if \arg FD is unavailable and current context is inside
1173/// an available function, false otherwise.
1174bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001175 if (!FD->isUnavailable())
1176 return false;
1177
1178 // Walk up the context of the caller.
1179 Decl *C = cast<Decl>(CurContext);
1180 do {
1181 if (C->isUnavailable())
1182 return false;
1183 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1184 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001185}
1186
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001187/// \brief Tries a user-defined conversion from From to ToType.
1188///
1189/// Produces an implicit conversion sequence for when a standard conversion
1190/// is not an option. See TryImplicitConversion for more information.
1191static ImplicitConversionSequence
1192TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1193 bool SuppressUserConversions,
1194 bool AllowExplicit,
1195 bool InOverloadResolution,
1196 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001197 bool AllowObjCWritebackConversion,
1198 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001199 ImplicitConversionSequence ICS;
1200
1201 if (SuppressUserConversions) {
1202 // We're not in the case above, so there is no conversion that
1203 // we can perform.
1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1205 return ICS;
1206 }
1207
1208 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001209 OverloadCandidateSet Conversions(From->getExprLoc(),
1210 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001211 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1212 Conversions, AllowExplicit,
1213 AllowObjCConversionOnExplicit)) {
1214 case OR_Success:
1215 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001216 ICS.setUserDefined();
1217 // C++ [over.ics.user]p4:
1218 // A conversion of an expression of class type to the same class
1219 // type is given Exact Match rank, and a conversion of an
1220 // expression of class type to a base class of that type is
1221 // given Conversion rank, in spite of the fact that a copy
1222 // constructor (i.e., a user-defined conversion function) is
1223 // called for those cases.
1224 if (CXXConstructorDecl *Constructor
1225 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1226 QualType FromCanon
1227 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1228 QualType ToCanon
1229 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1230 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001231 (FromCanon == ToCanon ||
1232 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001233 // Turn this into a "standard" conversion sequence, so that it
1234 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001235 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001236 ICS.setStandard();
1237 ICS.Standard.setAsIdentityConversion();
1238 ICS.Standard.setFromType(From->getType());
1239 ICS.Standard.setAllToTypes(ToType);
1240 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001241 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001242 if (ToCanon != FromCanon)
1243 ICS.Standard.Second = ICK_Derived_To_Base;
1244 }
1245 }
Richard Smith48372b62015-01-27 03:30:40 +00001246 break;
1247
1248 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001249 ICS.setAmbiguous();
1250 ICS.Ambiguous.setFromType(From->getType());
1251 ICS.Ambiguous.setToType(ToType);
1252 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1253 Cand != Conversions.end(); ++Cand)
1254 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001255 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001256 break;
Richard Smith48372b62015-01-27 03:30:40 +00001257
1258 // Fall through.
1259 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001260 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001261 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001262 }
1263
1264 return ICS;
1265}
1266
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001267/// TryImplicitConversion - Attempt to perform an implicit conversion
1268/// from the given expression (Expr) to the given type (ToType). This
1269/// function returns an implicit conversion sequence that can be used
1270/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001271///
1272/// void f(float f);
1273/// void g(int i) { f(i); }
1274///
1275/// this routine would produce an implicit conversion sequence to
1276/// describe the initialization of f from i, which will be a standard
1277/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1278/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1279//
1280/// Note that this routine only determines how the conversion can be
1281/// performed; it does not actually perform the conversion. As such,
1282/// it will not produce any diagnostics if no conversion is available,
1283/// but will instead return an implicit conversion sequence of kind
1284/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001285///
1286/// If @p SuppressUserConversions, then user-defined conversions are
1287/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001288/// If @p AllowExplicit, then explicit user-defined conversions are
1289/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001290///
1291/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1292/// writeback conversion, which allows __autoreleasing id* parameters to
1293/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001294static ImplicitConversionSequence
1295TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1296 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001298 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001299 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001300 bool AllowObjCWritebackConversion,
1301 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001303 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001304 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001305 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001306 return ICS;
1307 }
1308
David Blaikiebbafb8a2012-03-11 07:00:24 +00001309 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001310 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001311 return ICS;
1312 }
1313
Douglas Gregor836a7e82010-08-11 02:15:33 +00001314 // C++ [over.ics.user]p4:
1315 // A conversion of an expression of class type to the same class
1316 // type is given Exact Match rank, and a conversion of an
1317 // expression of class type to a base class of that type is
1318 // given Conversion rank, in spite of the fact that a copy/move
1319 // constructor (i.e., a user-defined conversion function) is
1320 // called for those cases.
1321 QualType FromType = From->getType();
1322 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001323 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001324 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001325 ICS.setStandard();
1326 ICS.Standard.setAsIdentityConversion();
1327 ICS.Standard.setFromType(FromType);
1328 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
Douglas Gregor5ab11652010-04-17 22:01:05 +00001330 // We don't actually check at this point whether there is a valid
1331 // copy/move constructor, since overloading just assumes that it
1332 // exists. When we actually perform initialization, we'll find the
1333 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001334 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335
Douglas Gregor5ab11652010-04-17 22:01:05 +00001336 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001337 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001338 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001339
Douglas Gregor836a7e82010-08-11 02:15:33 +00001340 return ICS;
1341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001343 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1344 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001345 AllowObjCWritebackConversion,
1346 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001347}
1348
John McCall31168b02011-06-15 23:02:42 +00001349ImplicitConversionSequence
1350Sema::TryImplicitConversion(Expr *From, QualType ToType,
1351 bool SuppressUserConversions,
1352 bool AllowExplicit,
1353 bool InOverloadResolution,
1354 bool CStyle,
1355 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001356 return ::TryImplicitConversion(*this, From, ToType,
1357 SuppressUserConversions, AllowExplicit,
1358 InOverloadResolution, CStyle,
1359 AllowObjCWritebackConversion,
1360 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001361}
1362
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001363/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001364/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001365/// converted expression. Flavor is the kind of conversion we're
1366/// performing, used in the error message. If @p AllowExplicit,
1367/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001368ExprResult
1369Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001370 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001371 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001372 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001373}
1374
John Wiegley01296292011-04-08 18:41:53 +00001375ExprResult
1376Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001377 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001378 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001379 if (checkPlaceholderForOverload(*this, From))
1380 return ExprError();
1381
John McCall31168b02011-06-15 23:02:42 +00001382 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1383 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001385 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001386 if (getLangOpts().ObjC1)
1387 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1388 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001389 ICS = ::TryImplicitConversion(*this, From, ToType,
1390 /*SuppressUserConversions=*/false,
1391 AllowExplicit,
1392 /*InOverloadResolution=*/false,
1393 /*CStyle=*/false,
1394 AllowObjCWritebackConversion,
1395 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001396 return PerformImplicitConversion(From, ToType, ICS, Action);
1397}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398
1399/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001400/// conversion that strips "noexcept" or "noreturn" off the nested function
1401/// type.
1402bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001403 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001404 if (Context.hasSameUnqualifiedType(FromType, ToType))
1405 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
John McCall991eb4b2010-12-21 00:44:39 +00001407 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001408 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001409 // where F adds one of the following at most once:
1410 // - a pointer
1411 // - a member pointer
1412 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001413 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001414 CanQualType CanTo = Context.getCanonicalType(ToType);
1415 CanQualType CanFrom = Context.getCanonicalType(FromType);
1416 Type::TypeClass TyClass = CanTo->getTypeClass();
1417 if (TyClass != CanFrom->getTypeClass()) return false;
1418 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1419 if (TyClass == Type::Pointer) {
1420 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1421 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1422 } else if (TyClass == Type::BlockPointer) {
1423 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1424 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1425 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001426 auto ToMPT = CanTo.getAs<MemberPointerType>();
1427 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1428 // A function pointer conversion cannot change the class of the function.
1429 if (ToMPT->getClass() != FromMPT->getClass())
1430 return false;
1431 CanTo = ToMPT->getPointeeType();
1432 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001433 } else {
1434 return false;
1435 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001436
John McCall991eb4b2010-12-21 00:44:39 +00001437 TyClass = CanTo->getTypeClass();
1438 if (TyClass != CanFrom->getTypeClass()) return false;
1439 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1440 return false;
1441 }
1442
Richard Smith3c4f8d22016-10-16 17:54:23 +00001443 const auto *FromFn = cast<FunctionType>(CanFrom);
1444 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001445
Richard Smith6f427402016-10-20 00:01:36 +00001446 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001447 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1448
1449 bool Changed = false;
1450
1451 // Drop 'noreturn' if not present in target type.
1452 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1453 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1454 Changed = true;
1455 }
1456
1457 // Drop 'noexcept' if not present in target type.
1458 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001459 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001460 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1461 FromFn = cast<FunctionType>(
1462 Context.getFunctionType(FromFPT->getReturnType(),
1463 FromFPT->getParamTypes(),
1464 FromFPT->getExtProtoInfo().withExceptionSpec(
1465 FunctionProtoType::ExceptionSpecInfo()))
1466 .getTypePtr());
1467 Changed = true;
1468 }
1469 }
1470
1471 if (!Changed)
1472 return false;
1473
John McCall991eb4b2010-12-21 00:44:39 +00001474 assert(QualType(FromFn, 0).isCanonical());
1475 if (QualType(FromFn, 0) != CanTo) return false;
1476
1477 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001478 return true;
1479}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
Douglas Gregor46188682010-05-18 22:42:18 +00001481/// \brief Determine whether the conversion from FromType to ToType is a valid
1482/// vector conversion.
1483///
1484/// \param ICK Will be set to the vector conversion kind, if this is a vector
1485/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001486static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001488 // We need at least one of these types to be a vector type to have a vector
1489 // conversion.
1490 if (!ToType->isVectorType() && !FromType->isVectorType())
1491 return false;
1492
1493 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001494 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001495 return false;
1496
1497 // There are no conversions between extended vector types, only identity.
1498 if (ToType->isExtVectorType()) {
1499 // There are no conversions between extended vector types other than the
1500 // identity conversion.
1501 if (FromType->isExtVectorType())
1502 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503
Douglas Gregor46188682010-05-18 22:42:18 +00001504 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001505 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001506 ICK = ICK_Vector_Splat;
1507 return true;
1508 }
1509 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001510
1511 // We can perform the conversion between vector types in the following cases:
1512 // 1)vector types are equivalent AltiVec and GCC vector types
1513 // 2)lax vector conversions are permitted and the vector types are of the
1514 // same size
1515 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001516 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1517 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001518 ICK = ICK_Vector_Conversion;
1519 return true;
1520 }
Douglas Gregor46188682010-05-18 22:42:18 +00001521 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001522
Douglas Gregor46188682010-05-18 22:42:18 +00001523 return false;
1524}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001525
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001526static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1527 bool InOverloadResolution,
1528 StandardConversionSequence &SCS,
1529 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001530
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001531/// IsStandardConversion - Determines whether there is a standard
1532/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1533/// expression From to the type ToType. Standard conversion sequences
1534/// only consider non-class types; for conversions that involve class
1535/// types, use TryImplicitConversion. If a conversion exists, SCS will
1536/// contain the standard conversion sequence required to perform this
1537/// conversion and this routine will return true. Otherwise, this
1538/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001539static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1540 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001541 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001542 bool CStyle,
1543 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001547 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001548 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001549 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001550 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001552 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001553 // abort early. When overloading in C, however, we do permit them.
1554 if (S.getLangOpts().CPlusPlus &&
1555 (FromType->isRecordType() || ToType->isRecordType()))
1556 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001557
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 // The first conversion can be an lvalue-to-rvalue conversion,
1559 // array-to-pointer conversion, or function-to-pointer conversion
1560 // (C++ 4p1).
1561
John McCall5c32be02010-08-24 20:38:10 +00001562 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001563 DeclAccessPair AccessPair;
1564 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001566 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001567 // We were able to resolve the address of the overloaded function,
1568 // so we can convert to the type of that function.
1569 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001570 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001571
1572 // we can sometimes resolve &foo<int> regardless of ToType, so check
1573 // if the type matches (identity) or we are converting to bool
1574 if (!S.Context.hasSameUnqualifiedType(
1575 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1576 QualType resultTy;
1577 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001578 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001579 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1580 // otherwise, only a boolean conversion is standard
1581 if (!ToType->isBooleanType())
1582 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584
Chandler Carruthffce2452011-03-29 08:08:18 +00001585 // Check if the "from" expression is taking the address of an overloaded
1586 // function and recompute the FromType accordingly. Take advantage of the
1587 // fact that non-static member functions *must* have such an address-of
1588 // expression.
1589 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1590 if (Method && !Method->isStatic()) {
1591 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1592 "Non-unary operator on non-static member address");
1593 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1594 == UO_AddrOf &&
1595 "Non-address-of operator on non-static member address");
1596 const Type *ClassType
1597 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1598 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001599 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1600 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1601 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001602 "Non-address-of operator for overloaded function expression");
1603 FromType = S.Context.getPointerType(FromType);
1604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605
Douglas Gregor980fb162010-04-29 18:24:40 +00001606 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001607 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1608 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001609 assert(S.Context.hasSameType(
1610 FromType,
1611 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001612 } else {
1613 return false;
1614 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001615 }
John McCall154a2fd2011-08-30 00:57:29 +00001616 // Lvalue-to-rvalue conversion (C++11 4.1):
1617 // A glvalue (3.10) of a non-function, non-array type T can
1618 // be converted to a prvalue.
1619 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001620 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001621 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001622 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624
Douglas Gregorc79862f2012-04-12 17:51:55 +00001625 // C11 6.3.2.1p2:
1626 // ... if the lvalue has atomic type, the value has the non-atomic version
1627 // of the type of the lvalue ...
1628 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1629 FromType = Atomic->getValueType();
1630
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631 // If T is a non-class type, the type of the rvalue is the
1632 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001633 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1634 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 } else if (FromType->isArrayType()) {
1637 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
1640 // An lvalue or rvalue of type "array of N T" or "array of unknown
1641 // bound of T" can be converted to an rvalue of type "pointer to
1642 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001643 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644
John McCall5c32be02010-08-24 20:38:10 +00001645 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001646 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001647 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001648
1649 // For the purpose of ranking in overload resolution
1650 // (13.3.3.1.1), this conversion is considered an
1651 // array-to-pointer conversion followed by a qualification
1652 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 SCS.Second = ICK_Identity;
1654 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001655 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001656 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001657 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001658 }
John McCall086a4642010-11-24 05:12:34 +00001659 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001660 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001661 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001663 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1664 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1665 if (!S.checkAddressOfFunctionIsAvailable(FD))
1666 return false;
1667
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 // An lvalue of function type T can be converted to an rvalue of
1669 // type "pointer to T." The result is a pointer to the
1670 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001671 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001672 } else {
1673 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001674 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001676 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677
1678 // The second conversion can be an integral promotion, floating
1679 // point promotion, integral conversion, floating point conversion,
1680 // floating-integral conversion, pointer conversion,
1681 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001682 // For overloading in C, this can also be a "compatible-type"
1683 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001684 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001685 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001686 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687 // The unqualified versions of the types are the same: there's no
1688 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001690 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001691 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001692 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001694 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001695 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001698 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001699 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001700 SCS.Second = ICK_Complex_Promotion;
1701 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001702 } else if (ToType->isBooleanType() &&
1703 (FromType->isArithmeticType() ||
1704 FromType->isAnyPointerType() ||
1705 FromType->isBlockPointerType() ||
1706 FromType->isMemberPointerType() ||
1707 FromType->isNullPtrType())) {
1708 // Boolean conversions (C++ 4.12).
1709 SCS.Second = ICK_Boolean_Conversion;
1710 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001711 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001712 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001713 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001714 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001716 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001717 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001718 SCS.Second = ICK_Complex_Conversion;
1719 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001720 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1721 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001722 // Complex-real conversions (C99 6.3.1.7)
1723 SCS.Second = ICK_Complex_Real;
1724 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001725 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001726 // FIXME: disable conversions between long double and __float128 if
1727 // their representation is different until there is back end support
1728 // We of course allow this conversion if long double is really double.
1729 if (&S.Context.getFloatTypeSemantics(FromType) !=
1730 &S.Context.getFloatTypeSemantics(ToType)) {
1731 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1732 ToType == S.Context.LongDoubleTy) ||
1733 (FromType == S.Context.LongDoubleTy &&
1734 ToType == S.Context.Float128Ty));
1735 if (Float128AndLongDouble &&
1736 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001737 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001738 return false;
1739 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001740 // Floating point conversions (C++ 4.8).
1741 SCS.Second = ICK_Floating_Conversion;
1742 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001744 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001745 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001746 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001747 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001748 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001750 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001751 SCS.Second = ICK_Block_Pointer_Conversion;
1752 } else if (AllowObjCWritebackConversion &&
1753 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1754 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001755 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1756 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001757 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001758 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001759 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001760 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001762 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001763 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001764 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001765 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001766 SCS.Second = SecondICK;
1767 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001768 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001769 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001770 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001771 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001772 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001773 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1774 InOverloadResolution,
1775 SCS, CStyle)) {
1776 SCS.Second = ICK_TransparentUnionConversion;
1777 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001778 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1779 CStyle)) {
1780 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001781 // appropriately.
1782 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001783 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001784 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001785 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001786 SCS.Second = ICK_Zero_Event_Conversion;
1787 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788 } else {
1789 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001790 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001792 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001793
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001794 // The third conversion can be a function pointer conversion or a
1795 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001796 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001797 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1798 // Function pointer conversions (removing 'noexcept') including removal of
1799 // 'noreturn' (Clang extension).
1800 SCS.Third = ICK_Function_Conversion;
1801 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1802 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001803 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001804 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001805 FromType = ToType;
1806 } else {
1807 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001808 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001809 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001810
1811 // C++ [over.best.ics]p6:
1812 // [...] Any difference in top-level cv-qualification is
1813 // subsumed by the initialization itself and does not constitute
1814 // a conversion. [...]
1815 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1816 QualType CanonTo = S.Context.getCanonicalType(ToType);
1817 if (CanonFrom.getLocalUnqualifiedType()
1818 == CanonTo.getLocalUnqualifiedType() &&
1819 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1820 FromType = ToType;
1821 CanonFrom = CanonTo;
1822 }
1823
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001824 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825
George Burgess IV45461812015-10-11 20:13:20 +00001826 if (CanonFrom == CanonTo)
1827 return true;
1828
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001830 // this is a bad conversion sequence, unless we're resolving an overload in C.
1831 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001832 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833
George Burgess IV45461812015-10-11 20:13:20 +00001834 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001835 Sema::AssignConvertType Conv =
1836 S.CheckSingleAssignmentConstraints(ToType, ER,
1837 /*Diagnose=*/false,
1838 /*DiagnoseCFAudited=*/false,
1839 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001840 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001841 switch (Conv) {
1842 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001843 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001844 break;
1845 // For our purposes, discarding qualifiers is just as bad as using an
1846 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1847 // qualifiers, as well.
1848 case Sema::CompatiblePointerDiscardsQualifiers:
1849 case Sema::IncompatiblePointer:
1850 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001851 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001852 break;
1853 default:
George Burgess IV45461812015-10-11 20:13:20 +00001854 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001855 }
George Burgess IV45461812015-10-11 20:13:20 +00001856
George Burgess IV6098fd12016-09-03 00:28:25 +00001857 // First can only be an lvalue conversion, so we pretend that this was the
1858 // second conversion. First should already be valid from earlier in the
1859 // function.
1860 SCS.Second = SecondConv;
1861 SCS.setToType(1, ToType);
1862
1863 // Third is Identity, because Second should rank us worse than any other
1864 // conversion. This could also be ICK_Qualification, but it's simpler to just
1865 // lump everything in with the second conversion, and we don't gain anything
1866 // from making this ICK_Qualification.
1867 SCS.Third = ICK_Identity;
1868 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001869 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870}
George Burgess IV2099b542016-09-02 22:59:57 +00001871
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001872static bool
1873IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1874 QualType &ToType,
1875 bool InOverloadResolution,
1876 StandardConversionSequence &SCS,
1877 bool CStyle) {
1878
1879 const RecordType *UT = ToType->getAsUnionType();
1880 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1881 return false;
1882 // The field to initialize within the transparent union.
1883 RecordDecl *UD = UT->getDecl();
1884 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001885 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001886 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1887 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001888 ToType = it->getType();
1889 return true;
1890 }
1891 }
1892 return false;
1893}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001894
1895/// IsIntegralPromotion - Determines whether the conversion from the
1896/// expression From (whose potentially-adjusted type is FromType) to
1897/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1898/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001899bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001900 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001901 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001902 if (!To) {
1903 return false;
1904 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001905
1906 // An rvalue of type char, signed char, unsigned char, short int, or
1907 // unsigned short int can be converted to an rvalue of type int if
1908 // int can represent all the values of the source type; otherwise,
1909 // the source rvalue can be converted to an rvalue of type unsigned
1910 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001911 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1912 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001913 if (// We can promote any signed, promotable integer type to an int
1914 (FromType->isSignedIntegerType() ||
1915 // We can promote any unsigned integer type whose size is
1916 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001917 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001918 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001919 }
1920
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001921 return To->getKind() == BuiltinType::UInt;
1922 }
1923
Richard Smithb9c5a602012-09-13 21:18:54 +00001924 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925 // A prvalue of an unscoped enumeration type whose underlying type is not
1926 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1927 // following types that can represent all the values of the enumeration
1928 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1929 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001930 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001932 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933 // with lowest integer conversion rank (4.13) greater than the rank of long
1934 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001935 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001936 // C++11 [conv.prom]p4:
1937 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1938 // can be converted to a prvalue of its underlying type. Moreover, if
1939 // integral promotion can be applied to its underlying type, a prvalue of an
1940 // unscoped enumeration type whose underlying type is fixed can also be
1941 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001942 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1943 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1944 // provided for a scoped enumeration.
1945 if (FromEnumType->getDecl()->isScoped())
1946 return false;
1947
Richard Smithb9c5a602012-09-13 21:18:54 +00001948 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001949 // even if that's not the promoted type. Note that the check for promoting
1950 // the underlying type is based on the type alone, and does not consider
1951 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001952 if (FromEnumType->getDecl()->isFixed()) {
1953 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1954 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001955 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001956 }
1957
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001958 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001960 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001961 return Context.hasSameUnqualifiedType(
1962 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001963 }
John McCall56774992009-12-09 09:09:27 +00001964
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001965 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1967 // to an rvalue a prvalue of the first of the following types that can
1968 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001969 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001971 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001973 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001974 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001975 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976 // Determine whether the type we're converting from is signed or
1977 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001978 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001979 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001981 // The types we'll try to promote to, in the appropriate
1982 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001983 QualType PromoteTypes[6] = {
1984 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001985 Context.LongTy, Context.UnsignedLongTy ,
1986 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001987 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001988 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001989 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1990 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001991 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001992 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1993 // We found the type that we can promote to. If this is the
1994 // type we wanted, we have a promotion. Otherwise, no
1995 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001996 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001997 }
1998 }
1999 }
2000
2001 // An rvalue for an integral bit-field (9.6) can be converted to an
2002 // rvalue of type int if int can represent all the values of the
2003 // bit-field; otherwise, it can be converted to unsigned int if
2004 // unsigned int can represent all the values of the bit-field. If
2005 // the bit-field is larger yet, no integral promotion applies to
2006 // it. If the bit-field has an enumerated type, it is treated as any
2007 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002008 // FIXME: We should delay checking of bit-fields until we actually perform the
2009 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002010 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002011 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002012 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002013 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002014 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002015 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002016 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002018 // Are we promoting to an int from a bitfield that fits in an int?
2019 if (BitWidth < ToSize ||
2020 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2021 return To->getKind() == BuiltinType::Int;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002024 // Are we promoting to an unsigned int from an unsigned bitfield
2025 // that fits into an unsigned int?
2026 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2027 return To->getKind() == BuiltinType::UInt;
2028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002030 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002031 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002032 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002035 // An rvalue of type bool can be converted to an rvalue of type int,
2036 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002037 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002038 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002039 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002040
2041 return false;
2042}
2043
2044/// IsFloatingPointPromotion - Determines whether the conversion from
2045/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2046/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002047bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002048 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2049 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002050 /// An rvalue of type float can be converted to an rvalue of type
2051 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 if (FromBuiltin->getKind() == BuiltinType::Float &&
2053 ToBuiltin->getKind() == BuiltinType::Double)
2054 return true;
2055
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002056 // C99 6.3.1.5p1:
2057 // When a float is promoted to double or long double, or a
2058 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002060 (FromBuiltin->getKind() == BuiltinType::Float ||
2061 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002062 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2063 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002064 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002065
2066 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002067 if (!getLangOpts().NativeHalfType &&
2068 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002069 ToBuiltin->getKind() == BuiltinType::Float)
2070 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002071 }
2072
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073 return false;
2074}
2075
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076/// \brief Determine if a conversion is a complex promotion.
2077///
2078/// A complex promotion is defined as a complex -> complex conversion
2079/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002080/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002081bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002082 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002083 if (!FromComplex)
2084 return false;
2085
John McCall9dd450b2009-09-21 23:43:11 +00002086 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002087 if (!ToComplex)
2088 return false;
2089
2090 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002091 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002092 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002093 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002094}
2095
Douglas Gregor237f96c2008-11-26 23:31:11 +00002096/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2097/// the pointer type FromPtr to a pointer to type ToPointee, with the
2098/// same type qualifiers as FromPtr has on its pointee type. ToType,
2099/// if non-empty, will be a pointer to ToType that may or may not have
2100/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002101///
Mike Stump11289f42009-09-09 15:08:12 +00002102static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002103BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002104 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002105 ASTContext &Context,
2106 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002107 assert((FromPtr->getTypeClass() == Type::Pointer ||
2108 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2109 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110
John McCall31168b02011-06-15 23:02:42 +00002111 /// Conversions to 'id' subsume cv-qualifier conversions.
2112 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002113 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
2115 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002116 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002118 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002119
John McCall31168b02011-06-15 23:02:42 +00002120 if (StripObjCLifetime)
2121 Quals.removeObjCLifetime();
2122
Mike Stump11289f42009-09-09 15:08:12 +00002123 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002124 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002126 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002127 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002128
2129 // Build a pointer to ToPointee. It has the right qualifiers
2130 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002131 if (isa<ObjCObjectPointerType>(ToType))
2132 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133 return Context.getPointerType(ToPointee);
2134 }
2135
2136 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002137 QualType QualifiedCanonToPointee
2138 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002140 if (isa<ObjCObjectPointerType>(ToType))
2141 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2142 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002143}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Mike Stump11289f42009-09-09 15:08:12 +00002145static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002146 bool InOverloadResolution,
2147 ASTContext &Context) {
2148 // Handle value-dependent integral null pointer constants correctly.
2149 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2150 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002151 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002152 return !InOverloadResolution;
2153
Douglas Gregor56751b52009-09-25 04:25:58 +00002154 return Expr->isNullPointerConstant(Context,
2155 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2156 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002157}
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002159/// IsPointerConversion - Determines whether the conversion of the
2160/// expression From, which has the (possibly adjusted) type FromType,
2161/// can be converted to the type ToType via a pointer conversion (C++
2162/// 4.10). If so, returns true and places the converted type (that
2163/// might differ from ToType in its cv-qualifiers at some level) into
2164/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002165///
Douglas Gregora29dc052008-11-27 01:19:21 +00002166/// This routine also supports conversions to and from block pointers
2167/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2168/// pointers to interfaces. FIXME: Once we've determined the
2169/// appropriate overloading rules for Objective-C, we may want to
2170/// split the Objective-C checks into a different routine; however,
2171/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002172/// conversions, so for now they live here. IncompatibleObjC will be
2173/// set if the conversion is an allowed Objective-C conversion that
2174/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002175bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002176 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002177 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002178 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002179 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002180 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2181 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002182 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002183
Mike Stump11289f42009-09-09 15:08:12 +00002184 // Conversion from a null pointer constant to any Objective-C pointer type.
2185 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002186 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002187 ConvertedType = ToType;
2188 return true;
2189 }
2190
Douglas Gregor231d1c62008-11-27 00:15:41 +00002191 // Blocks: Block pointers can be converted to void*.
2192 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002193 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002194 ConvertedType = ToType;
2195 return true;
2196 }
2197 // Blocks: A null pointer constant can be converted to a block
2198 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002199 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002200 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002201 ConvertedType = ToType;
2202 return true;
2203 }
2204
Sebastian Redl576fd422009-05-10 18:38:11 +00002205 // If the left-hand-side is nullptr_t, the right side can be a null
2206 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002207 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002208 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002209 ConvertedType = ToType;
2210 return true;
2211 }
2212
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002214 if (!ToTypePtr)
2215 return false;
2216
2217 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002218 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002219 ConvertedType = ToType;
2220 return true;
2221 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002222
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002223 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002224 // , including objective-c pointers.
2225 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002226 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002227 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002228 ConvertedType = BuildSimilarlyQualifiedPointerType(
2229 FromType->getAs<ObjCObjectPointerType>(),
2230 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002231 ToType, Context);
2232 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002233 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002234 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002235 if (!FromTypePtr)
2236 return false;
2237
2238 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002239
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002241 // pointer conversion, so don't do all of the work below.
2242 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2243 return false;
2244
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002245 // An rvalue of type "pointer to cv T," where T is an object type,
2246 // can be converted to an rvalue of type "pointer to cv void" (C++
2247 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002248 if (FromPointeeType->isIncompleteOrObjectType() &&
2249 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002250 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002251 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002252 ToType, Context,
2253 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002254 return true;
2255 }
2256
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002257 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002258 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002259 ToPointeeType->isVoidType()) {
2260 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2261 ToPointeeType,
2262 ToType, Context);
2263 return true;
2264 }
2265
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002266 // When we're overloading in C, we allow a special kind of pointer
2267 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002268 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002269 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002271 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002272 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002273 return true;
2274 }
2275
Douglas Gregor5c407d92008-10-23 00:40:37 +00002276 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002277 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002278 // An rvalue of type "pointer to cv D," where D is a class type,
2279 // can be converted to an rvalue of type "pointer to cv B," where
2280 // B is a base class (clause 10) of D. If B is an inaccessible
2281 // (clause 11) or ambiguous (10.2) base class of D, a program that
2282 // necessitates this conversion is ill-formed. The result of the
2283 // conversion is a pointer to the base class sub-object of the
2284 // derived class object. The null pointer value is converted to
2285 // the null pointer value of the destination type.
2286 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002287 // Note that we do not check for ambiguity or inaccessibility
2288 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002289 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002290 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002291 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002292 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002293 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002294 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002295 ToType, Context);
2296 return true;
2297 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002298
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002299 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2300 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2301 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2302 ToPointeeType,
2303 ToType, Context);
2304 return true;
2305 }
2306
Douglas Gregora119f102008-12-19 19:13:09 +00002307 return false;
2308}
Douglas Gregoraec25842011-04-26 23:16:46 +00002309
2310/// \brief Adopt the given qualifiers for the given type.
2311static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2312 Qualifiers TQs = T.getQualifiers();
2313
2314 // Check whether qualifiers already match.
2315 if (TQs == Qs)
2316 return T;
2317
2318 if (Qs.compatiblyIncludes(TQs))
2319 return Context.getQualifiedType(T, Qs);
2320
2321 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2322}
Douglas Gregora119f102008-12-19 19:13:09 +00002323
2324/// isObjCPointerConversion - Determines whether this is an
2325/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2326/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002327bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002328 QualType& ConvertedType,
2329 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002330 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002331 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002332
Douglas Gregoraec25842011-04-26 23:16:46 +00002333 // The set of qualifiers on the type we're converting from.
2334 Qualifiers FromQualifiers = FromType.getQualifiers();
2335
Steve Naroff7cae42b2009-07-10 23:34:53 +00002336 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002337 const ObjCObjectPointerType* ToObjCPtr =
2338 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002339 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002340 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002341
Steve Naroff7cae42b2009-07-10 23:34:53 +00002342 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002343 // If the pointee types are the same (ignoring qualifications),
2344 // then this is not a pointer conversion.
2345 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2346 FromObjCPtr->getPointeeType()))
2347 return false;
2348
Douglas Gregorab209d82015-07-07 03:58:42 +00002349 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002350 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002351 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2352 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002353 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002354 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2355 FromObjCPtr->getPointeeType()))
2356 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002357 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002358 ToObjCPtr->getPointeeType(),
2359 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002360 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002361 return true;
2362 }
2363
2364 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2365 // Okay: this is some kind of implicit downcast of Objective-C
2366 // interfaces, which is permitted. However, we're going to
2367 // complain about it.
2368 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002370 ToObjCPtr->getPointeeType(),
2371 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002372 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002373 return true;
2374 }
Mike Stump11289f42009-09-09 15:08:12 +00002375 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002376 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002377 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002378 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002381 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002382 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002383 // to a block pointer type.
2384 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002385 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002386 return true;
2387 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002388 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002390 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002391 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002393 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002394 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002395 return true;
2396 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002397 else
Douglas Gregora119f102008-12-19 19:13:09 +00002398 return false;
2399
Douglas Gregor033f56d2008-12-23 00:53:59 +00002400 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002401 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002402 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002403 else if (const BlockPointerType *FromBlockPtr =
2404 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002405 FromPointeeType = FromBlockPtr->getPointeeType();
2406 else
Douglas Gregora119f102008-12-19 19:13:09 +00002407 return false;
2408
Douglas Gregora119f102008-12-19 19:13:09 +00002409 // If we have pointers to pointers, recursively check whether this
2410 // is an Objective-C conversion.
2411 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2412 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2413 IncompatibleObjC)) {
2414 // We always complain about this conversion.
2415 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002416 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002417 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002418 return true;
2419 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002420 // Allow conversion of pointee being objective-c pointer to another one;
2421 // as in I* to id.
2422 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2423 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2424 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2425 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002426
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002427 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002429 return true;
2430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431
Douglas Gregor033f56d2008-12-23 00:53:59 +00002432 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002433 // differences in the argument and result types are in Objective-C
2434 // pointer conversions. If so, we permit the conversion (but
2435 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002436 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002437 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002438 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002439 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002440 if (FromFunctionType && ToFunctionType) {
2441 // If the function types are exactly the same, this isn't an
2442 // Objective-C pointer conversion.
2443 if (Context.getCanonicalType(FromPointeeType)
2444 == Context.getCanonicalType(ToPointeeType))
2445 return false;
2446
2447 // Perform the quick checks that will tell us whether these
2448 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002449 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2451 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2452 return false;
2453
2454 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002455 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2456 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002457 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002458 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2459 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002460 ConvertedType, IncompatibleObjC)) {
2461 // Okay, we have an Objective-C pointer conversion.
2462 HasObjCConversion = true;
2463 } else {
2464 // Function types are too different. Abort.
2465 return false;
2466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Douglas Gregora119f102008-12-19 19:13:09 +00002468 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002469 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002470 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002471 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2472 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002473 if (Context.getCanonicalType(FromArgType)
2474 == Context.getCanonicalType(ToArgType)) {
2475 // Okay, the types match exactly. Nothing to do.
2476 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2477 ConvertedType, IncompatibleObjC)) {
2478 // Okay, we have an Objective-C pointer conversion.
2479 HasObjCConversion = true;
2480 } else {
2481 // Argument types are too different. Abort.
2482 return false;
2483 }
2484 }
2485
2486 if (HasObjCConversion) {
2487 // We had an Objective-C conversion. Allow this pointer
2488 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002489 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002490 IncompatibleObjC = true;
2491 return true;
2492 }
2493 }
2494
Sebastian Redl72b597d2009-01-25 19:43:20 +00002495 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002496}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497
John McCall31168b02011-06-15 23:02:42 +00002498/// \brief Determine whether this is an Objective-C writeback conversion,
2499/// used for parameter passing when performing automatic reference counting.
2500///
2501/// \param FromType The type we're converting form.
2502///
2503/// \param ToType The type we're converting to.
2504///
2505/// \param ConvertedType The type that will be produced after applying
2506/// this conversion.
2507bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2508 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002509 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002510 Context.hasSameUnqualifiedType(FromType, ToType))
2511 return false;
2512
2513 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2514 QualType ToPointee;
2515 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2516 ToPointee = ToPointer->getPointeeType();
2517 else
2518 return false;
2519
2520 Qualifiers ToQuals = ToPointee.getQualifiers();
2521 if (!ToPointee->isObjCLifetimeType() ||
2522 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002523 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002524 return false;
2525
2526 // Argument must be a pointer to __strong to __weak.
2527 QualType FromPointee;
2528 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2529 FromPointee = FromPointer->getPointeeType();
2530 else
2531 return false;
2532
2533 Qualifiers FromQuals = FromPointee.getQualifiers();
2534 if (!FromPointee->isObjCLifetimeType() ||
2535 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2536 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2537 return false;
2538
2539 // Make sure that we have compatible qualifiers.
2540 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2541 if (!ToQuals.compatiblyIncludes(FromQuals))
2542 return false;
2543
2544 // Remove qualifiers from the pointee type we're converting from; they
2545 // aren't used in the compatibility check belong, and we'll be adding back
2546 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2547 FromPointee = FromPointee.getUnqualifiedType();
2548
2549 // The unqualified form of the pointee types must be compatible.
2550 ToPointee = ToPointee.getUnqualifiedType();
2551 bool IncompatibleObjC;
2552 if (Context.typesAreCompatible(FromPointee, ToPointee))
2553 FromPointee = ToPointee;
2554 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2555 IncompatibleObjC))
2556 return false;
2557
2558 /// \brief Construct the type we're converting to, which is a pointer to
2559 /// __autoreleasing pointee.
2560 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2561 ConvertedType = Context.getPointerType(FromPointee);
2562 return true;
2563}
2564
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002565bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2566 QualType& ConvertedType) {
2567 QualType ToPointeeType;
2568 if (const BlockPointerType *ToBlockPtr =
2569 ToType->getAs<BlockPointerType>())
2570 ToPointeeType = ToBlockPtr->getPointeeType();
2571 else
2572 return false;
2573
2574 QualType FromPointeeType;
2575 if (const BlockPointerType *FromBlockPtr =
2576 FromType->getAs<BlockPointerType>())
2577 FromPointeeType = FromBlockPtr->getPointeeType();
2578 else
2579 return false;
2580 // We have pointer to blocks, check whether the only
2581 // differences in the argument and result types are in Objective-C
2582 // pointer conversions. If so, we permit the conversion.
2583
2584 const FunctionProtoType *FromFunctionType
2585 = FromPointeeType->getAs<FunctionProtoType>();
2586 const FunctionProtoType *ToFunctionType
2587 = ToPointeeType->getAs<FunctionProtoType>();
2588
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002589 if (!FromFunctionType || !ToFunctionType)
2590 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002591
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002592 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002593 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002594
2595 // Perform the quick checks that will tell us whether these
2596 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002597 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002598 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2599 return false;
2600
2601 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2602 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2603 if (FromEInfo != ToEInfo)
2604 return false;
2605
2606 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002607 if (Context.hasSameType(FromFunctionType->getReturnType(),
2608 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002609 // Okay, the types match exactly. Nothing to do.
2610 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002611 QualType RHS = FromFunctionType->getReturnType();
2612 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002613 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002614 !RHS.hasQualifiers() && LHS.hasQualifiers())
2615 LHS = LHS.getUnqualifiedType();
2616
2617 if (Context.hasSameType(RHS,LHS)) {
2618 // OK exact match.
2619 } else if (isObjCPointerConversion(RHS, LHS,
2620 ConvertedType, IncompatibleObjC)) {
2621 if (IncompatibleObjC)
2622 return false;
2623 // Okay, we have an Objective-C pointer conversion.
2624 }
2625 else
2626 return false;
2627 }
2628
2629 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002630 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002631 ArgIdx != NumArgs; ++ArgIdx) {
2632 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002633 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2634 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002635 if (Context.hasSameType(FromArgType, ToArgType)) {
2636 // Okay, the types match exactly. Nothing to do.
2637 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2638 ConvertedType, IncompatibleObjC)) {
2639 if (IncompatibleObjC)
2640 return false;
2641 // Okay, we have an Objective-C pointer conversion.
2642 } else
2643 // Argument types are too different. Abort.
2644 return false;
2645 }
John McCall18afab72016-03-01 00:49:02 +00002646 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2647 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002648 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002649
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002650 ConvertedType = ToType;
2651 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002652}
2653
Richard Trieucaff2472011-11-23 22:32:32 +00002654enum {
2655 ft_default,
2656 ft_different_class,
2657 ft_parameter_arity,
2658 ft_parameter_mismatch,
2659 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002660 ft_qualifer_mismatch,
2661 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002662};
2663
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002664/// Attempts to get the FunctionProtoType from a Type. Handles
2665/// MemberFunctionPointers properly.
2666static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2667 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2668 return FPT;
2669
2670 if (auto *MPT = FromType->getAs<MemberPointerType>())
2671 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2672
2673 return nullptr;
2674}
2675
Richard Trieucaff2472011-11-23 22:32:32 +00002676/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2677/// function types. Catches different number of parameter, mismatch in
2678/// parameter types, and different return types.
2679void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2680 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002681 // If either type is not valid, include no extra info.
2682 if (FromType.isNull() || ToType.isNull()) {
2683 PDiag << ft_default;
2684 return;
2685 }
2686
Richard Trieucaff2472011-11-23 22:32:32 +00002687 // Get the function type from the pointers.
2688 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2689 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2690 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002691 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002692 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2693 << QualType(FromMember->getClass(), 0);
2694 return;
2695 }
2696 FromType = FromMember->getPointeeType();
2697 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002698 }
2699
Richard Trieu96ed5b62011-12-13 23:19:45 +00002700 if (FromType->isPointerType())
2701 FromType = FromType->getPointeeType();
2702 if (ToType->isPointerType())
2703 ToType = ToType->getPointeeType();
2704
2705 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002706 FromType = FromType.getNonReferenceType();
2707 ToType = ToType.getNonReferenceType();
2708
Richard Trieucaff2472011-11-23 22:32:32 +00002709 // Don't print extra info for non-specialized template functions.
2710 if (FromType->isInstantiationDependentType() &&
2711 !FromType->getAs<TemplateSpecializationType>()) {
2712 PDiag << ft_default;
2713 return;
2714 }
2715
Richard Trieu96ed5b62011-12-13 23:19:45 +00002716 // No extra info for same types.
2717 if (Context.hasSameType(FromType, ToType)) {
2718 PDiag << ft_default;
2719 return;
2720 }
2721
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002722 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2723 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002724
2725 // Both types need to be function types.
2726 if (!FromFunction || !ToFunction) {
2727 PDiag << ft_default;
2728 return;
2729 }
2730
Alp Toker9cacbab2014-01-20 20:26:09 +00002731 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2732 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2733 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002734 return;
2735 }
2736
2737 // Handle different parameter types.
2738 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002739 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002740 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002741 << ToFunction->getParamType(ArgPos)
2742 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002743 return;
2744 }
2745
2746 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002747 if (!Context.hasSameType(FromFunction->getReturnType(),
2748 ToFunction->getReturnType())) {
2749 PDiag << ft_return_type << ToFunction->getReturnType()
2750 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002751 return;
2752 }
2753
2754 unsigned FromQuals = FromFunction->getTypeQuals(),
2755 ToQuals = ToFunction->getTypeQuals();
2756 if (FromQuals != ToQuals) {
2757 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2758 return;
2759 }
2760
Richard Smith3c4f8d22016-10-16 17:54:23 +00002761 // Handle exception specification differences on canonical type (in C++17
2762 // onwards).
2763 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2764 ->isNothrow(Context) !=
2765 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2766 ->isNothrow(Context)) {
2767 PDiag << ft_noexcept;
2768 return;
2769 }
2770
Richard Trieucaff2472011-11-23 22:32:32 +00002771 // Unable to find a difference, so add no extra info.
2772 PDiag << ft_default;
2773}
2774
Alp Toker9cacbab2014-01-20 20:26:09 +00002775/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002776/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002777/// they have same number of arguments. If the parameters are different,
2778/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002779bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2780 const FunctionProtoType *NewType,
2781 unsigned *ArgPos) {
2782 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2783 N = NewType->param_type_begin(),
2784 E = OldType->param_type_end();
2785 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002786 if (!Context.hasSameType(O->getUnqualifiedType(),
2787 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002788 if (ArgPos)
2789 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002790 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002791 }
2792 }
2793 return true;
2794}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002795
Douglas Gregor39c16d42008-10-24 04:54:22 +00002796/// CheckPointerConversion - Check the pointer conversion from the
2797/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002798/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002799/// conversions for which IsPointerConversion has already returned
2800/// true. It returns true and produces a diagnostic if there was an
2801/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002802bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002803 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002804 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002805 bool IgnoreBaseAccess,
2806 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002807 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002808 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002809
John McCall8cb679e2010-11-15 09:13:47 +00002810 Kind = CK_BitCast;
2811
George Burgess IV60bc9722016-01-13 23:36:34 +00002812 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002813 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002814 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002815 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2816 DiagRuntimeBehavior(From->getExprLoc(), From,
2817 PDiag(diag::warn_impcast_bool_to_null_pointer)
2818 << ToType << From->getSourceRange());
2819 else if (!isUnevaluatedContext())
2820 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2821 << ToType << From->getSourceRange();
2822 }
John McCall9320b872011-09-09 05:25:32 +00002823 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2824 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002825 QualType FromPointeeType = FromPtrType->getPointeeType(),
2826 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002827
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002828 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2829 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002830 // We must have a derived-to-base conversion. Check an
2831 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002832 unsigned InaccessibleID = 0;
2833 unsigned AmbigiousID = 0;
2834 if (Diagnose) {
2835 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2836 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2837 }
2838 if (CheckDerivedToBaseConversion(
2839 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2840 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2841 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002842 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002844 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002845 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002846 }
David Majnemer6bf02822015-10-31 08:42:14 +00002847
George Burgess IV60bc9722016-01-13 23:36:34 +00002848 if (Diagnose && !IsCStyleOrFunctionalCast &&
2849 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002850 assert(getLangOpts().MSVCCompat &&
2851 "this should only be possible with MSVCCompat!");
2852 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2853 << From->getSourceRange();
2854 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002855 }
John McCall9320b872011-09-09 05:25:32 +00002856 } else if (const ObjCObjectPointerType *ToPtrType =
2857 ToType->getAs<ObjCObjectPointerType>()) {
2858 if (const ObjCObjectPointerType *FromPtrType =
2859 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002860 // Objective-C++ conversions are always okay.
2861 // FIXME: We should have a different class of conversions for the
2862 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002863 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002864 return false;
John McCall9320b872011-09-09 05:25:32 +00002865 } else if (FromType->isBlockPointerType()) {
2866 Kind = CK_BlockPointerToObjCPointerCast;
2867 } else {
2868 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002869 }
John McCall9320b872011-09-09 05:25:32 +00002870 } else if (ToType->isBlockPointerType()) {
2871 if (!FromType->isBlockPointerType())
2872 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002873 }
John McCall8cb679e2010-11-15 09:13:47 +00002874
2875 // We shouldn't fall into this case unless it's valid for other
2876 // reasons.
2877 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2878 Kind = CK_NullToPointer;
2879
Douglas Gregor39c16d42008-10-24 04:54:22 +00002880 return false;
2881}
2882
Sebastian Redl72b597d2009-01-25 19:43:20 +00002883/// IsMemberPointerConversion - Determines whether the conversion of the
2884/// expression From, which has the (possibly adjusted) type FromType, can be
2885/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2886/// If so, returns true and places the converted type (that might differ from
2887/// ToType in its cv-qualifiers at some level) into ConvertedType.
2888bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002890 bool InOverloadResolution,
2891 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002892 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002893 if (!ToTypePtr)
2894 return false;
2895
2896 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002897 if (From->isNullPointerConstant(Context,
2898 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2899 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002900 ConvertedType = ToType;
2901 return true;
2902 }
2903
2904 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002905 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002906 if (!FromTypePtr)
2907 return false;
2908
2909 // A pointer to member of B can be converted to a pointer to member of D,
2910 // where D is derived from B (C++ 4.11p2).
2911 QualType FromClass(FromTypePtr->getClass(), 0);
2912 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002913
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002914 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002915 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002916 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2917 ToClass.getTypePtr());
2918 return true;
2919 }
2920
2921 return false;
2922}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923
Sebastian Redl72b597d2009-01-25 19:43:20 +00002924/// CheckMemberPointerConversion - Check the member pointer conversion from the
2925/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002926/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002927/// for which IsMemberPointerConversion has already returned true. It returns
2928/// true and produces a diagnostic if there was an error, or returns false
2929/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002930bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002931 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002932 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002933 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002934 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002936 if (!FromPtrType) {
2937 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002939 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002940 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002941 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002942 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002943 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002944
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002945 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002946 assert(ToPtrType && "No member pointer cast has a target type "
2947 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002948
Sebastian Redled8f2002009-01-28 18:33:18 +00002949 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2950 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002951
Sebastian Redled8f2002009-01-28 18:33:18 +00002952 // FIXME: What about dependent types?
2953 assert(FromClass->isRecordType() && "Pointer into non-class.");
2954 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002955
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002957 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002958 bool DerivationOkay =
2959 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002960 assert(DerivationOkay &&
2961 "Should not have been called if derivation isn't OK.");
2962 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002963
Sebastian Redled8f2002009-01-28 18:33:18 +00002964 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2965 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002966 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2967 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2968 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2969 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002970 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002971
Douglas Gregor89ee6822009-02-28 01:32:25 +00002972 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002973 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2974 << FromClass << ToClass << QualType(VBase, 0)
2975 << From->getSourceRange();
2976 return true;
2977 }
2978
John McCall5b0829a2010-02-10 09:31:12 +00002979 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002980 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2981 Paths.front(),
2982 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002983
Anders Carlssond7923c62009-08-22 23:33:40 +00002984 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002985 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002986 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002987 return false;
2988}
2989
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002990/// Determine whether the lifetime conversion between the two given
2991/// qualifiers sets is nontrivial.
2992static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2993 Qualifiers ToQuals) {
2994 // Converting anything to const __unsafe_unretained is trivial.
2995 if (ToQuals.hasConst() &&
2996 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2997 return false;
2998
2999 return true;
3000}
3001
Douglas Gregor9a657932008-10-21 23:43:52 +00003002/// IsQualificationConversion - Determines whether the conversion from
3003/// an rvalue of type FromType to ToType is a qualification conversion
3004/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003005///
3006/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3007/// when the qualification conversion involves a change in the Objective-C
3008/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003009bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003011 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003012 FromType = Context.getCanonicalType(FromType);
3013 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003014 ObjCLifetimeConversion = false;
3015
Douglas Gregor9a657932008-10-21 23:43:52 +00003016 // If FromType and ToType are the same type, this is not a
3017 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003018 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003019 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003020
Douglas Gregor9a657932008-10-21 23:43:52 +00003021 // (C++ 4.4p4):
3022 // A conversion can add cv-qualifiers at levels other than the first
3023 // in multi-level pointers, subject to the following rules: [...]
3024 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003025 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003026 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003027 // Within each iteration of the loop, we check the qualifiers to
3028 // determine if this still looks like a qualification
3029 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003030 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003031 // until there are no more pointers or pointers-to-members left to
3032 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003033 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003034
Douglas Gregor90609aa2011-04-25 18:40:17 +00003035 Qualifiers FromQuals = FromType.getQualifiers();
3036 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003037
3038 // Ignore __unaligned qualifier if this type is void.
3039 if (ToType.getUnqualifiedType()->isVoidType())
3040 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003041
John McCall31168b02011-06-15 23:02:42 +00003042 // Objective-C ARC:
3043 // Check Objective-C lifetime conversions.
3044 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3045 UnwrappedAnyPointer) {
3046 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003047 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3048 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003049 FromQuals.removeObjCLifetime();
3050 ToQuals.removeObjCLifetime();
3051 } else {
3052 // Qualification conversions cannot cast between different
3053 // Objective-C lifetime qualifiers.
3054 return false;
3055 }
3056 }
3057
Douglas Gregorf30053d2011-05-08 06:09:53 +00003058 // Allow addition/removal of GC attributes but not changing GC attributes.
3059 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3060 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3061 FromQuals.removeObjCGCAttr();
3062 ToQuals.removeObjCGCAttr();
3063 }
3064
Douglas Gregor9a657932008-10-21 23:43:52 +00003065 // -- for every j > 0, if const is in cv 1,j then const is in cv
3066 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003067 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003068 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003069
Douglas Gregor9a657932008-10-21 23:43:52 +00003070 // -- if the cv 1,j and cv 2,j are different, then const is in
3071 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003072 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003073 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003074 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003075
Douglas Gregor9a657932008-10-21 23:43:52 +00003076 // Keep track of whether all prior cv-qualifiers in the "to" type
3077 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003078 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003079 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003080 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003081
3082 // We are left with FromType and ToType being the pointee types
3083 // after unwrapping the original FromType and ToType the same number
3084 // of types. If we unwrapped any pointers, and if FromType and
3085 // ToType have the same unqualified type (since we checked
3086 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003087 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003088}
3089
Douglas Gregorc79862f2012-04-12 17:51:55 +00003090/// \brief - Determine whether this is a conversion from a scalar type to an
3091/// atomic type.
3092///
3093/// If successful, updates \c SCS's second and third steps in the conversion
3094/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003095static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3096 bool InOverloadResolution,
3097 StandardConversionSequence &SCS,
3098 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003099 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3100 if (!ToAtomic)
3101 return false;
3102
3103 StandardConversionSequence InnerSCS;
3104 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3105 InOverloadResolution, InnerSCS,
3106 CStyle, /*AllowObjCWritebackConversion=*/false))
3107 return false;
3108
3109 SCS.Second = InnerSCS.Second;
3110 SCS.setToType(1, InnerSCS.getToType(1));
3111 SCS.Third = InnerSCS.Third;
3112 SCS.QualificationIncludesObjCLifetime
3113 = InnerSCS.QualificationIncludesObjCLifetime;
3114 SCS.setToType(2, InnerSCS.getToType(2));
3115 return true;
3116}
3117
Sebastian Redle5417162012-03-27 18:33:03 +00003118static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3119 CXXConstructorDecl *Constructor,
3120 QualType Type) {
3121 const FunctionProtoType *CtorType =
3122 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003123 if (CtorType->getNumParams() > 0) {
3124 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003125 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3126 return true;
3127 }
3128 return false;
3129}
3130
Sebastian Redl82ace982012-02-11 23:51:08 +00003131static OverloadingResult
3132IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3133 CXXRecordDecl *To,
3134 UserDefinedConversionSequence &User,
3135 OverloadCandidateSet &CandidateSet,
3136 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003137 for (auto *D : S.LookupConstructors(To)) {
3138 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003139 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003140 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003141
Richard Smithc2bebe92016-05-11 20:37:46 +00003142 bool Usable = !Info.Constructor->isInvalidDecl() &&
3143 S.isInitListConstructor(Info.Constructor) &&
3144 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003145 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003146 // If the first argument is (a reference to) the target type,
3147 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003148 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3149 S.Context, Info.Constructor, ToType);
3150 if (Info.ConstructorTmpl)
3151 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3152 /*ExplicitArgs*/ nullptr, From,
3153 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003154 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003155 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3156 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003157 }
3158 }
3159
3160 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3161
3162 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003163 switch (auto Result =
3164 CandidateSet.BestViableFunction(S, From->getLocStart(),
3165 Best, true)) {
3166 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003167 case OR_Success: {
3168 // Record the standard conversion we used and the conversion function.
3169 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003170 QualType ThisType = Constructor->getThisType(S.Context);
3171 // Initializer lists don't have conversions as such.
3172 User.Before.setAsIdentityConversion();
3173 User.HadMultipleCandidates = HadMultipleCandidates;
3174 User.ConversionFunction = Constructor;
3175 User.FoundConversionFunction = Best->FoundDecl;
3176 User.After.setAsIdentityConversion();
3177 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3178 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003179 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003180 }
3181
3182 case OR_No_Viable_Function:
3183 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003184 case OR_Ambiguous:
3185 return OR_Ambiguous;
3186 }
3187
3188 llvm_unreachable("Invalid OverloadResult!");
3189}
3190
Douglas Gregor576e98c2009-01-30 23:27:23 +00003191/// Determines whether there is a user-defined conversion sequence
3192/// (C++ [over.ics.user]) that converts expression From to the type
3193/// ToType. If such a conversion exists, User will contain the
3194/// user-defined conversion sequence that performs such a conversion
3195/// and this routine will return true. Otherwise, this routine returns
3196/// false and User is unspecified.
3197///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003198/// \param AllowExplicit true if the conversion should consider C++0x
3199/// "explicit" conversion functions as well as non-explicit conversion
3200/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003201///
3202/// \param AllowObjCConversionOnExplicit true if the conversion should
3203/// allow an extra Objective-C pointer conversion on uses of explicit
3204/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003205static OverloadingResult
3206IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003207 UserDefinedConversionSequence &User,
3208 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003209 bool AllowExplicit,
3210 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003211 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003212
Douglas Gregor5ab11652010-04-17 22:01:05 +00003213 // Whether we will only visit constructors.
3214 bool ConstructorsOnly = false;
3215
3216 // If the type we are conversion to is a class type, enumerate its
3217 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003218 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003219 // C++ [over.match.ctor]p1:
3220 // When objects of class type are direct-initialized (8.5), or
3221 // copy-initialized from an expression of the same or a
3222 // derived class type (8.5), overload resolution selects the
3223 // constructor. [...] For copy-initialization, the candidate
3224 // functions are all the converting constructors (12.3.1) of
3225 // that class. The argument list is the expression-list within
3226 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003227 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003228 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003229 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003230 ConstructorsOnly = true;
3231
Richard Smithdb0ac552015-12-18 22:40:25 +00003232 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003233 // We're not going to find any constructors.
3234 } else if (CXXRecordDecl *ToRecordDecl
3235 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003236
3237 Expr **Args = &From;
3238 unsigned NumArgs = 1;
3239 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003240 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003241 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003242 OverloadingResult Result = IsInitializerListConstructorConversion(
3243 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3244 if (Result != OR_No_Viable_Function)
3245 return Result;
3246 // Never mind.
3247 CandidateSet.clear();
3248
3249 // If we're list-initializing, we pass the individual elements as
3250 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003251 Args = InitList->getInits();
3252 NumArgs = InitList->getNumInits();
3253 ListInitializing = true;
3254 }
3255
Richard Smithc2bebe92016-05-11 20:37:46 +00003256 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3257 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003258 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003259 continue;
John McCalla0296f72010-03-19 07:35:19 +00003260
Richard Smithc2bebe92016-05-11 20:37:46 +00003261 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003262 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003263 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003264 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003265 Usable = Usable &&
3266 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003267 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003268 bool SuppressUserConversions = !ConstructorsOnly;
3269 if (SuppressUserConversions && ListInitializing) {
3270 SuppressUserConversions = false;
3271 if (NumArgs == 1) {
3272 // If the first argument is (a reference to) the target type,
3273 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003274 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003275 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003276 }
3277 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003278 if (Info.ConstructorTmpl)
3279 S.AddTemplateOverloadCandidate(
3280 Info.ConstructorTmpl, Info.FoundDecl,
3281 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3282 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003283 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003284 // Allow one user-defined conversion when user specifies a
3285 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003286 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003287 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003288 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003289 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003290 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003291 }
3292 }
3293
Douglas Gregor5ab11652010-04-17 22:01:05 +00003294 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003295 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003296 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003297 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003298 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003299 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003300 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003301 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3302 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003303 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3304 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003305 DeclAccessPair FoundDecl = I.getPair();
3306 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003307 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3308 if (isa<UsingShadowDecl>(D))
3309 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3310
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003311 CXXConversionDecl *Conv;
3312 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003313 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3314 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003315 else
John McCallda4458e2010-03-31 01:36:47 +00003316 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003317
3318 if (AllowExplicit || !Conv->isExplicit()) {
3319 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003320 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3321 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003322 CandidateSet,
3323 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003324 else
John McCall5c32be02010-08-24 20:38:10 +00003325 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003326 From, ToType, CandidateSet,
3327 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003328 }
3329 }
3330 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003331 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003332
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003333 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3334
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003335 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003336 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3337 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003338 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003339 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003340 // Record the standard conversion we used and the conversion function.
3341 if (CXXConstructorDecl *Constructor
3342 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3343 // C++ [over.ics.user]p1:
3344 // If the user-defined conversion is specified by a
3345 // constructor (12.3.1), the initial standard conversion
3346 // sequence converts the source type to the type required by
3347 // the argument of the constructor.
3348 //
3349 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003350 if (isa<InitListExpr>(From)) {
3351 // Initializer lists don't have conversions as such.
3352 User.Before.setAsIdentityConversion();
3353 } else {
3354 if (Best->Conversions[0].isEllipsis())
3355 User.EllipsisConversion = true;
3356 else {
3357 User.Before = Best->Conversions[0].Standard;
3358 User.EllipsisConversion = false;
3359 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003360 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003361 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003362 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003363 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003364 User.After.setAsIdentityConversion();
3365 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3366 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003367 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003368 }
3369 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003370 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3371 // C++ [over.ics.user]p1:
3372 //
3373 // [...] If the user-defined conversion is specified by a
3374 // conversion function (12.3.2), the initial standard
3375 // conversion sequence converts the source type to the
3376 // implicit object parameter of the conversion function.
3377 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003378 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003379 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003380 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003381 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003382
John McCall5c32be02010-08-24 20:38:10 +00003383 // C++ [over.ics.user]p2:
3384 // The second standard conversion sequence converts the
3385 // result of the user-defined conversion to the target type
3386 // for the sequence. Since an implicit conversion sequence
3387 // is an initialization, the special rules for
3388 // initialization by user-defined conversion apply when
3389 // selecting the best user-defined conversion for a
3390 // user-defined conversion sequence (see 13.3.3 and
3391 // 13.3.3.1).
3392 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003393 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003394 }
David Blaikie8a40f702012-01-17 06:56:22 +00003395 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003396
John McCall5c32be02010-08-24 20:38:10 +00003397 case OR_No_Viable_Function:
3398 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
John McCall5c32be02010-08-24 20:38:10 +00003400 case OR_Ambiguous:
3401 return OR_Ambiguous;
3402 }
3403
David Blaikie8a40f702012-01-17 06:56:22 +00003404 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003405}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003407bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003408Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003409 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003410 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3411 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003413 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003414 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003415 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003416 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3417 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003418 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003419 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003420 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003421 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003422 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003423 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003424 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003425 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003428}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003429
Douglas Gregor2837aa22012-02-22 17:32:19 +00003430/// \brief Compare the user-defined conversion functions or constructors
3431/// of two user-defined conversion sequences to determine whether any ordering
3432/// is possible.
3433static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003434compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003435 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003436 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003437 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003438
Douglas Gregor2837aa22012-02-22 17:32:19 +00003439 // Objective-C++:
3440 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003441 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003442 // respectively, always prefer the conversion to a function pointer,
3443 // because the function pointer is more lightweight and is more likely
3444 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003445 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003446 if (!Conv1)
3447 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003448
Douglas Gregor2837aa22012-02-22 17:32:19 +00003449 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3450 if (!Conv2)
3451 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003452
Douglas Gregor2837aa22012-02-22 17:32:19 +00003453 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3454 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3455 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3456 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003457 return Block1 ? ImplicitConversionSequence::Worse
3458 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003459 }
3460
3461 return ImplicitConversionSequence::Indistinguishable;
3462}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003463
3464static bool hasDeprecatedStringLiteralToCharPtrConversion(
3465 const ImplicitConversionSequence &ICS) {
3466 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3467 (ICS.isUserDefined() &&
3468 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3469}
3470
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003471/// CompareImplicitConversionSequences - Compare two implicit
3472/// conversion sequences to determine whether one is better than the
3473/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003474static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003475CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003476 const ImplicitConversionSequence& ICS1,
3477 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003478{
3479 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3480 // conversion sequences (as defined in 13.3.3.1)
3481 // -- a standard conversion sequence (13.3.3.1.1) is a better
3482 // conversion sequence than a user-defined conversion sequence or
3483 // an ellipsis conversion sequence, and
3484 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3485 // conversion sequence than an ellipsis conversion sequence
3486 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003487 //
John McCall0d1da222010-01-12 00:44:57 +00003488 // C++0x [over.best.ics]p10:
3489 // For the purpose of ranking implicit conversion sequences as
3490 // described in 13.3.3.2, the ambiguous conversion sequence is
3491 // treated as a user-defined sequence that is indistinguishable
3492 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003493
3494 // String literal to 'char *' conversion has been deprecated in C++03. It has
3495 // been removed from C++11. We still accept this conversion, if it happens at
3496 // the best viable function. Otherwise, this conversion is considered worse
3497 // than ellipsis conversion. Consider this as an extension; this is not in the
3498 // standard. For example:
3499 //
3500 // int &f(...); // #1
3501 // void f(char*); // #2
3502 // void g() { int &r = f("foo"); }
3503 //
3504 // In C++03, we pick #2 as the best viable function.
3505 // In C++11, we pick #1 as the best viable function, because ellipsis
3506 // conversion is better than string-literal to char* conversion (since there
3507 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3508 // convert arguments, #2 would be the best viable function in C++11.
3509 // If the best viable function has this conversion, a warning will be issued
3510 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3511
3512 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3513 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3514 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3515 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3516 ? ImplicitConversionSequence::Worse
3517 : ImplicitConversionSequence::Better;
3518
Douglas Gregor5ab11652010-04-17 22:01:05 +00003519 if (ICS1.getKindRank() < ICS2.getKindRank())
3520 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003521 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003522 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003523
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003524 // The following checks require both conversion sequences to be of
3525 // the same kind.
3526 if (ICS1.getKind() != ICS2.getKind())
3527 return ImplicitConversionSequence::Indistinguishable;
3528
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003529 ImplicitConversionSequence::CompareKind Result =
3530 ImplicitConversionSequence::Indistinguishable;
3531
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003532 // Two implicit conversion sequences of the same form are
3533 // indistinguishable conversion sequences unless one of the
3534 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003535
3536 // List-initialization sequence L1 is a better conversion sequence than
3537 // list-initialization sequence L2 if:
3538 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3539 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003540 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003541 // and N1 is smaller than N2.,
3542 // even if one of the other rules in this paragraph would otherwise apply.
3543 if (!ICS1.isBad()) {
3544 if (ICS1.isStdInitializerListElement() &&
3545 !ICS2.isStdInitializerListElement())
3546 return ImplicitConversionSequence::Better;
3547 if (!ICS1.isStdInitializerListElement() &&
3548 ICS2.isStdInitializerListElement())
3549 return ImplicitConversionSequence::Worse;
3550 }
3551
John McCall0d1da222010-01-12 00:44:57 +00003552 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003553 // Standard conversion sequence S1 is a better conversion sequence than
3554 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003555 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003556 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003557 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003558 // User-defined conversion sequence U1 is a better conversion
3559 // sequence than another user-defined conversion sequence U2 if
3560 // they contain the same user-defined conversion function or
3561 // constructor and if the second standard conversion sequence of
3562 // U1 is better than the second standard conversion sequence of
3563 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003564 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003565 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003566 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003567 ICS1.UserDefined.After,
3568 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003569 else
3570 Result = compareConversionFunctions(S,
3571 ICS1.UserDefined.ConversionFunction,
3572 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003573 }
3574
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003575 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003576}
3577
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003578static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3579 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3580 Qualifiers Quals;
3581 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003585 return Context.hasSameUnqualifiedType(T1, T2);
3586}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003588// Per 13.3.3.2p3, compare the given standard conversion sequences to
3589// determine if one is a proper subset of the other.
3590static ImplicitConversionSequence::CompareKind
3591compareStandardConversionSubsets(ASTContext &Context,
3592 const StandardConversionSequence& SCS1,
3593 const StandardConversionSequence& SCS2) {
3594 ImplicitConversionSequence::CompareKind Result
3595 = ImplicitConversionSequence::Indistinguishable;
3596
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003598 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003599 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3600 return ImplicitConversionSequence::Better;
3601 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3602 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003604 if (SCS1.Second != SCS2.Second) {
3605 if (SCS1.Second == ICK_Identity)
3606 Result = ImplicitConversionSequence::Better;
3607 else if (SCS2.Second == ICK_Identity)
3608 Result = ImplicitConversionSequence::Worse;
3609 else
3610 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003611 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003612 return ImplicitConversionSequence::Indistinguishable;
3613
3614 if (SCS1.Third == SCS2.Third) {
3615 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3616 : ImplicitConversionSequence::Indistinguishable;
3617 }
3618
3619 if (SCS1.Third == ICK_Identity)
3620 return Result == ImplicitConversionSequence::Worse
3621 ? ImplicitConversionSequence::Indistinguishable
3622 : ImplicitConversionSequence::Better;
3623
3624 if (SCS2.Third == ICK_Identity)
3625 return Result == ImplicitConversionSequence::Better
3626 ? ImplicitConversionSequence::Indistinguishable
3627 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003629 return ImplicitConversionSequence::Indistinguishable;
3630}
3631
Douglas Gregore696ebb2011-01-26 14:52:12 +00003632/// \brief Determine whether one of the given reference bindings is better
3633/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003634static bool
3635isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3636 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003637 // C++0x [over.ics.rank]p3b4:
3638 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3639 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003641 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003643 // reference*.
3644 //
3645 // FIXME: Rvalue references. We're going rogue with the above edits,
3646 // because the semantics in the current C++0x working paper (N3225 at the
3647 // time of this writing) break the standard definition of std::forward
3648 // and std::reference_wrapper when dealing with references to functions.
3649 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003650 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3651 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3652 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
Douglas Gregore696ebb2011-01-26 14:52:12 +00003654 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3655 SCS2.IsLvalueReference) ||
3656 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003657 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003658}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003660/// CompareStandardConversionSequences - Compare two standard
3661/// conversion sequences to determine whether one is better than the
3662/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003663static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003664CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003665 const StandardConversionSequence& SCS1,
3666 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003667{
3668 // Standard conversion sequence S1 is a better conversion sequence
3669 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3670
3671 // -- S1 is a proper subsequence of S2 (comparing the conversion
3672 // sequences in the canonical form defined by 13.3.3.1.1,
3673 // excluding any Lvalue Transformation; the identity conversion
3674 // sequence is considered to be a subsequence of any
3675 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003676 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003677 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003678 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003679
3680 // -- the rank of S1 is better than the rank of S2 (by the rules
3681 // defined below), or, if not that,
3682 ImplicitConversionRank Rank1 = SCS1.getRank();
3683 ImplicitConversionRank Rank2 = SCS2.getRank();
3684 if (Rank1 < Rank2)
3685 return ImplicitConversionSequence::Better;
3686 else if (Rank2 < Rank1)
3687 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003688
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003689 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3690 // are indistinguishable unless one of the following rules
3691 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003693 // A conversion that is not a conversion of a pointer, or
3694 // pointer to member, to bool is better than another conversion
3695 // that is such a conversion.
3696 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3697 return SCS2.isPointerConversionToBool()
3698 ? ImplicitConversionSequence::Better
3699 : ImplicitConversionSequence::Worse;
3700
Douglas Gregor5c407d92008-10-23 00:40:37 +00003701 // C++ [over.ics.rank]p4b2:
3702 //
3703 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003704 // conversion of B* to A* is better than conversion of B* to
3705 // void*, and conversion of A* to void* is better than conversion
3706 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003707 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003708 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003709 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003710 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003711 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3712 // Exactly one of the conversion sequences is a conversion to
3713 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003714 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3715 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003716 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3717 // Neither conversion sequence converts to a void pointer; compare
3718 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003719 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003720 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003721 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003722 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3723 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003724 // Both conversion sequences are conversions to void
3725 // pointers. Compare the source types to determine if there's an
3726 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003727 QualType FromType1 = SCS1.getFromType();
3728 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003729
3730 // Adjust the types we're converting from via the array-to-pointer
3731 // conversion, if we need to.
3732 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003733 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003734 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003735 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003736
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003737 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3738 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003739
Richard Smith0f59cb32015-12-18 21:45:41 +00003740 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003741 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003742 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003743 return ImplicitConversionSequence::Worse;
3744
3745 // Objective-C++: If one interface is more specific than the
3746 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003747 const ObjCObjectPointerType* FromObjCPtr1
3748 = FromType1->getAs<ObjCObjectPointerType>();
3749 const ObjCObjectPointerType* FromObjCPtr2
3750 = FromType2->getAs<ObjCObjectPointerType>();
3751 if (FromObjCPtr1 && FromObjCPtr2) {
3752 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3753 FromObjCPtr2);
3754 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3755 FromObjCPtr1);
3756 if (AssignLeft != AssignRight) {
3757 return AssignLeft? ImplicitConversionSequence::Better
3758 : ImplicitConversionSequence::Worse;
3759 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003760 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003761 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003762
3763 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3764 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003765 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003766 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003767 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003768
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003769 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003770 // Check for a better reference binding based on the kind of bindings.
3771 if (isBetterReferenceBindingKind(SCS1, SCS2))
3772 return ImplicitConversionSequence::Better;
3773 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3774 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775
Sebastian Redlb28b4072009-03-22 23:49:27 +00003776 // C++ [over.ics.rank]p3b4:
3777 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3778 // which the references refer are the same type except for
3779 // top-level cv-qualifiers, and the type to which the reference
3780 // initialized by S2 refers is more cv-qualified than the type
3781 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003782 QualType T1 = SCS1.getToType(2);
3783 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003784 T1 = S.Context.getCanonicalType(T1);
3785 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003786 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003787 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3788 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003789 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003790 // Objective-C++ ARC: If the references refer to objects with different
3791 // lifetimes, prefer bindings that don't change lifetime.
3792 if (SCS1.ObjCLifetimeConversionBinding !=
3793 SCS2.ObjCLifetimeConversionBinding) {
3794 return SCS1.ObjCLifetimeConversionBinding
3795 ? ImplicitConversionSequence::Worse
3796 : ImplicitConversionSequence::Better;
3797 }
3798
Chandler Carruth8e543b32010-12-12 08:17:55 +00003799 // If the type is an array type, promote the element qualifiers to the
3800 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003801 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003802 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003803 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003804 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003805 if (T2.isMoreQualifiedThan(T1))
3806 return ImplicitConversionSequence::Better;
3807 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003808 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809 }
3810 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003811
Francois Pichet08d2fa02011-09-18 21:37:37 +00003812 // In Microsoft mode, prefer an integral conversion to a
3813 // floating-to-integral conversion if the integral conversion
3814 // is between types of the same size.
3815 // For example:
3816 // void f(float);
3817 // void f(int);
3818 // int main {
3819 // long a;
3820 // f(a);
3821 // }
3822 // Here, MSVC will call f(int) instead of generating a compile error
3823 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003824 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3825 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003826 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003827 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003828 return ImplicitConversionSequence::Better;
3829
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003830 return ImplicitConversionSequence::Indistinguishable;
3831}
3832
3833/// CompareQualificationConversions - Compares two standard conversion
3834/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003835/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003836static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003837CompareQualificationConversions(Sema &S,
3838 const StandardConversionSequence& SCS1,
3839 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003840 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003841 // -- S1 and S2 differ only in their qualification conversion and
3842 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3843 // cv-qualification signature of type T1 is a proper subset of
3844 // the cv-qualification signature of type T2, and S1 is not the
3845 // deprecated string literal array-to-pointer conversion (4.2).
3846 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3847 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3848 return ImplicitConversionSequence::Indistinguishable;
3849
3850 // FIXME: the example in the standard doesn't use a qualification
3851 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003852 QualType T1 = SCS1.getToType(2);
3853 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003854 T1 = S.Context.getCanonicalType(T1);
3855 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003856 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003857 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3858 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003859
3860 // If the types are the same, we won't learn anything by unwrapped
3861 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003862 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003863 return ImplicitConversionSequence::Indistinguishable;
3864
Chandler Carruth607f38e2009-12-29 07:16:59 +00003865 // If the type is an array type, promote the element qualifiers to the type
3866 // for comparison.
3867 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003868 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003869 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003870 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003871
Mike Stump11289f42009-09-09 15:08:12 +00003872 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003873 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003874
3875 // Objective-C++ ARC:
3876 // Prefer qualification conversions not involving a change in lifetime
3877 // to qualification conversions that do not change lifetime.
3878 if (SCS1.QualificationIncludesObjCLifetime !=
3879 SCS2.QualificationIncludesObjCLifetime) {
3880 Result = SCS1.QualificationIncludesObjCLifetime
3881 ? ImplicitConversionSequence::Worse
3882 : ImplicitConversionSequence::Better;
3883 }
3884
John McCall5c32be02010-08-24 20:38:10 +00003885 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003886 // Within each iteration of the loop, we check the qualifiers to
3887 // determine if this still looks like a qualification
3888 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003889 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003890 // until there are no more pointers or pointers-to-members left
3891 // to unwrap. This essentially mimics what
3892 // IsQualificationConversion does, but here we're checking for a
3893 // strict subset of qualifiers.
3894 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3895 // The qualifiers are the same, so this doesn't tell us anything
3896 // about how the sequences rank.
3897 ;
3898 else if (T2.isMoreQualifiedThan(T1)) {
3899 // T1 has fewer qualifiers, so it could be the better sequence.
3900 if (Result == ImplicitConversionSequence::Worse)
3901 // Neither has qualifiers that are a subset of the other's
3902 // qualifiers.
3903 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003904
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003905 Result = ImplicitConversionSequence::Better;
3906 } else if (T1.isMoreQualifiedThan(T2)) {
3907 // T2 has fewer qualifiers, so it could be the better sequence.
3908 if (Result == ImplicitConversionSequence::Better)
3909 // Neither has qualifiers that are a subset of the other's
3910 // qualifiers.
3911 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003912
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003913 Result = ImplicitConversionSequence::Worse;
3914 } else {
3915 // Qualifiers are disjoint.
3916 return ImplicitConversionSequence::Indistinguishable;
3917 }
3918
3919 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003920 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003921 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003922 }
3923
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003924 // Check that the winning standard conversion sequence isn't using
3925 // the deprecated string literal array to pointer conversion.
3926 switch (Result) {
3927 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003928 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003929 Result = ImplicitConversionSequence::Indistinguishable;
3930 break;
3931
3932 case ImplicitConversionSequence::Indistinguishable:
3933 break;
3934
3935 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003936 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003937 Result = ImplicitConversionSequence::Indistinguishable;
3938 break;
3939 }
3940
3941 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003942}
3943
Douglas Gregor5c407d92008-10-23 00:40:37 +00003944/// CompareDerivedToBaseConversions - Compares two standard conversion
3945/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003946/// various kinds of derived-to-base conversions (C++
3947/// [over.ics.rank]p4b3). As part of these checks, we also look at
3948/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003949static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003950CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003951 const StandardConversionSequence& SCS1,
3952 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003953 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003954 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003955 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003956 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003957
3958 // Adjust the types we're converting from via the array-to-pointer
3959 // conversion, if we need to.
3960 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003961 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003962 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003963 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003964
3965 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003966 FromType1 = S.Context.getCanonicalType(FromType1);
3967 ToType1 = S.Context.getCanonicalType(ToType1);
3968 FromType2 = S.Context.getCanonicalType(FromType2);
3969 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003970
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003971 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003972 //
3973 // If class B is derived directly or indirectly from class A and
3974 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003975 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003976 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003977 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003978 SCS2.Second == ICK_Pointer_Conversion &&
3979 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3980 FromType1->isPointerType() && FromType2->isPointerType() &&
3981 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003982 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003983 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003984 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003985 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003986 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003987 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003988 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003989 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003990
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003991 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003992 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003993 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003994 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003995 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003996 return ImplicitConversionSequence::Worse;
3997 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003998
3999 // -- conversion of B* to A* is better than conversion of C* to A*,
4000 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004001 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004002 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004003 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004004 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004005 }
4006 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4007 SCS2.Second == ICK_Pointer_Conversion) {
4008 const ObjCObjectPointerType *FromPtr1
4009 = FromType1->getAs<ObjCObjectPointerType>();
4010 const ObjCObjectPointerType *FromPtr2
4011 = FromType2->getAs<ObjCObjectPointerType>();
4012 const ObjCObjectPointerType *ToPtr1
4013 = ToType1->getAs<ObjCObjectPointerType>();
4014 const ObjCObjectPointerType *ToPtr2
4015 = ToType2->getAs<ObjCObjectPointerType>();
4016
4017 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4018 // Apply the same conversion ranking rules for Objective-C pointer types
4019 // that we do for C++ pointers to class types. However, we employ the
4020 // Objective-C pseudo-subtyping relationship used for assignment of
4021 // Objective-C pointer types.
4022 bool FromAssignLeft
4023 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4024 bool FromAssignRight
4025 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4026 bool ToAssignLeft
4027 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4028 bool ToAssignRight
4029 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4030
4031 // A conversion to an a non-id object pointer type or qualified 'id'
4032 // type is better than a conversion to 'id'.
4033 if (ToPtr1->isObjCIdType() &&
4034 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4035 return ImplicitConversionSequence::Worse;
4036 if (ToPtr2->isObjCIdType() &&
4037 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4038 return ImplicitConversionSequence::Better;
4039
4040 // A conversion to a non-id object pointer type is better than a
4041 // conversion to a qualified 'id' type
4042 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4043 return ImplicitConversionSequence::Worse;
4044 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4045 return ImplicitConversionSequence::Better;
4046
4047 // A conversion to an a non-Class object pointer type or qualified 'Class'
4048 // type is better than a conversion to 'Class'.
4049 if (ToPtr1->isObjCClassType() &&
4050 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4051 return ImplicitConversionSequence::Worse;
4052 if (ToPtr2->isObjCClassType() &&
4053 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4054 return ImplicitConversionSequence::Better;
4055
4056 // A conversion to a non-Class object pointer type is better than a
4057 // conversion to a qualified 'Class' type.
4058 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4059 return ImplicitConversionSequence::Worse;
4060 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4061 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004062
Douglas Gregor058d3de2011-01-31 18:51:41 +00004063 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4064 if (S.Context.hasSameType(FromType1, FromType2) &&
4065 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4066 (ToAssignLeft != ToAssignRight))
4067 return ToAssignLeft? ImplicitConversionSequence::Worse
4068 : ImplicitConversionSequence::Better;
4069
4070 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4071 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4072 (FromAssignLeft != FromAssignRight))
4073 return FromAssignLeft? ImplicitConversionSequence::Better
4074 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004075 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004076 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004077
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004078 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004079 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4080 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4081 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004083 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004085 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004087 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004089 ToType2->getAs<MemberPointerType>();
4090 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4091 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4092 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4093 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4094 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4095 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4096 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4097 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004098 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004099 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004100 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004101 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004102 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004103 return ImplicitConversionSequence::Better;
4104 }
4105 // conversion of B::* to C::* is better than conversion of A::* to C::*
4106 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004107 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004108 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004109 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004110 return ImplicitConversionSequence::Worse;
4111 }
4112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113
Douglas Gregor5ab11652010-04-17 22:01:05 +00004114 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004115 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004116 // -- binding of an expression of type C to a reference of type
4117 // B& is better than binding an expression of type C to a
4118 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004119 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4120 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004121 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004122 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004123 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004124 return ImplicitConversionSequence::Worse;
4125 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004126
Douglas Gregor2fe98832008-11-03 19:09:14 +00004127 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004128 // -- binding of an expression of type B to a reference of type
4129 // A& is better than binding an expression of type C to a
4130 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004131 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4132 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004133 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004134 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004135 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004136 return ImplicitConversionSequence::Worse;
4137 }
4138 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004139
Douglas Gregor5c407d92008-10-23 00:40:37 +00004140 return ImplicitConversionSequence::Indistinguishable;
4141}
4142
Douglas Gregor45bb4832013-03-26 23:36:30 +00004143/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4144/// C++ class.
4145static bool isTypeValid(QualType T) {
4146 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4147 return !Record->isInvalidDecl();
4148
4149 return true;
4150}
4151
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004152/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4153/// determine whether they are reference-related,
4154/// reference-compatible, reference-compatible with added
4155/// qualification, or incompatible, for use in C++ initialization by
4156/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4157/// type, and the first type (T1) is the pointee type of the reference
4158/// type being initialized.
4159Sema::ReferenceCompareResult
4160Sema::CompareReferenceRelationship(SourceLocation Loc,
4161 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004162 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004163 bool &ObjCConversion,
4164 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004165 assert(!OrigT1->isReferenceType() &&
4166 "T1 must be the pointee type of the reference type");
4167 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4168
4169 QualType T1 = Context.getCanonicalType(OrigT1);
4170 QualType T2 = Context.getCanonicalType(OrigT2);
4171 Qualifiers T1Quals, T2Quals;
4172 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4173 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4174
4175 // C++ [dcl.init.ref]p4:
4176 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4177 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4178 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004179 DerivedToBase = false;
4180 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004181 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004182 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004183 if (UnqualT1 == UnqualT2) {
4184 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004185 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004186 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004187 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004188 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004189 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4190 UnqualT2->isObjCObjectOrInterfaceType() &&
4191 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4192 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004193 else if (UnqualT2->isFunctionType() &&
4194 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4195 // C++1z [dcl.init.ref]p4:
4196 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4197 // function" and T1 is "function"
4198 //
4199 // We extend this to also apply to 'noreturn', so allow any function
4200 // conversion between function types.
4201 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004202 else
4203 return Ref_Incompatible;
4204
4205 // At this point, we know that T1 and T2 are reference-related (at
4206 // least).
4207
4208 // If the type is an array type, promote the element qualifiers to the type
4209 // for comparison.
4210 if (isa<ArrayType>(T1) && T1Quals)
4211 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4212 if (isa<ArrayType>(T2) && T2Quals)
4213 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4214
4215 // C++ [dcl.init.ref]p4:
4216 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4217 // reference-related to T2 and cv1 is the same cv-qualification
4218 // as, or greater cv-qualification than, cv2. For purposes of
4219 // overload resolution, cases for which cv1 is greater
4220 // cv-qualification than cv2 are identified as
4221 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004222 //
4223 // Note that we also require equivalence of Objective-C GC and address-space
4224 // qualifiers when performing these computations, so that e.g., an int in
4225 // address space 1 is not reference-compatible with an int in address
4226 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004227 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4228 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004229 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4230 ObjCLifetimeConversion = true;
4231
John McCall31168b02011-06-15 23:02:42 +00004232 T1Quals.removeObjCLifetime();
4233 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004234 }
4235
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004236 // MS compiler ignores __unaligned qualifier for references; do the same.
4237 T1Quals.removeUnaligned();
4238 T2Quals.removeUnaligned();
4239
Richard Smithce766292016-10-21 23:01:55 +00004240 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004241 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004242 else
4243 return Ref_Related;
4244}
4245
Douglas Gregor836a7e82010-08-11 02:15:33 +00004246/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004247/// with DeclType. Return true if something definite is found.
4248static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004249FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4250 QualType DeclType, SourceLocation DeclLoc,
4251 Expr *Init, QualType T2, bool AllowRvalues,
4252 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 assert(T2->isRecordType() && "Can only find conversions of record types.");
4254 CXXRecordDecl *T2RecordDecl
4255 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4256
Richard Smith100b24a2014-04-17 01:52:14 +00004257 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004258 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4259 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004260 NamedDecl *D = *I;
4261 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4262 if (isa<UsingShadowDecl>(D))
4263 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4264
4265 FunctionTemplateDecl *ConvTemplate
4266 = dyn_cast<FunctionTemplateDecl>(D);
4267 CXXConversionDecl *Conv;
4268 if (ConvTemplate)
4269 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4270 else
4271 Conv = cast<CXXConversionDecl>(D);
4272
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004274 // explicit conversions, skip it.
4275 if (!AllowExplicit && Conv->isExplicit())
4276 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Douglas Gregor836a7e82010-08-11 02:15:33 +00004278 if (AllowRvalues) {
4279 bool DerivedToBase = false;
4280 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004281 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004282
4283 // If we are initializing an rvalue reference, don't permit conversion
4284 // functions that return lvalues.
4285 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4286 const ReferenceType *RefType
4287 = Conv->getConversionType()->getAs<LValueReferenceType>();
4288 if (RefType && !RefType->getPointeeType()->isFunctionType())
4289 continue;
4290 }
4291
Douglas Gregor836a7e82010-08-11 02:15:33 +00004292 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004293 S.CompareReferenceRelationship(
4294 DeclLoc,
4295 Conv->getConversionType().getNonReferenceType()
4296 .getUnqualifiedType(),
4297 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004298 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004299 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004300 continue;
4301 } else {
4302 // If the conversion function doesn't return a reference type,
4303 // it can't be considered for this conversion. An rvalue reference
4304 // is only acceptable if its referencee is a function type.
4305
4306 const ReferenceType *RefType =
4307 Conv->getConversionType()->getAs<ReferenceType>();
4308 if (!RefType ||
4309 (!RefType->isLValueReferenceType() &&
4310 !RefType->getPointeeType()->isFunctionType()))
4311 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor836a7e82010-08-11 02:15:33 +00004314 if (ConvTemplate)
4315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004316 Init, DeclType, CandidateSet,
4317 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004318 else
4319 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004320 DeclType, CandidateSet,
4321 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004322 }
4323
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004324 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4325
Sebastian Redld92badf2010-06-30 18:13:39 +00004326 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004327 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004328 case OR_Success:
4329 // C++ [over.ics.ref]p1:
4330 //
4331 // [...] If the parameter binds directly to the result of
4332 // applying a conversion function to the argument
4333 // expression, the implicit conversion sequence is a
4334 // user-defined conversion sequence (13.3.3.1.2), with the
4335 // second standard conversion sequence either an identity
4336 // conversion or, if the conversion function returns an
4337 // entity of a type that is a derived class of the parameter
4338 // type, a derived-to-base Conversion.
4339 if (!Best->FinalConversion.DirectBinding)
4340 return false;
4341
4342 ICS.setUserDefined();
4343 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4344 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004345 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004346 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004347 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 ICS.UserDefined.EllipsisConversion = false;
4349 assert(ICS.UserDefined.After.ReferenceBinding &&
4350 ICS.UserDefined.After.DirectBinding &&
4351 "Expected a direct reference binding!");
4352 return true;
4353
4354 case OR_Ambiguous:
4355 ICS.setAmbiguous();
4356 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4357 Cand != CandidateSet.end(); ++Cand)
4358 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004359 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004360 return true;
4361
4362 case OR_No_Viable_Function:
4363 case OR_Deleted:
4364 // There was no suitable conversion, or we found a deleted
4365 // conversion; continue with other checks.
4366 return false;
4367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
David Blaikie8a40f702012-01-17 06:56:22 +00004369 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004370}
4371
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004372/// \brief Compute an implicit conversion sequence for reference
4373/// initialization.
4374static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004375TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004376 SourceLocation DeclLoc,
4377 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004378 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004379 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4380
4381 // Most paths end in a failed conversion.
4382 ImplicitConversionSequence ICS;
4383 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4384
4385 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4386 QualType T2 = Init->getType();
4387
4388 // If the initializer is the address of an overloaded function, try
4389 // to resolve the overloaded function. If all goes well, T2 is the
4390 // type of the resulting function.
4391 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4392 DeclAccessPair Found;
4393 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4394 false, Found))
4395 T2 = Fn->getType();
4396 }
4397
4398 // Compute some basic properties of the types and the initializer.
4399 bool isRValRef = DeclType->isRValueReferenceType();
4400 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004401 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004402 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004403 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004404 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004405 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004406 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004407
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004408
Sebastian Redld92badf2010-06-30 18:13:39 +00004409 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004410 // A reference to type "cv1 T1" is initialized by an expression
4411 // of type "cv2 T2" as follows:
4412
Sebastian Redld92badf2010-06-30 18:13:39 +00004413 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004414 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004415 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4416 // reference-compatible with "cv2 T2," or
4417 //
4418 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004419 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004420 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004421 // When a parameter of reference type binds directly (8.5.3)
4422 // to an argument expression, the implicit conversion sequence
4423 // is the identity conversion, unless the argument expression
4424 // has a type that is a derived class of the parameter type,
4425 // in which case the implicit conversion sequence is a
4426 // derived-to-base Conversion (13.3.3.1).
4427 ICS.setStandard();
4428 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004429 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4430 : ObjCConversion? ICK_Compatible_Conversion
4431 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004432 ICS.Standard.Third = ICK_Identity;
4433 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4434 ICS.Standard.setToType(0, T2);
4435 ICS.Standard.setToType(1, T1);
4436 ICS.Standard.setToType(2, T1);
4437 ICS.Standard.ReferenceBinding = true;
4438 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004439 ICS.Standard.IsLvalueReference = !isRValRef;
4440 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4441 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004442 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004443 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004445 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004446
Sebastian Redld92badf2010-06-30 18:13:39 +00004447 // Nothing more to do: the inaccessibility/ambiguity check for
4448 // derived-to-base conversions is suppressed when we're
4449 // computing the implicit conversion sequence (C++
4450 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004451 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004452 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004453
Sebastian Redld92badf2010-06-30 18:13:39 +00004454 // -- has a class type (i.e., T2 is a class type), where T1 is
4455 // not reference-related to T2, and can be implicitly
4456 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4457 // is reference-compatible with "cv3 T3" 92) (this
4458 // conversion is selected by enumerating the applicable
4459 // conversion functions (13.3.1.6) and choosing the best
4460 // one through overload resolution (13.3)),
4461 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004462 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004463 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004464 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4465 Init, T2, /*AllowRvalues=*/false,
4466 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004467 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004468 }
4469 }
4470
Sebastian Redld92badf2010-06-30 18:13:39 +00004471 // -- Otherwise, the reference shall be an lvalue reference to a
4472 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004473 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004474 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004475 return ICS;
4476
Douglas Gregorf143cd52011-01-24 16:14:37 +00004477 // -- If the initializer expression
4478 //
4479 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004480 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004481 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004482 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004483 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4484 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004485 ICS.setStandard();
4486 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004488 : ObjCConversion? ICK_Compatible_Conversion
4489 : ICK_Identity;
4490 ICS.Standard.Third = ICK_Identity;
4491 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4492 ICS.Standard.setToType(0, T2);
4493 ICS.Standard.setToType(1, T1);
4494 ICS.Standard.setToType(2, T1);
4495 ICS.Standard.ReferenceBinding = true;
4496 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4497 // binding unless we're binding to a class prvalue.
4498 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4499 // allow the use of rvalue references in C++98/03 for the benefit of
4500 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004502 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004503 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004504 ICS.Standard.IsLvalueReference = !isRValRef;
4505 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004507 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004508 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004509 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004510 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregorf143cd52011-01-24 16:14:37 +00004514 // -- has a class type (i.e., T2 is a class type), where T1 is not
4515 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 // an xvalue, class prvalue, or function lvalue of type
4517 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004518 // "cv3 T3",
4519 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004521 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004523 // class subobject).
4524 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004525 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004526 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4527 Init, T2, /*AllowRvalues=*/true,
4528 AllowExplicit)) {
4529 // In the second case, if the reference is an rvalue reference
4530 // and the second standard conversion sequence of the
4531 // user-defined conversion sequence includes an lvalue-to-rvalue
4532 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004534 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4535 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4536
Douglas Gregor95273c32011-01-21 16:36:05 +00004537 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539
Richard Smith19172c42014-07-14 02:28:44 +00004540 // A temporary of function type cannot be created; don't even try.
4541 if (T1->isFunctionType())
4542 return ICS;
4543
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004544 // -- Otherwise, a temporary of type "cv1 T1" is created and
4545 // initialized from the initializer expression using the
4546 // rules for a non-reference copy initialization (8.5). The
4547 // reference is then bound to the temporary. If T1 is
4548 // reference-related to T2, cv1 must be the same
4549 // cv-qualification as, or greater cv-qualification than,
4550 // cv2; otherwise, the program is ill-formed.
4551 if (RefRelationship == Sema::Ref_Related) {
4552 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4553 // we would be reference-compatible or reference-compatible with
4554 // added qualification. But that wasn't the case, so the reference
4555 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004556 //
4557 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004558 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004559 Qualifiers T1Quals = T1.getQualifiers();
4560 Qualifiers T2Quals = T2.getQualifiers();
4561 T1Quals.removeObjCGCAttr();
4562 T1Quals.removeObjCLifetime();
4563 T2Quals.removeObjCGCAttr();
4564 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004565 // MS compiler ignores __unaligned qualifier for references; do the same.
4566 T1Quals.removeUnaligned();
4567 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004568 if (!T1Quals.compatiblyIncludes(T2Quals))
4569 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004570 }
4571
4572 // If at least one of the types is a class type, the types are not
4573 // related, and we aren't allowed any user conversions, the
4574 // reference binding fails. This case is important for breaking
4575 // recursion, since TryImplicitConversion below will attempt to
4576 // create a temporary through the use of a copy constructor.
4577 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4578 (T1->isRecordType() || T2->isRecordType()))
4579 return ICS;
4580
Douglas Gregorcba72b12011-01-21 05:18:22 +00004581 // If T1 is reference-related to T2 and the reference is an rvalue
4582 // reference, the initializer expression shall not be an lvalue.
4583 if (RefRelationship >= Sema::Ref_Related &&
4584 isRValRef && Init->Classify(S.Context).isLValue())
4585 return ICS;
4586
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004587 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004588 // When a parameter of reference type is not bound directly to
4589 // an argument expression, the conversion sequence is the one
4590 // required to convert the argument expression to the
4591 // underlying type of the reference according to
4592 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4593 // to copy-initializing a temporary of the underlying type with
4594 // the argument expression. Any difference in top-level
4595 // cv-qualification is subsumed by the initialization itself
4596 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004597 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4598 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004599 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004600 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004601 /*AllowObjCWritebackConversion=*/false,
4602 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004603
4604 // Of course, that's still a reference binding.
4605 if (ICS.isStandard()) {
4606 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004607 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004608 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004609 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004610 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004611 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004612 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004613 const ReferenceType *LValRefType =
4614 ICS.UserDefined.ConversionFunction->getReturnType()
4615 ->getAs<LValueReferenceType>();
4616
4617 // C++ [over.ics.ref]p3:
4618 // Except for an implicit object parameter, for which see 13.3.1, a
4619 // standard conversion sequence cannot be formed if it requires [...]
4620 // binding an rvalue reference to an lvalue other than a function
4621 // lvalue.
4622 // Note that the function case is not possible here.
4623 if (DeclType->isRValueReferenceType() && LValRefType) {
4624 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4625 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4626 // reference to an rvalue!
4627 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4628 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004629 }
Richard Smith19172c42014-07-14 02:28:44 +00004630
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004631 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004632 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004633 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4634 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004635 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004637 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004638
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004639 return ICS;
4640}
4641
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004642static ImplicitConversionSequence
4643TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4644 bool SuppressUserConversions,
4645 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004646 bool AllowObjCWritebackConversion,
4647 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004648
4649/// TryListConversion - Try to copy-initialize a value of type ToType from the
4650/// initializer list From.
4651static ImplicitConversionSequence
4652TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4653 bool SuppressUserConversions,
4654 bool InOverloadResolution,
4655 bool AllowObjCWritebackConversion) {
4656 // C++11 [over.ics.list]p1:
4657 // When an argument is an initializer list, it is not an expression and
4658 // special rules apply for converting it to a parameter type.
4659
4660 ImplicitConversionSequence Result;
4661 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4662
Sebastian Redl09edce02012-01-23 22:09:39 +00004663 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004664 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004665 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004666 return Result;
4667
Larisse Voufo19d08672015-01-27 18:47:05 +00004668 // Per DR1467:
4669 // If the parameter type is a class X and the initializer list has a single
4670 // element of type cv U, where U is X or a class derived from X, the
4671 // implicit conversion sequence is the one required to convert the element
4672 // to the parameter type.
4673 //
4674 // Otherwise, if the parameter type is a character array [... ]
4675 // and the initializer list has a single element that is an
4676 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4677 // implicit conversion sequence is the identity conversion.
4678 if (From->getNumInits() == 1) {
4679 if (ToType->isRecordType()) {
4680 QualType InitType = From->getInit(0)->getType();
4681 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004682 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004683 return TryCopyInitialization(S, From->getInit(0), ToType,
4684 SuppressUserConversions,
4685 InOverloadResolution,
4686 AllowObjCWritebackConversion);
4687 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004688 // FIXME: Check the other conditions here: array of character type,
4689 // initializer is a string literal.
4690 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004691 InitializedEntity Entity =
4692 InitializedEntity::InitializeParameter(S.Context, ToType,
4693 /*Consumed=*/false);
4694 if (S.CanPerformCopyInitialization(Entity, From)) {
4695 Result.setStandard();
4696 Result.Standard.setAsIdentityConversion();
4697 Result.Standard.setFromType(ToType);
4698 Result.Standard.setAllToTypes(ToType);
4699 return Result;
4700 }
4701 }
4702 }
4703
4704 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004705 // C++11 [over.ics.list]p2:
4706 // If the parameter type is std::initializer_list<X> or "array of X" and
4707 // all the elements can be implicitly converted to X, the implicit
4708 // conversion sequence is the worst conversion necessary to convert an
4709 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004710 //
4711 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004712 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004713 // list has exactly N elements or if it has fewer than N elements and X is
4714 // default-constructible, and if all the elements of the initializer list
4715 // can be implicitly converted to X, the implicit conversion sequence is
4716 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004717 //
4718 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004719 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004720 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004721 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004722 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004723 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004724 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004725 if (!X.isNull()) {
4726 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4727 Expr *Init = From->getInit(i);
4728 ImplicitConversionSequence ICS =
4729 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4730 InOverloadResolution,
4731 AllowObjCWritebackConversion);
4732 // If a single element isn't convertible, fail.
4733 if (ICS.isBad()) {
4734 Result = ICS;
4735 break;
4736 }
4737 // Otherwise, look for the worst conversion.
4738 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004739 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4740 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004741 ImplicitConversionSequence::Worse)
4742 Result = ICS;
4743 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004744
4745 // For an empty list, we won't have computed any conversion sequence.
4746 // Introduce the identity conversion sequence.
4747 if (From->getNumInits() == 0) {
4748 Result.setStandard();
4749 Result.Standard.setAsIdentityConversion();
4750 Result.Standard.setFromType(ToType);
4751 Result.Standard.setAllToTypes(ToType);
4752 }
4753
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004754 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004755 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004756 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004757
Larisse Voufo19d08672015-01-27 18:47:05 +00004758 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004759 // C++11 [over.ics.list]p3:
4760 // Otherwise, if the parameter is a non-aggregate class X and overload
4761 // resolution chooses a single best constructor [...] the implicit
4762 // conversion sequence is a user-defined conversion sequence. If multiple
4763 // constructors are viable but none is better than the others, the
4764 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004765 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4766 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004767 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4768 /*AllowExplicit=*/false,
4769 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004770 AllowObjCWritebackConversion,
4771 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004772 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004773
Larisse Voufo19d08672015-01-27 18:47:05 +00004774 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004775 // C++11 [over.ics.list]p4:
4776 // Otherwise, if the parameter has an aggregate type which can be
4777 // initialized from the initializer list [...] the implicit conversion
4778 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004779 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004780 // Type is an aggregate, argument is an init list. At this point it comes
4781 // down to checking whether the initialization works.
4782 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004783 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4784 // need to call into the initialization code here; overload resolution
4785 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004786 InitializedEntity Entity =
4787 InitializedEntity::InitializeParameter(S.Context, ToType,
4788 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004789 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004790 Result.setUserDefined();
4791 Result.UserDefined.Before.setAsIdentityConversion();
4792 // Initializer lists don't have a type.
4793 Result.UserDefined.Before.setFromType(QualType());
4794 Result.UserDefined.Before.setAllToTypes(QualType());
4795
4796 Result.UserDefined.After.setAsIdentityConversion();
4797 Result.UserDefined.After.setFromType(ToType);
4798 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004799 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004800 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004801 return Result;
4802 }
4803
Larisse Voufo19d08672015-01-27 18:47:05 +00004804 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004805 // C++11 [over.ics.list]p5:
4806 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004807 if (ToType->isReferenceType()) {
4808 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4809 // mention initializer lists in any way. So we go by what list-
4810 // initialization would do and try to extrapolate from that.
4811
4812 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4813
4814 // If the initializer list has a single element that is reference-related
4815 // to the parameter type, we initialize the reference from that.
4816 if (From->getNumInits() == 1) {
4817 Expr *Init = From->getInit(0);
4818
4819 QualType T2 = Init->getType();
4820
4821 // If the initializer is the address of an overloaded function, try
4822 // to resolve the overloaded function. If all goes well, T2 is the
4823 // type of the resulting function.
4824 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4825 DeclAccessPair Found;
4826 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4827 Init, ToType, false, Found))
4828 T2 = Fn->getType();
4829 }
4830
4831 // Compute some basic properties of the types and the initializer.
4832 bool dummy1 = false;
4833 bool dummy2 = false;
4834 bool dummy3 = false;
4835 Sema::ReferenceCompareResult RefRelationship
4836 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4837 dummy2, dummy3);
4838
Richard Smith4d2bbd72013-09-06 01:22:42 +00004839 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004840 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4841 SuppressUserConversions,
4842 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004843 }
Sebastian Redldf888642011-12-03 14:54:30 +00004844 }
4845
4846 // Otherwise, we bind the reference to a temporary created from the
4847 // initializer list.
4848 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4849 InOverloadResolution,
4850 AllowObjCWritebackConversion);
4851 if (Result.isFailure())
4852 return Result;
4853 assert(!Result.isEllipsis() &&
4854 "Sub-initialization cannot result in ellipsis conversion.");
4855
4856 // Can we even bind to a temporary?
4857 if (ToType->isRValueReferenceType() ||
4858 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4859 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4860 Result.UserDefined.After;
4861 SCS.ReferenceBinding = true;
4862 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4863 SCS.BindsToRvalue = true;
4864 SCS.BindsToFunctionLvalue = false;
4865 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4866 SCS.ObjCLifetimeConversionBinding = false;
4867 } else
4868 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4869 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004870 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004871 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004872
Larisse Voufo19d08672015-01-27 18:47:05 +00004873 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004874 // C++11 [over.ics.list]p6:
4875 // Otherwise, if the parameter type is not a class:
4876 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004877 // - if the initializer list has one element that is not itself an
4878 // initializer list, the implicit conversion sequence is the one
4879 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004880 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004881 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004882 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4883 SuppressUserConversions,
4884 InOverloadResolution,
4885 AllowObjCWritebackConversion);
4886 // - if the initializer list has no elements, the implicit conversion
4887 // sequence is the identity conversion.
4888 else if (NumInits == 0) {
4889 Result.setStandard();
4890 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004891 Result.Standard.setFromType(ToType);
4892 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004893 }
4894 return Result;
4895 }
4896
Larisse Voufo19d08672015-01-27 18:47:05 +00004897 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004898 // C++11 [over.ics.list]p7:
4899 // In all cases other than those enumerated above, no conversion is possible
4900 return Result;
4901}
4902
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004903/// TryCopyInitialization - Try to copy-initialize a value of type
4904/// ToType from the expression From. Return the implicit conversion
4905/// sequence required to pass this argument, which may be a bad
4906/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004907/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004908/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004909static ImplicitConversionSequence
4910TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004912 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004913 bool AllowObjCWritebackConversion,
4914 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004915 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4916 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4917 InOverloadResolution,AllowObjCWritebackConversion);
4918
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004919 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004920 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004921 /*FIXME:*/From->getLocStart(),
4922 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004923 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004924
John McCall5c32be02010-08-24 20:38:10 +00004925 return TryImplicitConversion(S, From, ToType,
4926 SuppressUserConversions,
4927 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004928 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004929 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004930 AllowObjCWritebackConversion,
4931 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004932}
4933
Anna Zaks1b068122011-07-28 19:46:48 +00004934static bool TryCopyInitialization(const CanQualType FromQTy,
4935 const CanQualType ToQTy,
4936 Sema &S,
4937 SourceLocation Loc,
4938 ExprValueKind FromVK) {
4939 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4940 ImplicitConversionSequence ICS =
4941 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4942
4943 return !ICS.isBad();
4944}
4945
Douglas Gregor436424c2008-11-18 23:14:02 +00004946/// TryObjectArgumentInitialization - Try to initialize the object
4947/// parameter of the given member function (@c Method) from the
4948/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004949static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004950TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004951 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004952 CXXMethodDecl *Method,
4953 CXXRecordDecl *ActingContext) {
4954 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004955 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4956 // const volatile object.
4957 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4958 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004959 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004960
4961 // Set up the conversion sequence as a "bad" conversion, to allow us
4962 // to exit early.
4963 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004964
4965 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004966 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004967 FromType = PT->getPointeeType();
4968
Douglas Gregor02824322011-01-26 19:30:28 +00004969 // When we had a pointer, it's implicitly dereferenced, so we
4970 // better have an lvalue.
4971 assert(FromClassification.isLValue());
4972 }
4973
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004974 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004975
Douglas Gregor02824322011-01-26 19:30:28 +00004976 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004978 // parameter is
4979 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004980 // - "lvalue reference to cv X" for functions declared without a
4981 // ref-qualifier or with the & ref-qualifier
4982 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004983 // ref-qualifier
4984 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004986 // cv-qualification on the member function declaration.
4987 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00004989 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004990 // (C++ [over.match.funcs]p5). We perform a simplified version of
4991 // reference binding here, that allows class rvalues to bind to
4992 // non-constant references.
4993
Douglas Gregor02824322011-01-26 19:30:28 +00004994 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004995 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004997 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004998 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004999 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005000 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005001 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005002 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005003
5004 // Check that we have either the same type or a derived type. It
5005 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005006 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005007 ImplicitConversionKind SecondKind;
5008 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5009 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005010 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005011 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005012 else {
John McCall65eb8792010-02-25 01:37:24 +00005013 ICS.setBad(BadConversionSequence::unrelated_class,
5014 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005015 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005016 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005017
Douglas Gregor02824322011-01-26 19:30:28 +00005018 // Check the ref-qualifier.
5019 switch (Method->getRefQualifier()) {
5020 case RQ_None:
5021 // Do nothing; we don't care about lvalueness or rvalueness.
5022 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023
Douglas Gregor02824322011-01-26 19:30:28 +00005024 case RQ_LValue:
5025 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5026 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005028 ImplicitParamType);
5029 return ICS;
5030 }
5031 break;
5032
5033 case RQ_RValue:
5034 if (!FromClassification.isRValue()) {
5035 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005037 ImplicitParamType);
5038 return ICS;
5039 }
5040 break;
5041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042
Douglas Gregor436424c2008-11-18 23:14:02 +00005043 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005044 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005045 ICS.Standard.setAsIdentityConversion();
5046 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005047 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005048 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005049 ICS.Standard.ReferenceBinding = true;
5050 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005052 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005053 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5054 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5055 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005056 return ICS;
5057}
5058
5059/// PerformObjectArgumentInitialization - Perform initialization of
5060/// the implicit object parameter for the given Method with the given
5061/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005062ExprResult
5063Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005065 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005066 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005067 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005068 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005069 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005070
Douglas Gregor02824322011-01-26 19:30:28 +00005071 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005072 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005073 FromRecordType = PT->getPointeeType();
5074 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005075 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005076 } else {
5077 FromRecordType = From->getType();
5078 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005079 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005080 }
5081
John McCall6e9f8f62009-12-03 04:06:58 +00005082 // Note that we always use the true parent context when performing
5083 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005084 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005085 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5086 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005087 if (ICS.isBad()) {
5088 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5089 Qualifiers FromQs = FromRecordType.getQualifiers();
5090 Qualifiers ToQs = DestType.getQualifiers();
5091 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5092 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005093 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005094 diag::err_member_function_call_bad_cvr)
5095 << Method->getDeclName() << FromRecordType << (CVR - 1)
5096 << From->getSourceRange();
5097 Diag(Method->getLocation(), diag::note_previous_decl)
5098 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005099 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005100 }
5101 }
5102
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005103 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005104 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005105 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005106 }
Mike Stump11289f42009-09-09 15:08:12 +00005107
John Wiegley01296292011-04-08 18:41:53 +00005108 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5109 ExprResult FromRes =
5110 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5111 if (FromRes.isInvalid())
5112 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005113 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005114 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005115
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005116 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005117 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005118 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005119 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005120}
5121
Douglas Gregor5fb53972009-01-14 15:45:31 +00005122/// TryContextuallyConvertToBool - Attempt to contextually convert the
5123/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005124static ImplicitConversionSequence
5125TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005126 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005127 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005128 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005129 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005130 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005131 /*AllowObjCWritebackConversion=*/false,
5132 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005133}
5134
5135/// PerformContextuallyConvertToBool - Perform a contextual conversion
5136/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005137ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005138 if (checkPlaceholderForOverload(*this, From))
5139 return ExprError();
5140
John McCall5c32be02010-08-24 20:38:10 +00005141 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005142 if (!ICS.isBad())
5143 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144
Fariborz Jahanian76197412009-11-18 18:26:29 +00005145 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005146 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005147 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005148 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005149 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005150}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Richard Smithf8379a02012-01-18 23:55:52 +00005152/// Check that the specified conversion is permitted in a converted constant
5153/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5154/// is acceptable.
5155static bool CheckConvertedConstantConversions(Sema &S,
5156 StandardConversionSequence &SCS) {
5157 // Since we know that the target type is an integral or unscoped enumeration
5158 // type, most conversion kinds are impossible. All possible First and Third
5159 // conversions are fine.
5160 switch (SCS.Second) {
5161 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005162 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005163 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005164 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005165 return true;
5166
5167 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005168 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005169 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5170 // conversion, so we allow it in a converted constant expression.
5171 //
5172 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5173 // a lot of popular code. We should at least add a warning for this
5174 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005175 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5176 SCS.getToType(2)->isBooleanType();
5177
Richard Smith410cc892014-11-26 03:26:53 +00005178 case ICK_Pointer_Conversion:
5179 case ICK_Pointer_Member:
5180 // C++1z: null pointer conversions and null member pointer conversions are
5181 // only permitted if the source type is std::nullptr_t.
5182 return SCS.getFromType()->isNullPtrType();
5183
5184 case ICK_Floating_Promotion:
5185 case ICK_Complex_Promotion:
5186 case ICK_Floating_Conversion:
5187 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005188 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005189 case ICK_Compatible_Conversion:
5190 case ICK_Derived_To_Base:
5191 case ICK_Vector_Conversion:
5192 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005193 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005194 case ICK_Block_Pointer_Conversion:
5195 case ICK_TransparentUnionConversion:
5196 case ICK_Writeback_Conversion:
5197 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005198 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005199 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005200 return false;
5201
5202 case ICK_Lvalue_To_Rvalue:
5203 case ICK_Array_To_Pointer:
5204 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005205 llvm_unreachable("found a first conversion kind in Second");
5206
Richard Smithf8379a02012-01-18 23:55:52 +00005207 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005208 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005209
5210 case ICK_Num_Conversion_Kinds:
5211 break;
5212 }
5213
5214 llvm_unreachable("unknown conversion kind");
5215}
5216
5217/// CheckConvertedConstantExpression - Check that the expression From is a
5218/// converted constant expression of type T, perform the conversion and produce
5219/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005220static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5221 QualType T, APValue &Value,
5222 Sema::CCEKind CCE,
5223 bool RequireInt) {
5224 assert(S.getLangOpts().CPlusPlus11 &&
5225 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005226
Richard Smith410cc892014-11-26 03:26:53 +00005227 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005228 return ExprError();
5229
Richard Smith410cc892014-11-26 03:26:53 +00005230 // C++1z [expr.const]p3:
5231 // A converted constant expression of type T is an expression,
5232 // implicitly converted to type T, where the converted
5233 // expression is a constant expression and the implicit conversion
5234 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005235 // C++1z [stmt.if]p2:
5236 // If the if statement is of the form if constexpr, the value of the
5237 // condition shall be a contextually converted constant expression of type
5238 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005239 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005240 CCE == Sema::CCEK_ConstexprIf
5241 ? TryContextuallyConvertToBool(S, From)
5242 : TryCopyInitialization(S, From, T,
5243 /*SuppressUserConversions=*/false,
5244 /*InOverloadResolution=*/false,
5245 /*AllowObjcWritebackConversion=*/false,
5246 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005247 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005248 switch (ICS.getKind()) {
5249 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005250 SCS = &ICS.Standard;
5251 break;
5252 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005253 // We are converting to a non-class type, so the Before sequence
5254 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005255 SCS = &ICS.UserDefined.After;
5256 break;
5257 case ImplicitConversionSequence::AmbiguousConversion:
5258 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005259 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5260 return S.Diag(From->getLocStart(),
5261 diag::err_typecheck_converted_constant_expression)
5262 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005263 return ExprError();
5264
5265 case ImplicitConversionSequence::EllipsisConversion:
5266 llvm_unreachable("ellipsis conversion in converted constant expression");
5267 }
5268
Richard Smith410cc892014-11-26 03:26:53 +00005269 // Check that we would only use permitted conversions.
5270 if (!CheckConvertedConstantConversions(S, *SCS)) {
5271 return S.Diag(From->getLocStart(),
5272 diag::err_typecheck_converted_constant_expression_disallowed)
5273 << From->getType() << From->getSourceRange() << T;
5274 }
5275 // [...] and where the reference binding (if any) binds directly.
5276 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5277 return S.Diag(From->getLocStart(),
5278 diag::err_typecheck_converted_constant_expression_indirect)
5279 << From->getType() << From->getSourceRange() << T;
5280 }
5281
5282 ExprResult Result =
5283 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005284 if (Result.isInvalid())
5285 return Result;
5286
5287 // Check for a narrowing implicit conversion.
5288 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005289 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005290 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005291 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005292 case NK_Variable_Narrowing:
5293 // Implicit conversion to a narrower type, and the value is not a constant
5294 // expression. We'll diagnose this in a moment.
5295 case NK_Not_Narrowing:
5296 break;
5297
5298 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005299 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005300 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005301 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005302 break;
5303
5304 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005305 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005306 << CCE << /*Constant*/0 << From->getType() << T;
5307 break;
5308 }
5309
5310 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005311 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005312 Expr::EvalResult Eval;
5313 Eval.Diag = &Notes;
5314
Richard Smith410cc892014-11-26 03:26:53 +00005315 if ((T->isReferenceType()
5316 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5317 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5318 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005319 // The expression can't be folded, so we can't keep it at this position in
5320 // the AST.
5321 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005322 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005323 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005324
5325 if (Notes.empty()) {
5326 // It's a constant expression.
5327 return Result;
5328 }
Richard Smithf8379a02012-01-18 23:55:52 +00005329 }
5330
5331 // It's not a constant expression. Produce an appropriate diagnostic.
5332 if (Notes.size() == 1 &&
5333 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005334 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005335 else {
Richard Smith410cc892014-11-26 03:26:53 +00005336 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005337 << CCE << From->getSourceRange();
5338 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005339 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005340 }
Richard Smith410cc892014-11-26 03:26:53 +00005341 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005342}
5343
Richard Smith410cc892014-11-26 03:26:53 +00005344ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5345 APValue &Value, CCEKind CCE) {
5346 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5347}
5348
5349ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5350 llvm::APSInt &Value,
5351 CCEKind CCE) {
5352 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5353
5354 APValue V;
5355 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5356 if (!R.isInvalid())
5357 Value = V.getInt();
5358 return R;
5359}
5360
5361
John McCallfec112d2011-09-09 06:11:02 +00005362/// dropPointerConversions - If the given standard conversion sequence
5363/// involves any pointer conversions, remove them. This may change
5364/// the result type of the conversion sequence.
5365static void dropPointerConversion(StandardConversionSequence &SCS) {
5366 if (SCS.Second == ICK_Pointer_Conversion) {
5367 SCS.Second = ICK_Identity;
5368 SCS.Third = ICK_Identity;
5369 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5370 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005371}
John McCall5c32be02010-08-24 20:38:10 +00005372
John McCallfec112d2011-09-09 06:11:02 +00005373/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5374/// convert the expression From to an Objective-C pointer type.
5375static ImplicitConversionSequence
5376TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5377 // Do an implicit conversion to 'id'.
5378 QualType Ty = S.Context.getObjCIdType();
5379 ImplicitConversionSequence ICS
5380 = TryImplicitConversion(S, From, Ty,
5381 // FIXME: Are these flags correct?
5382 /*SuppressUserConversions=*/false,
5383 /*AllowExplicit=*/true,
5384 /*InOverloadResolution=*/false,
5385 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005386 /*AllowObjCWritebackConversion=*/false,
5387 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005388
5389 // Strip off any final conversions to 'id'.
5390 switch (ICS.getKind()) {
5391 case ImplicitConversionSequence::BadConversion:
5392 case ImplicitConversionSequence::AmbiguousConversion:
5393 case ImplicitConversionSequence::EllipsisConversion:
5394 break;
5395
5396 case ImplicitConversionSequence::UserDefinedConversion:
5397 dropPointerConversion(ICS.UserDefined.After);
5398 break;
5399
5400 case ImplicitConversionSequence::StandardConversion:
5401 dropPointerConversion(ICS.Standard);
5402 break;
5403 }
5404
5405 return ICS;
5406}
5407
5408/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5409/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005410/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005411ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005412 if (checkPlaceholderForOverload(*this, From))
5413 return ExprError();
5414
John McCall8b07ec22010-05-15 11:32:37 +00005415 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005416 ImplicitConversionSequence ICS =
5417 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005418 if (!ICS.isBad())
5419 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005420 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005421}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005422
Richard Smith8dd34252012-02-04 07:07:42 +00005423/// Determine whether the provided type is an integral type, or an enumeration
5424/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005425bool Sema::ICEConvertDiagnoser::match(QualType T) {
5426 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5427 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005428}
5429
Larisse Voufo236bec22013-06-10 06:50:24 +00005430static ExprResult
5431diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5432 Sema::ContextualImplicitConverter &Converter,
5433 QualType T, UnresolvedSetImpl &ViableConversions) {
5434
5435 if (Converter.Suppress)
5436 return ExprError();
5437
5438 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5439 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5440 CXXConversionDecl *Conv =
5441 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5442 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5443 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5444 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005445 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005446}
5447
5448static bool
5449diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5450 Sema::ContextualImplicitConverter &Converter,
5451 QualType T, bool HadMultipleCandidates,
5452 UnresolvedSetImpl &ExplicitConversions) {
5453 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5454 DeclAccessPair Found = ExplicitConversions[0];
5455 CXXConversionDecl *Conversion =
5456 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5457
5458 // The user probably meant to invoke the given explicit
5459 // conversion; use it.
5460 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5461 std::string TypeStr;
5462 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5463
5464 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5465 << FixItHint::CreateInsertion(From->getLocStart(),
5466 "static_cast<" + TypeStr + ">(")
5467 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005468 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5470
5471 // If we aren't in a SFINAE context, build a call to the
5472 // explicit conversion function.
5473 if (SemaRef.isSFINAEContext())
5474 return true;
5475
Craig Topperc3ec1492014-05-26 06:22:03 +00005476 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005477 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5478 HadMultipleCandidates);
5479 if (Result.isInvalid())
5480 return true;
5481 // Record usage of conversion in an implicit cast.
5482 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005483 CK_UserDefinedConversion, Result.get(),
5484 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005485 }
5486 return false;
5487}
5488
5489static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5490 Sema::ContextualImplicitConverter &Converter,
5491 QualType T, bool HadMultipleCandidates,
5492 DeclAccessPair &Found) {
5493 CXXConversionDecl *Conversion =
5494 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005495 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005496
5497 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5498 if (!Converter.SuppressConversion) {
5499 if (SemaRef.isSFINAEContext())
5500 return true;
5501
5502 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5503 << From->getSourceRange();
5504 }
5505
5506 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5507 HadMultipleCandidates);
5508 if (Result.isInvalid())
5509 return true;
5510 // Record usage of conversion in an implicit cast.
5511 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005512 CK_UserDefinedConversion, Result.get(),
5513 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 return false;
5515}
5516
5517static ExprResult finishContextualImplicitConversion(
5518 Sema &SemaRef, SourceLocation Loc, Expr *From,
5519 Sema::ContextualImplicitConverter &Converter) {
5520 if (!Converter.match(From->getType()) && !Converter.Suppress)
5521 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5522 << From->getSourceRange();
5523
5524 return SemaRef.DefaultLvalueConversion(From);
5525}
5526
5527static void
5528collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5529 UnresolvedSetImpl &ViableConversions,
5530 OverloadCandidateSet &CandidateSet) {
5531 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5532 DeclAccessPair FoundDecl = ViableConversions[I];
5533 NamedDecl *D = FoundDecl.getDecl();
5534 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5535 if (isa<UsingShadowDecl>(D))
5536 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5537
5538 CXXConversionDecl *Conv;
5539 FunctionTemplateDecl *ConvTemplate;
5540 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5541 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5542 else
5543 Conv = cast<CXXConversionDecl>(D);
5544
5545 if (ConvTemplate)
5546 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005547 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5548 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005549 else
5550 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005551 ToType, CandidateSet,
5552 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005553 }
5554}
5555
Richard Smithccc11812013-05-21 19:05:48 +00005556/// \brief Attempt to convert the given expression to a type which is accepted
5557/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005558///
Richard Smithccc11812013-05-21 19:05:48 +00005559/// This routine will attempt to convert an expression of class type to a
5560/// type accepted by the specified converter. In C++11 and before, the class
5561/// must have a single non-explicit conversion function converting to a matching
5562/// type. In C++1y, there can be multiple such conversion functions, but only
5563/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005564///
Douglas Gregor4799d032010-06-30 00:20:43 +00005565/// \param Loc The source location of the construct that requires the
5566/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005567///
James Dennett18348b62012-06-22 08:52:37 +00005568/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005569///
Richard Smithccc11812013-05-21 19:05:48 +00005570/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005571///
Douglas Gregor4799d032010-06-30 00:20:43 +00005572/// \returns The expression, converted to an integral or enumeration type if
5573/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005574ExprResult Sema::PerformContextualImplicitConversion(
5575 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005576 // We can't perform any more checking for type-dependent expressions.
5577 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005578 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Eli Friedman1da70392012-01-26 00:26:18 +00005580 // Process placeholders immediately.
5581 if (From->hasPlaceholderType()) {
5582 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005583 if (result.isInvalid())
5584 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005585 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005586 }
5587
Richard Smithccc11812013-05-21 19:05:48 +00005588 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005589 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005590 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005591 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005592
5593 // FIXME: Check for missing '()' if T is a function type?
5594
Richard Smithccc11812013-05-21 19:05:48 +00005595 // We can only perform contextual implicit conversions on objects of class
5596 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005597 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005598 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005599 if (!Converter.Suppress)
5600 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005601 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005604 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005605 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005606 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005607 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005608
5609 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005610 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005611
Craig Toppere14c0f82014-03-12 04:55:44 +00005612 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005613 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005614 }
Richard Smithccc11812013-05-21 19:05:48 +00005615 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005616
Richard Smithdb0ac552015-12-18 22:40:25 +00005617 if (Converter.Suppress ? !isCompleteType(Loc, T)
5618 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005619 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005621 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005622 UnresolvedSet<4>
5623 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005624 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005625 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005626 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Larisse Voufo236bec22013-06-10 06:50:24 +00005628 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005629 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005630
Larisse Voufo236bec22013-06-10 06:50:24 +00005631 // To check that there is only one target type, in C++1y:
5632 QualType ToType;
5633 bool HasUniqueTargetType = true;
5634
5635 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005636 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005637 NamedDecl *D = (*I)->getUnderlyingDecl();
5638 CXXConversionDecl *Conversion;
5639 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5640 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005641 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005642 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5643 else
5644 continue; // C++11 does not consider conversion operator templates(?).
5645 } else
5646 Conversion = cast<CXXConversionDecl>(D);
5647
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005648 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005649 "Conversion operator templates are considered potentially "
5650 "viable in C++1y");
5651
5652 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5653 if (Converter.match(CurToType) || ConvTemplate) {
5654
5655 if (Conversion->isExplicit()) {
5656 // FIXME: For C++1y, do we need this restriction?
5657 // cf. diagnoseNoViableConversion()
5658 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005659 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005660 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005661 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005662 if (ToType.isNull())
5663 ToType = CurToType.getUnqualifiedType();
5664 else if (HasUniqueTargetType &&
5665 (CurToType.getUnqualifiedType() != ToType))
5666 HasUniqueTargetType = false;
5667 }
5668 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005669 }
Richard Smith8dd34252012-02-04 07:07:42 +00005670 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005673 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005674 // C++1y [conv]p6:
5675 // ... An expression e of class type E appearing in such a context
5676 // is said to be contextually implicitly converted to a specified
5677 // type T and is well-formed if and only if e can be implicitly
5678 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005679 // for conversion functions whose return type is cv T or reference to
5680 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005681 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682
Larisse Voufo236bec22013-06-10 06:50:24 +00005683 // If no unique T is found:
5684 if (ToType.isNull()) {
5685 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5686 HadMultipleCandidates,
5687 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005688 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005689 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Larisse Voufo236bec22013-06-10 06:50:24 +00005692 // If more than one unique Ts are found:
5693 if (!HasUniqueTargetType)
5694 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5695 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Larisse Voufo236bec22013-06-10 06:50:24 +00005697 // If one unique T is found:
5698 // First, build a candidate set from the previously recorded
5699 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005700 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005701 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5702 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703
Larisse Voufo236bec22013-06-10 06:50:24 +00005704 // Then, perform overload resolution over the candidate set.
5705 OverloadCandidateSet::iterator Best;
5706 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5707 case OR_Success: {
5708 // Apply this conversion.
5709 DeclAccessPair Found =
5710 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5711 if (recordConversion(*this, Loc, From, Converter, T,
5712 HadMultipleCandidates, Found))
5713 return ExprError();
5714 break;
5715 }
5716 case OR_Ambiguous:
5717 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5718 ViableConversions);
5719 case OR_No_Viable_Function:
5720 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5721 HadMultipleCandidates,
5722 ExplicitConversions))
5723 return ExprError();
5724 // fall through 'OR_Deleted' case.
5725 case OR_Deleted:
5726 // We'll complain below about a non-integral condition type.
5727 break;
5728 }
5729 } else {
5730 switch (ViableConversions.size()) {
5731 case 0: {
5732 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5733 HadMultipleCandidates,
5734 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005735 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Larisse Voufo236bec22013-06-10 06:50:24 +00005737 // We'll complain below about a non-integral condition type.
5738 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005739 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005740 case 1: {
5741 // Apply this conversion.
5742 DeclAccessPair Found = ViableConversions[0];
5743 if (recordConversion(*this, Loc, From, Converter, T,
5744 HadMultipleCandidates, Found))
5745 return ExprError();
5746 break;
5747 }
5748 default:
5749 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5750 ViableConversions);
5751 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Larisse Voufo236bec22013-06-10 06:50:24 +00005754 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005755}
5756
Richard Smith100b24a2014-04-17 01:52:14 +00005757/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5758/// an acceptable non-member overloaded operator for a call whose
5759/// arguments have types T1 (and, if non-empty, T2). This routine
5760/// implements the check in C++ [over.match.oper]p3b2 concerning
5761/// enumeration types.
5762static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5763 FunctionDecl *Fn,
5764 ArrayRef<Expr *> Args) {
5765 QualType T1 = Args[0]->getType();
5766 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5767
5768 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5769 return true;
5770
5771 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5772 return true;
5773
5774 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5775 if (Proto->getNumParams() < 1)
5776 return false;
5777
5778 if (T1->isEnumeralType()) {
5779 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5780 if (Context.hasSameUnqualifiedType(T1, ArgType))
5781 return true;
5782 }
5783
5784 if (Proto->getNumParams() < 2)
5785 return false;
5786
5787 if (!T2.isNull() && T2->isEnumeralType()) {
5788 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5789 if (Context.hasSameUnqualifiedType(T2, ArgType))
5790 return true;
5791 }
5792
5793 return false;
5794}
5795
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005796/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005797/// candidate functions, using the given function call arguments. If
5798/// @p SuppressUserConversions, then don't allow user-defined
5799/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005800///
James Dennett2a4d13c2012-06-15 07:13:21 +00005801/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005802/// based on an incomplete set of function arguments. This feature is used by
5803/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005804void
5805Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005806 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005807 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005808 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005809 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005810 bool PartialOverloading,
5811 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005812 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005813 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005814 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005815 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005816 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005817
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005819 if (!isa<CXXConstructorDecl>(Method)) {
5820 // If we get here, it's because we're calling a member function
5821 // that is named without a member access expression (e.g.,
5822 // "this->f") that was either written explicitly or created
5823 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005824 // function, e.g., X::f(). We use an empty type for the implied
5825 // object argument (C++ [over.call.func]p3), and the acting context
5826 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005827 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005828 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005829 Args, CandidateSet, SuppressUserConversions,
5830 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005831 return;
5832 }
5833 // We treat a constructor like a non-member function, since its object
5834 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005835 }
5836
Douglas Gregorff7028a2009-11-13 23:59:09 +00005837 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005838 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005839
Richard Smith100b24a2014-04-17 01:52:14 +00005840 // C++ [over.match.oper]p3:
5841 // if no operand has a class type, only those non-member functions in the
5842 // lookup set that have a first parameter of type T1 or "reference to
5843 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5844 // is a right operand) a second parameter of type T2 or "reference to
5845 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5846 // candidate functions.
5847 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5848 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5849 return;
5850
Richard Smith8b86f2d2013-11-04 01:48:18 +00005851 // C++11 [class.copy]p11: [DR1402]
5852 // A defaulted move constructor that is defined as deleted is ignored by
5853 // overload resolution.
5854 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5855 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5856 Constructor->isMoveConstructor())
5857 return;
5858
Douglas Gregor27381f32009-11-23 12:27:39 +00005859 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005860 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005861
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005862 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005863 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005864 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005865 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005866 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005867 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005868 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005869 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
John McCall578a1f82014-12-14 01:46:53 +00005871 if (Constructor) {
5872 // C++ [class.copy]p3:
5873 // A member function template is never instantiated to perform the copy
5874 // of a class object to an object of its class type.
5875 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005876 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005877 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005878 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5879 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005880 Candidate.Viable = false;
5881 Candidate.FailureKind = ovl_fail_illegal_constructor;
5882 return;
5883 }
5884 }
5885
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005886 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005887
5888 // (C++ 13.3.2p2): A candidate function having fewer than m
5889 // parameters is viable only if it has an ellipsis in its parameter
5890 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005891 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005892 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005893 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005894 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005895 return;
5896 }
5897
5898 // (C++ 13.3.2p2): A candidate function having more than m parameters
5899 // is viable only if the (m+1)st parameter has a default argument
5900 // (8.3.6). For the purposes of overload resolution, the
5901 // parameter list is truncated on the right, so that there are
5902 // exactly m parameters.
5903 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005904 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005905 // Not enough arguments.
5906 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005907 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005908 return;
5909 }
5910
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005911 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005912 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005913 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005914 // Skip the check for callers that are implicit members, because in this
5915 // case we may not yet know what the member's target is; the target is
5916 // inferred for the member automatically, based on the bases and fields of
5917 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005918 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005919 Candidate.Viable = false;
5920 Candidate.FailureKind = ovl_fail_bad_target;
5921 return;
5922 }
5923
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005924 // Determine the implicit conversion sequences for each of the
5925 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005926 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005927 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005928 // (C++ 13.3.2p3): for F to be a viable function, there shall
5929 // exist for each argument an implicit conversion sequence
5930 // (13.3.3.1) that converts that argument to the corresponding
5931 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005932 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005933 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005934 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005936 /*InOverloadResolution=*/true,
5937 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005938 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005939 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005940 if (Candidate.Conversions[ArgIdx].isBad()) {
5941 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005942 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005943 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005944 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005945 } else {
5946 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5947 // argument for which there is no corresponding parameter is
5948 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005949 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005950 }
5951 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005952
5953 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5954 Candidate.Viable = false;
5955 Candidate.FailureKind = ovl_fail_enable_if;
5956 Candidate.DeductionFailure.Data = FailedAttr;
5957 return;
5958 }
Yaxun Liu5b746652016-12-18 05:18:55 +00005959
5960 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
5961 Candidate.Viable = false;
5962 Candidate.FailureKind = ovl_fail_ext_disabled;
5963 return;
5964 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005965}
5966
Manman Rend2a3cd72016-04-07 19:30:20 +00005967ObjCMethodDecl *
5968Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5969 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5970 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005971 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005972
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005973 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5974 bool Match = true;
5975 ObjCMethodDecl *Method = Methods[b];
5976 unsigned NumNamedArgs = Sel.getNumArgs();
5977 // Method might have more arguments than selector indicates. This is due
5978 // to addition of c-style arguments in method.
5979 if (Method->param_size() > NumNamedArgs)
5980 NumNamedArgs = Method->param_size();
5981 if (Args.size() < NumNamedArgs)
5982 continue;
5983
5984 for (unsigned i = 0; i < NumNamedArgs; i++) {
5985 // We can't do any type-checking on a type-dependent argument.
5986 if (Args[i]->isTypeDependent()) {
5987 Match = false;
5988 break;
5989 }
5990
5991 ParmVarDecl *param = Method->parameters()[i];
5992 Expr *argExpr = Args[i];
5993 assert(argExpr && "SelectBestMethod(): missing expression");
5994
5995 // Strip the unbridged-cast placeholder expression off unless it's
5996 // a consumed argument.
5997 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5998 !param->hasAttr<CFConsumedAttr>())
5999 argExpr = stripARCUnbridgedCast(argExpr);
6000
6001 // If the parameter is __unknown_anytype, move on to the next method.
6002 if (param->getType() == Context.UnknownAnyTy) {
6003 Match = false;
6004 break;
6005 }
George Burgess IV45461812015-10-11 20:13:20 +00006006
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006007 ImplicitConversionSequence ConversionState
6008 = TryCopyInitialization(*this, argExpr, param->getType(),
6009 /*SuppressUserConversions*/false,
6010 /*InOverloadResolution=*/true,
6011 /*AllowObjCWritebackConversion=*/
6012 getLangOpts().ObjCAutoRefCount,
6013 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006014 // This function looks for a reasonably-exact match, so we consider
6015 // incompatible pointer conversions to be a failure here.
6016 if (ConversionState.isBad() ||
6017 (ConversionState.isStandard() &&
6018 ConversionState.Standard.Second ==
6019 ICK_Incompatible_Pointer_Conversion)) {
6020 Match = false;
6021 break;
6022 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006023 }
6024 // Promote additional arguments to variadic methods.
6025 if (Match && Method->isVariadic()) {
6026 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6027 if (Args[i]->isTypeDependent()) {
6028 Match = false;
6029 break;
6030 }
6031 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6032 nullptr);
6033 if (Arg.isInvalid()) {
6034 Match = false;
6035 break;
6036 }
6037 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006038 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006039 // Check for extra arguments to non-variadic methods.
6040 if (Args.size() != NumNamedArgs)
6041 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006042 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6043 // Special case when selectors have no argument. In this case, select
6044 // one with the most general result type of 'id'.
6045 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6046 QualType ReturnT = Methods[b]->getReturnType();
6047 if (ReturnT->isObjCIdType())
6048 return Methods[b];
6049 }
6050 }
6051 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006052
6053 if (Match)
6054 return Method;
6055 }
6056 return nullptr;
6057}
6058
George Burgess IV2a6150d2015-10-16 01:17:38 +00006059// specific_attr_iterator iterates over enable_if attributes in reverse, and
6060// enable_if is order-sensitive. As a result, we need to reverse things
6061// sometimes. Size of 4 elements is arbitrary.
6062static SmallVector<EnableIfAttr *, 4>
6063getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6064 SmallVector<EnableIfAttr *, 4> Result;
6065 if (!Function->hasAttrs())
6066 return Result;
6067
6068 const auto &FuncAttrs = Function->getAttrs();
6069 for (Attr *Attr : FuncAttrs)
6070 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6071 Result.push_back(EnableIf);
6072
6073 std::reverse(Result.begin(), Result.end());
6074 return Result;
6075}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006076
6077EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6078 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006079 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6080 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006081 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006082
6083 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006084 SmallVector<Expr *, 16> ConvertedArgs;
6085 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006086
George Burgess IV458b3f32016-08-12 04:19:35 +00006087 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006088 // user can't refer to them in the enable_if condition.
6089 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6090
Nick Lewyckye283c552015-08-25 22:33:16 +00006091 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006092 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006093 ExprResult R;
6094 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006095 !cast<CXXMethodDecl>(Function)->isStatic() &&
6096 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006097 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006098 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6099 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006100 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006101 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6102 Context, Function->getParamDecl(I)),
6103 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006104 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006105
6106 if (R.isInvalid()) {
6107 InitializationFailed = true;
6108 break;
6109 }
6110
George Burgess IVe96abf72016-02-24 22:31:14 +00006111 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006112 }
6113
6114 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006115 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006116
Nick Lewyckye283c552015-08-25 22:33:16 +00006117 // Push default arguments if needed.
6118 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6119 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6120 ParmVarDecl *P = Function->getParamDecl(i);
6121 ExprResult R = PerformCopyInitialization(
6122 InitializedEntity::InitializeParameter(Context,
6123 Function->getParamDecl(i)),
6124 SourceLocation(),
6125 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6126 : P->getDefaultArg());
6127 if (R.isInvalid()) {
6128 InitializationFailed = true;
6129 break;
6130 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006131 ConvertedArgs.push_back(R.get());
6132 }
6133
6134 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006135 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006136 }
6137
George Burgess IV2a6150d2015-10-16 01:17:38 +00006138 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006139 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006140 // FIXME: This doesn't consider value-dependent cases, because doing so is
6141 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006142 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006143 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006144 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006145
6146 if (!Result.isInt() || !Result.getInt().getBoolValue())
6147 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006148 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006149 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006150}
6151
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006152/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006153/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006154void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006155 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006156 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006157 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006158 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006159 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006160 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006161 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6162 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006163 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006164 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006165 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006166 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006167 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006168 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006169 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006170 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006171 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006172 } else {
John McCalla0296f72010-03-19 07:35:19 +00006173 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006174 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6175 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006176 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006177 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006178 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006179 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006180 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006181 CandidateSet, SuppressUserConversions,
6182 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006183 else
John McCalla0296f72010-03-19 07:35:19 +00006184 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006185 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006186 CandidateSet, SuppressUserConversions,
6187 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006188 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006189 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006190}
6191
John McCallf0f1cf02009-11-17 07:50:12 +00006192/// AddMethodCandidate - Adds a named decl (which is some kind of
6193/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006194void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006195 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006196 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006197 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006198 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006199 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006200 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006201 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006202
6203 if (isa<UsingShadowDecl>(Decl))
6204 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205
John McCallf0f1cf02009-11-17 07:50:12 +00006206 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6207 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6208 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006209 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006210 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006211 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006212 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006213 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006214 } else {
John McCalla0296f72010-03-19 07:35:19 +00006215 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006216 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006217 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006218 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006219 }
6220}
6221
Douglas Gregor436424c2008-11-18 23:14:02 +00006222/// AddMethodCandidate - Adds the given C++ member function to the set
6223/// of candidate functions, using the given function call arguments
6224/// and the object argument (@c Object). For example, in a call
6225/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6226/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6227/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006228/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006229void
John McCalla0296f72010-03-19 07:35:19 +00006230Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006231 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006232 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006233 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006234 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006235 bool SuppressUserConversions,
6236 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006237 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006238 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006239 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006240 assert(!isa<CXXConstructorDecl>(Method) &&
6241 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006242
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006243 if (!CandidateSet.isNewCandidate(Method))
6244 return;
6245
Richard Smith8b86f2d2013-11-04 01:48:18 +00006246 // C++11 [class.copy]p23: [DR1402]
6247 // A defaulted move assignment operator that is defined as deleted is
6248 // ignored by overload resolution.
6249 if (Method->isDefaulted() && Method->isDeleted() &&
6250 Method->isMoveAssignmentOperator())
6251 return;
6252
Douglas Gregor27381f32009-11-23 12:27:39 +00006253 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006254 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006255
Douglas Gregor436424c2008-11-18 23:14:02 +00006256 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006257 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006258 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006259 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006260 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006261 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006262 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006263
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006264 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006265
6266 // (C++ 13.3.2p2): A candidate function having fewer than m
6267 // parameters is viable only if it has an ellipsis in its parameter
6268 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006269 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6270 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006271 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006272 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006273 return;
6274 }
6275
6276 // (C++ 13.3.2p2): A candidate function having more than m parameters
6277 // is viable only if the (m+1)st parameter has a default argument
6278 // (8.3.6). For the purposes of overload resolution, the
6279 // parameter list is truncated on the right, so that there are
6280 // exactly m parameters.
6281 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006282 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006283 // Not enough arguments.
6284 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006285 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006286 return;
6287 }
6288
6289 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006290
John McCall6e9f8f62009-12-03 04:06:58 +00006291 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006292 // The implicit object argument is ignored.
6293 Candidate.IgnoreObjectArgument = true;
6294 else {
6295 // Determine the implicit conversion sequence for the object
6296 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006297 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6298 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6299 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006300 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006301 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006302 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006303 return;
6304 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006305 }
6306
Eli Bendersky291a57e2014-09-25 23:59:08 +00006307 // (CUDA B.1): Check for invalid calls between targets.
6308 if (getLangOpts().CUDA)
6309 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006310 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006311 Candidate.Viable = false;
6312 Candidate.FailureKind = ovl_fail_bad_target;
6313 return;
6314 }
6315
Douglas Gregor436424c2008-11-18 23:14:02 +00006316 // Determine the implicit conversion sequences for each of the
6317 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006318 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006319 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006320 // (C++ 13.3.2p3): for F to be a viable function, there shall
6321 // exist for each argument an implicit conversion sequence
6322 // (13.3.3.1) that converts that argument to the corresponding
6323 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006324 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006325 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006326 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006328 /*InOverloadResolution=*/true,
6329 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006330 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006331 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006332 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006333 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006334 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006335 }
6336 } else {
6337 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6338 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006339 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006340 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006341 }
6342 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006343
6344 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6345 Candidate.Viable = false;
6346 Candidate.FailureKind = ovl_fail_enable_if;
6347 Candidate.DeductionFailure.Data = FailedAttr;
6348 return;
6349 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006350}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006351
Douglas Gregor97628d62009-08-21 00:16:32 +00006352/// \brief Add a C++ member function template as a candidate to the candidate
6353/// set, using template argument deduction to produce an appropriate member
6354/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006355void
Douglas Gregor97628d62009-08-21 00:16:32 +00006356Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006357 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006358 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006359 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006360 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006361 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006362 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006363 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006364 bool SuppressUserConversions,
6365 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006366 if (!CandidateSet.isNewCandidate(MethodTmpl))
6367 return;
6368
Douglas Gregor97628d62009-08-21 00:16:32 +00006369 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006370 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006371 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006372 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006373 // candidate functions in the usual way.113) A given name can refer to one
6374 // or more function templates and also to a set of overloaded non-template
6375 // functions. In such a case, the candidate functions generated from each
6376 // function template are combined with the set of non-template candidate
6377 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006378 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006379 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006380 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006381 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006382 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006383 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006384 Candidate.FoundDecl = FoundDecl;
6385 Candidate.Function = MethodTmpl->getTemplatedDecl();
6386 Candidate.Viable = false;
6387 Candidate.FailureKind = ovl_fail_bad_deduction;
6388 Candidate.IsSurrogate = false;
6389 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006390 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006391 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006392 Info);
6393 return;
6394 }
Mike Stump11289f42009-09-09 15:08:12 +00006395
Douglas Gregor97628d62009-08-21 00:16:32 +00006396 // Add the function template specialization produced by template argument
6397 // deduction as a candidate.
6398 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006399 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006400 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006401 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006402 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006403 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006404}
6405
Douglas Gregor05155d82009-08-21 23:19:43 +00006406/// \brief Add a C++ function template specialization as a candidate
6407/// in the candidate set, using template argument deduction to produce
6408/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006409void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006410Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006411 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006412 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006413 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006414 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006415 bool SuppressUserConversions,
6416 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006417 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6418 return;
6419
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006420 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006421 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006422 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006423 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006424 // candidate functions in the usual way.113) A given name can refer to one
6425 // or more function templates and also to a set of overloaded non-template
6426 // functions. In such a case, the candidate functions generated from each
6427 // function template are combined with the set of non-template candidate
6428 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006429 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006430 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006431 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006432 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006433 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006434 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006435 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006436 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6437 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006438 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006439 Candidate.IsSurrogate = false;
6440 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006441 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006442 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006443 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006444 return;
6445 }
Mike Stump11289f42009-09-09 15:08:12 +00006446
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006447 // Add the function template specialization produced by template argument
6448 // deduction as a candidate.
6449 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006450 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006451 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006452}
Mike Stump11289f42009-09-09 15:08:12 +00006453
Douglas Gregor4b60a152013-11-07 22:34:54 +00006454/// Determine whether this is an allowable conversion from the result
6455/// of an explicit conversion operator to the expected type, per C++
6456/// [over.match.conv]p1 and [over.match.ref]p1.
6457///
6458/// \param ConvType The return type of the conversion function.
6459///
6460/// \param ToType The type we are converting to.
6461///
6462/// \param AllowObjCPointerConversion Allow a conversion from one
6463/// Objective-C pointer to another.
6464///
6465/// \returns true if the conversion is allowable, false otherwise.
6466static bool isAllowableExplicitConversion(Sema &S,
6467 QualType ConvType, QualType ToType,
6468 bool AllowObjCPointerConversion) {
6469 QualType ToNonRefType = ToType.getNonReferenceType();
6470
6471 // Easy case: the types are the same.
6472 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6473 return true;
6474
6475 // Allow qualification conversions.
6476 bool ObjCLifetimeConversion;
6477 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6478 ObjCLifetimeConversion))
6479 return true;
6480
6481 // If we're not allowed to consider Objective-C pointer conversions,
6482 // we're done.
6483 if (!AllowObjCPointerConversion)
6484 return false;
6485
6486 // Is this an Objective-C pointer conversion?
6487 bool IncompatibleObjC = false;
6488 QualType ConvertedType;
6489 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6490 IncompatibleObjC);
6491}
6492
Douglas Gregora1f013e2008-11-07 22:36:19 +00006493/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006494/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006495/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006496/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006497/// (which may or may not be the same type as the type that the
6498/// conversion function produces).
6499void
6500Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006501 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006502 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006503 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006504 OverloadCandidateSet& CandidateSet,
6505 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006506 assert(!Conversion->getDescribedFunctionTemplate() &&
6507 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006508 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006509 if (!CandidateSet.isNewCandidate(Conversion))
6510 return;
6511
Richard Smith2a7d4812013-05-04 07:00:32 +00006512 // If the conversion function has an undeduced return type, trigger its
6513 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006514 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006515 if (DeduceReturnType(Conversion, From->getExprLoc()))
6516 return;
6517 ConvType = Conversion->getConversionType().getNonReferenceType();
6518 }
6519
Richard Smith089c3162013-09-21 21:55:46 +00006520 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6521 // operator is only a candidate if its return type is the target type or
6522 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006523 if (Conversion->isExplicit() &&
6524 !isAllowableExplicitConversion(*this, ConvType, ToType,
6525 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006526 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
Douglas Gregora1f013e2008-11-07 22:36:19 +00006531 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006532 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006533 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006534 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006535 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006536 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006537 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006538 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006539 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006540 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006541 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006542
Douglas Gregor6affc782010-08-19 15:37:02 +00006543 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544 // For conversion functions, the function is considered to be a member of
6545 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006546 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006547 //
6548 // Determine the implicit conversion sequence for the implicit
6549 // object parameter.
6550 QualType ImplicitParamType = From->getType();
6551 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6552 ImplicitParamType = FromPtrType->getPointeeType();
6553 CXXRecordDecl *ConversionContext
6554 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555
Richard Smith0f59cb32015-12-18 21:45:41 +00006556 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6557 *this, CandidateSet.getLocation(), From->getType(),
6558 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
John McCall0d1da222010-01-12 00:44:57 +00006560 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006561 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006562 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006563 return;
6564 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006565
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006566 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006567 // derived to base as such conversions are given Conversion Rank. They only
6568 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6569 QualType FromCanon
6570 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6571 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006572 if (FromCanon == ToCanon ||
6573 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006574 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006575 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006576 return;
6577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578
Douglas Gregora1f013e2008-11-07 22:36:19 +00006579 // To determine what the conversion from the result of calling the
6580 // conversion function to the type we're eventually trying to
6581 // convert to (ToType), we need to synthesize a call to the
6582 // conversion function and attempt copy initialization from it. This
6583 // makes sure that we get the right semantics with respect to
6584 // lvalues/rvalues and the type. Fortunately, we can allocate this
6585 // call on the stack and we don't need its arguments to be
6586 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006587 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006588 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006589 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6590 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006591 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006592 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006593
Richard Smith48d24642011-07-13 22:53:21 +00006594 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006595 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006596 Candidate.Viable = false;
6597 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6598 return;
6599 }
6600
Richard Smith48d24642011-07-13 22:53:21 +00006601 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006602
Mike Stump11289f42009-09-09 15:08:12 +00006603 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006604 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6605 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006606 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006607 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006608 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006609 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006610 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006611 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006612 /*InOverloadResolution=*/false,
6613 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006614
John McCall0d1da222010-01-12 00:44:57 +00006615 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006616 case ImplicitConversionSequence::StandardConversion:
6617 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006619 // C++ [over.ics.user]p3:
6620 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006622 // shall have exact match rank.
6623 if (Conversion->getPrimaryTemplate() &&
6624 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6625 Candidate.Viable = false;
6626 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006627 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629
Douglas Gregorcba72b12011-01-21 05:18:22 +00006630 // C++0x [dcl.init.ref]p5:
6631 // In the second case, if the reference is an rvalue reference and
6632 // the second standard conversion sequence of the user-defined
6633 // conversion sequence includes an lvalue-to-rvalue conversion, the
6634 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006635 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006636 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6637 Candidate.Viable = false;
6638 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006639 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006640 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006641 break;
6642
6643 case ImplicitConversionSequence::BadConversion:
6644 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006645 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006646 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006647
6648 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006649 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006650 "Can only end up with a standard conversion sequence or failure");
6651 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006652
Craig Topper5fc8fc22014-08-27 06:28:36 +00006653 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006654 Candidate.Viable = false;
6655 Candidate.FailureKind = ovl_fail_enable_if;
6656 Candidate.DeductionFailure.Data = FailedAttr;
6657 return;
6658 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006659}
6660
Douglas Gregor05155d82009-08-21 23:19:43 +00006661/// \brief Adds a conversion function template specialization
6662/// candidate to the overload set, using template argument deduction
6663/// to deduce the template arguments of the conversion function
6664/// template from the type that we are converting to (C++
6665/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006666void
Douglas Gregor05155d82009-08-21 23:19:43 +00006667Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006668 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006669 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006670 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006671 OverloadCandidateSet &CandidateSet,
6672 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006673 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6674 "Only conversion function templates permitted here");
6675
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006676 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6677 return;
6678
Craig Toppere6706e42012-09-19 02:26:47 +00006679 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006680 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006681 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006682 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006683 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006684 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006685 Candidate.FoundDecl = FoundDecl;
6686 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6687 Candidate.Viable = false;
6688 Candidate.FailureKind = ovl_fail_bad_deduction;
6689 Candidate.IsSurrogate = false;
6690 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006691 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006693 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006694 return;
6695 }
Mike Stump11289f42009-09-09 15:08:12 +00006696
Douglas Gregor05155d82009-08-21 23:19:43 +00006697 // Add the conversion function template specialization produced by
6698 // template argument deduction as a candidate.
6699 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006700 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006701 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006702}
6703
Douglas Gregorab7897a2008-11-19 22:57:39 +00006704/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6705/// converts the given @c Object to a function pointer via the
6706/// conversion function @c Conversion, and then attempts to call it
6707/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6708/// the type of function that we'll eventually be calling.
6709void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006710 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006711 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006712 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006713 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006714 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006715 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006716 if (!CandidateSet.isNewCandidate(Conversion))
6717 return;
6718
Douglas Gregor27381f32009-11-23 12:27:39 +00006719 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006720 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006721
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006722 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006723 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006724 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006725 Candidate.Surrogate = Conversion;
6726 Candidate.Viable = true;
6727 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006728 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006729 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006730
6731 // Determine the implicit conversion sequence for the implicit
6732 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006733 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6734 *this, CandidateSet.getLocation(), Object->getType(),
6735 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006736 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006737 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006738 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006739 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006740 return;
6741 }
6742
6743 // The first conversion is actually a user-defined conversion whose
6744 // first conversion is ObjectInit's standard conversion (which is
6745 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006746 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006747 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006748 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006749 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006750 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006751 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006752 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006753 = Candidate.Conversions[0].UserDefined.Before;
6754 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6755
Mike Stump11289f42009-09-09 15:08:12 +00006756 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006757 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006758
6759 // (C++ 13.3.2p2): A candidate function having fewer than m
6760 // parameters is viable only if it has an ellipsis in its parameter
6761 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006762 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006764 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006765 return;
6766 }
6767
6768 // Function types don't have any default arguments, so just check if
6769 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006770 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006771 // Not enough arguments.
6772 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006773 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006774 return;
6775 }
6776
6777 // Determine the implicit conversion sequences for each of the
6778 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006780 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006781 // (C++ 13.3.2p3): for F to be a viable function, there shall
6782 // exist for each argument an implicit conversion sequence
6783 // (13.3.3.1) that converts that argument to the corresponding
6784 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006785 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006786 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006787 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006788 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006789 /*InOverloadResolution=*/false,
6790 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006791 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006792 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006793 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006794 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006795 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006796 }
6797 } else {
6798 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6799 // argument for which there is no corresponding parameter is
6800 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006801 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006802 }
6803 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006804
Craig Topper5fc8fc22014-08-27 06:28:36 +00006805 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006806 Candidate.Viable = false;
6807 Candidate.FailureKind = ovl_fail_enable_if;
6808 Candidate.DeductionFailure.Data = FailedAttr;
6809 return;
6810 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006811}
6812
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006813/// \brief Add overload candidates for overloaded operators that are
6814/// member functions.
6815///
6816/// Add the overloaded operator candidates that are member functions
6817/// for the operator Op that was used in an operator expression such
6818/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6819/// CandidateSet will store the added overload candidates. (C++
6820/// [over.match.oper]).
6821void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6822 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006823 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006824 OverloadCandidateSet& CandidateSet,
6825 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6827
6828 // C++ [over.match.oper]p3:
6829 // For a unary operator @ with an operand of a type whose
6830 // cv-unqualified version is T1, and for a binary operator @ with
6831 // a left operand of a type whose cv-unqualified version is T1 and
6832 // a right operand of a type whose cv-unqualified version is T2,
6833 // three sets of candidate functions, designated member
6834 // candidates, non-member candidates and built-in candidates, are
6835 // constructed as follows:
6836 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006837
Richard Smith0feaf0c2013-04-20 12:41:22 +00006838 // -- If T1 is a complete class type or a class currently being
6839 // defined, the set of member candidates is the result of the
6840 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6841 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006842 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006843 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006844 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006845 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006846 // If the type is neither complete nor being defined, bail out now.
6847 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006848 return;
Mike Stump11289f42009-09-09 15:08:12 +00006849
John McCall27b18f82009-11-17 02:14:36 +00006850 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6851 LookupQualifiedName(Operators, T1Rec->getDecl());
6852 Operators.suppressDiagnostics();
6853
Mike Stump11289f42009-09-09 15:08:12 +00006854 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006855 OperEnd = Operators.end();
6856 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006857 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006858 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006859 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006860 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006861 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006862 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006863 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006864}
6865
Douglas Gregora11693b2008-11-12 17:17:38 +00006866/// AddBuiltinCandidate - Add a candidate for a built-in
6867/// operator. ResultTy and ParamTys are the result and parameter types
6868/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006869/// arguments being passed to the candidate. IsAssignmentOperator
6870/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006871/// operator. NumContextualBoolArguments is the number of arguments
6872/// (at the beginning of the argument list) that will be contextually
6873/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006874void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006875 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006876 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006877 bool IsAssignmentOperator,
6878 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006879 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006880 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006881
Douglas Gregora11693b2008-11-12 17:17:38 +00006882 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006883 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006884 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6885 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006886 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006887 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006888 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006889 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006890 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6891
6892 // Determine the implicit conversion sequences for each of the
6893 // arguments.
6894 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006895 Candidate.ExplicitCallArguments = Args.size();
6896 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006897 // C++ [over.match.oper]p4:
6898 // For the built-in assignment operators, conversions of the
6899 // left operand are restricted as follows:
6900 // -- no temporaries are introduced to hold the left operand, and
6901 // -- no user-defined conversions are applied to the left
6902 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006903 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006904 //
6905 // We block these conversions by turning off user-defined
6906 // conversions, since that is the only way that initialization of
6907 // a reference to a non-class type can occur from something that
6908 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006909 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006910 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006911 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006912 Candidate.Conversions[ArgIdx]
6913 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006914 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006915 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006916 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006917 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006918 /*InOverloadResolution=*/false,
6919 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006920 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006921 }
John McCall0d1da222010-01-12 00:44:57 +00006922 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006923 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006924 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006925 break;
6926 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006927 }
6928}
6929
Craig Toppercd7b0332013-07-01 06:29:40 +00006930namespace {
6931
Douglas Gregora11693b2008-11-12 17:17:38 +00006932/// BuiltinCandidateTypeSet - A set of types that will be used for the
6933/// candidate operator functions for built-in operators (C++
6934/// [over.built]). The types are separated into pointer types and
6935/// enumeration types.
6936class BuiltinCandidateTypeSet {
6937 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006938 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6939 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006940
6941 /// PointerTypes - The set of pointer types that will be used in the
6942 /// built-in candidates.
6943 TypeSet PointerTypes;
6944
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006945 /// MemberPointerTypes - The set of member pointer types that will be
6946 /// used in the built-in candidates.
6947 TypeSet MemberPointerTypes;
6948
Douglas Gregora11693b2008-11-12 17:17:38 +00006949 /// EnumerationTypes - The set of enumeration types that will be
6950 /// used in the built-in candidates.
6951 TypeSet EnumerationTypes;
6952
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006954 /// candidates.
6955 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006956
6957 /// \brief A flag indicating non-record types are viable candidates
6958 bool HasNonRecordTypes;
6959
6960 /// \brief A flag indicating whether either arithmetic or enumeration types
6961 /// were present in the candidate set.
6962 bool HasArithmeticOrEnumeralTypes;
6963
Douglas Gregor80af3132011-05-21 23:15:46 +00006964 /// \brief A flag indicating whether the nullptr type was present in the
6965 /// candidate set.
6966 bool HasNullPtrType;
6967
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006968 /// Sema - The semantic analysis instance where we are building the
6969 /// candidate type set.
6970 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006971
Douglas Gregora11693b2008-11-12 17:17:38 +00006972 /// Context - The AST context in which we will build the type sets.
6973 ASTContext &Context;
6974
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006975 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6976 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006977 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006978
6979public:
6980 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006981 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006982
Mike Stump11289f42009-09-09 15:08:12 +00006983 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006984 : HasNonRecordTypes(false),
6985 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006986 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006987 SemaRef(SemaRef),
6988 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006990 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006991 SourceLocation Loc,
6992 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006993 bool AllowExplicitConversions,
6994 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006995
6996 /// pointer_begin - First pointer type found;
6997 iterator pointer_begin() { return PointerTypes.begin(); }
6998
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006999 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007000 iterator pointer_end() { return PointerTypes.end(); }
7001
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007002 /// member_pointer_begin - First member pointer type found;
7003 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7004
7005 /// member_pointer_end - Past the last member pointer type found;
7006 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7007
Douglas Gregora11693b2008-11-12 17:17:38 +00007008 /// enumeration_begin - First enumeration type found;
7009 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7010
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007011 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007012 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007014 iterator vector_begin() { return VectorTypes.begin(); }
7015 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007016
7017 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7018 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007019 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007020};
7021
Craig Toppercd7b0332013-07-01 06:29:40 +00007022} // end anonymous namespace
7023
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007024/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007025/// the set of pointer types along with any more-qualified variants of
7026/// that type. For example, if @p Ty is "int const *", this routine
7027/// will add "int const *", "int const volatile *", "int const
7028/// restrict *", and "int const volatile restrict *" to the set of
7029/// pointer types. Returns true if the add of @p Ty itself succeeded,
7030/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007031///
7032/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007033bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007034BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7035 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007036
Douglas Gregora11693b2008-11-12 17:17:38 +00007037 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007038 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007039 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007041 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007042 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007043 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007044 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007045 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7046 PointeeTy = PTy->getPointeeType();
7047 buildObjCPtr = true;
7048 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007049 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007050 }
7051
Sebastian Redl4990a632009-11-18 20:39:26 +00007052 // Don't add qualified variants of arrays. For one, they're not allowed
7053 // (the qualifier would sink to the element type), and for another, the
7054 // only overload situation where it matters is subscript or pointer +- int,
7055 // and those shouldn't have qualifier variants anyway.
7056 if (PointeeTy->isArrayType())
7057 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007058
John McCall8ccfcb52009-09-24 19:53:00 +00007059 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007060 bool hasVolatile = VisibleQuals.hasVolatile();
7061 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007062
John McCall8ccfcb52009-09-24 19:53:00 +00007063 // Iterate through all strict supersets of BaseCVR.
7064 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7065 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007066 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007067 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007068
7069 // Skip over restrict if no restrict found anywhere in the types, or if
7070 // the type cannot be restrict-qualified.
7071 if ((CVR & Qualifiers::Restrict) &&
7072 (!hasRestrict ||
7073 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7074 continue;
7075
7076 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007077 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007078
7079 // Build qualified pointer type.
7080 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007081 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007082 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007083 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007084 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7085
7086 // Insert qualified pointer type.
7087 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007088 }
7089
7090 return true;
7091}
7092
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007093/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7094/// to the set of pointer types along with any more-qualified variants of
7095/// that type. For example, if @p Ty is "int const *", this routine
7096/// will add "int const *", "int const volatile *", "int const
7097/// restrict *", and "int const volatile restrict *" to the set of
7098/// pointer types. Returns true if the add of @p Ty itself succeeded,
7099/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007100///
7101/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007102bool
7103BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7104 QualType Ty) {
7105 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007106 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007107 return false;
7108
John McCall8ccfcb52009-09-24 19:53:00 +00007109 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7110 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007111
John McCall8ccfcb52009-09-24 19:53:00 +00007112 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007113 // Don't add qualified variants of arrays. For one, they're not allowed
7114 // (the qualifier would sink to the element type), and for another, the
7115 // only overload situation where it matters is subscript or pointer +- int,
7116 // and those shouldn't have qualifier variants anyway.
7117 if (PointeeTy->isArrayType())
7118 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007119 const Type *ClassTy = PointerTy->getClass();
7120
7121 // Iterate through all strict supersets of the pointee type's CVR
7122 // qualifiers.
7123 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7124 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7125 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007126
John McCall8ccfcb52009-09-24 19:53:00 +00007127 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007128 MemberPointerTypes.insert(
7129 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007130 }
7131
7132 return true;
7133}
7134
Douglas Gregora11693b2008-11-12 17:17:38 +00007135/// AddTypesConvertedFrom - Add each of the types to which the type @p
7136/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007137/// primarily interested in pointer types and enumeration types. We also
7138/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007139/// AllowUserConversions is true if we should look at the conversion
7140/// functions of a class type, and AllowExplicitConversions if we
7141/// should also include the explicit conversion functions of a class
7142/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007143void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007144BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007145 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007146 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007147 bool AllowExplicitConversions,
7148 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007149 // Only deal with canonical types.
7150 Ty = Context.getCanonicalType(Ty);
7151
7152 // Look through reference types; they aren't part of the type of an
7153 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007154 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007155 Ty = RefTy->getPointeeType();
7156
John McCall33ddac02011-01-19 10:06:00 +00007157 // If we're dealing with an array type, decay to the pointer.
7158 if (Ty->isArrayType())
7159 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7160
7161 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007162 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007163
Chandler Carruth00a38332010-12-13 01:44:01 +00007164 // Flag if we ever add a non-record type.
7165 const RecordType *TyRec = Ty->getAs<RecordType>();
7166 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7167
Chandler Carruth00a38332010-12-13 01:44:01 +00007168 // Flag if we encounter an arithmetic type.
7169 HasArithmeticOrEnumeralTypes =
7170 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7171
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007172 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7173 PointerTypes.insert(Ty);
7174 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007175 // Insert our type, and its more-qualified variants, into the set
7176 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007177 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007178 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007179 } else if (Ty->isMemberPointerType()) {
7180 // Member pointers are far easier, since the pointee can't be converted.
7181 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7182 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007183 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007184 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007185 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007186 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007187 // We treat vector types as arithmetic types in many contexts as an
7188 // extension.
7189 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007190 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007191 } else if (Ty->isNullPtrType()) {
7192 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007193 } else if (AllowUserConversions && TyRec) {
7194 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007195 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007196 return;
Mike Stump11289f42009-09-09 15:08:12 +00007197
Chandler Carruth00a38332010-12-13 01:44:01 +00007198 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007199 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007200 if (isa<UsingShadowDecl>(D))
7201 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007202
Chandler Carruth00a38332010-12-13 01:44:01 +00007203 // Skip conversion function templates; they don't tell us anything
7204 // about which builtin types we can convert to.
7205 if (isa<FunctionTemplateDecl>(D))
7206 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007207
Chandler Carruth00a38332010-12-13 01:44:01 +00007208 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7209 if (AllowExplicitConversions || !Conv->isExplicit()) {
7210 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7211 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007212 }
7213 }
7214 }
7215}
7216
Douglas Gregor84605ae2009-08-24 13:43:27 +00007217/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7218/// the volatile- and non-volatile-qualified assignment operators for the
7219/// given type to the candidate set.
7220static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7221 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007222 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007223 OverloadCandidateSet &CandidateSet) {
7224 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007225
Douglas Gregor84605ae2009-08-24 13:43:27 +00007226 // T& operator=(T&, T)
7227 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7228 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007229 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007230 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007231
Douglas Gregor84605ae2009-08-24 13:43:27 +00007232 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7233 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007234 ParamTypes[0]
7235 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007236 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007238 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007239 }
7240}
Mike Stump11289f42009-09-09 15:08:12 +00007241
Sebastian Redl1054fae2009-10-25 17:03:50 +00007242/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7243/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007244static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7245 Qualifiers VRQuals;
7246 const RecordType *TyRec;
7247 if (const MemberPointerType *RHSMPType =
7248 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007249 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007250 else
7251 TyRec = ArgExpr->getType()->getAs<RecordType>();
7252 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007253 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007254 VRQuals.addVolatile();
7255 VRQuals.addRestrict();
7256 return VRQuals;
7257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007259 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007260 if (!ClassDecl->hasDefinition())
7261 return VRQuals;
7262
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007263 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007264 if (isa<UsingShadowDecl>(D))
7265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7266 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007267 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7268 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7269 CanTy = ResTypeRef->getPointeeType();
7270 // Need to go down the pointer/mempointer chain and add qualifiers
7271 // as see them.
7272 bool done = false;
7273 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007274 if (CanTy.isRestrictQualified())
7275 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007276 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7277 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007279 CanTy->getAs<MemberPointerType>())
7280 CanTy = ResTypeMPtr->getPointeeType();
7281 else
7282 done = true;
7283 if (CanTy.isVolatileQualified())
7284 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007285 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7286 return VRQuals;
7287 }
7288 }
7289 }
7290 return VRQuals;
7291}
John McCall52872982010-11-13 05:51:15 +00007292
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007293namespace {
John McCall52872982010-11-13 05:51:15 +00007294
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007295/// \brief Helper class to manage the addition of builtin operator overload
7296/// candidates. It provides shared state and utility methods used throughout
7297/// the process, as well as a helper method to add each group of builtin
7298/// operator overloads from the standard to a candidate set.
7299class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007300 // Common instance state available to all overload candidate addition methods.
7301 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007302 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007303 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007304 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007305 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007306 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007307
Chandler Carruthc6586e52010-12-12 10:35:00 +00007308 // Define some constants used to index and iterate over the arithemetic types
7309 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007310 // The "promoted arithmetic types" are the arithmetic
7311 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007312 static const unsigned FirstIntegralType = 4;
7313 static const unsigned LastIntegralType = 21;
7314 static const unsigned FirstPromotedIntegralType = 4,
7315 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007316 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007317 LastPromotedArithmeticType = 12;
7318 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007319
Chandler Carruthc6586e52010-12-12 10:35:00 +00007320 /// \brief Get the canonical type for a given arithmetic type index.
7321 CanQualType getArithmeticType(unsigned index) {
7322 assert(index < NumArithmeticTypes);
7323 static CanQualType ASTContext::* const
7324 ArithmeticTypes[NumArithmeticTypes] = {
7325 // Start of promoted types.
7326 &ASTContext::FloatTy,
7327 &ASTContext::DoubleTy,
7328 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007329 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007330
Chandler Carruthc6586e52010-12-12 10:35:00 +00007331 // Start of integral types.
7332 &ASTContext::IntTy,
7333 &ASTContext::LongTy,
7334 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007335 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007336 &ASTContext::UnsignedIntTy,
7337 &ASTContext::UnsignedLongTy,
7338 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007339 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007340 // End of promoted types.
7341
7342 &ASTContext::BoolTy,
7343 &ASTContext::CharTy,
7344 &ASTContext::WCharTy,
7345 &ASTContext::Char16Ty,
7346 &ASTContext::Char32Ty,
7347 &ASTContext::SignedCharTy,
7348 &ASTContext::ShortTy,
7349 &ASTContext::UnsignedCharTy,
7350 &ASTContext::UnsignedShortTy,
7351 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007352 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007353 };
7354 return S.Context.*ArithmeticTypes[index];
7355 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007357 /// \brief Gets the canonical type resulting from the usual arithemetic
7358 /// converions for the given arithmetic types.
7359 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7360 // Accelerator table for performing the usual arithmetic conversions.
7361 // The rules are basically:
7362 // - if either is floating-point, use the wider floating-point
7363 // - if same signedness, use the higher rank
7364 // - if same size, use unsigned of the higher rank
7365 // - use the larger type
7366 // These rules, together with the axiom that higher ranks are
7367 // never smaller, are sufficient to precompute all of these results
7368 // *except* when dealing with signed types of higher rank.
7369 // (we could precompute SLL x UI for all known platforms, but it's
7370 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007371 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007372 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007373 Dep=-1,
7374 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007375 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007376 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007377 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007378/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7379/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7380/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7381/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7382/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7383/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7384/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7385/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7386/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7387/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7388/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007389 };
7390
7391 assert(L < LastPromotedArithmeticType);
7392 assert(R < LastPromotedArithmeticType);
7393 int Idx = ConversionsTable[L][R];
7394
7395 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007396 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007397
7398 // Slow path: we need to compare widths.
7399 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007400 CanQualType LT = getArithmeticType(L),
7401 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007402 unsigned LW = S.Context.getIntWidth(LT),
7403 RW = S.Context.getIntWidth(RT);
7404
7405 // If they're different widths, use the signed type.
7406 if (LW > RW) return LT;
7407 else if (LW < RW) return RT;
7408
7409 // Otherwise, use the unsigned type of the signed type's rank.
7410 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7411 assert(L == SLL || R == SLL);
7412 return S.Context.UnsignedLongLongTy;
7413 }
7414
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007415 /// \brief Helper method to factor out the common pattern of adding overloads
7416 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007417 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007418 bool HasVolatile,
7419 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007420 QualType ParamTypes[2] = {
7421 S.Context.getLValueReferenceType(CandidateTy),
7422 S.Context.IntTy
7423 };
7424
7425 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007426 if (Args.size() == 1)
7427 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 else
Richard Smithe54c3072013-05-05 15:51:06 +00007429 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007430
7431 // Use a heuristic to reduce number of builtin candidates in the set:
7432 // add volatile version only if there are conversions to a volatile type.
7433 if (HasVolatile) {
7434 ParamTypes[0] =
7435 S.Context.getLValueReferenceType(
7436 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007437 if (Args.size() == 1)
7438 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007439 else
Richard Smithe54c3072013-05-05 15:51:06 +00007440 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007441 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007442
7443 // Add restrict version only if there are conversions to a restrict type
7444 // and our candidate type is a non-restrict-qualified pointer.
7445 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7446 !CandidateTy.isRestrictQualified()) {
7447 ParamTypes[0]
7448 = S.Context.getLValueReferenceType(
7449 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007450 if (Args.size() == 1)
7451 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007452 else
Richard Smithe54c3072013-05-05 15:51:06 +00007453 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007454
7455 if (HasVolatile) {
7456 ParamTypes[0]
7457 = S.Context.getLValueReferenceType(
7458 S.Context.getCVRQualifiedType(CandidateTy,
7459 (Qualifiers::Volatile |
7460 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007461 if (Args.size() == 1)
7462 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007463 else
Richard Smithe54c3072013-05-05 15:51:06 +00007464 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007465 }
7466 }
7467
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007468 }
7469
7470public:
7471 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007472 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007473 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007474 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007475 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007477 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007478 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007479 HasArithmeticOrEnumeralCandidateType(
7480 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007481 CandidateTypes(CandidateTypes),
7482 CandidateSet(CandidateSet) {
7483 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007484 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007485 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007486 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007487 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007488 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007489 assert(getArithmeticType(FirstPromotedArithmeticType)
7490 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007492 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007493 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007494 "Invalid last promoted arithmetic type");
7495 }
7496
7497 // C++ [over.built]p3:
7498 //
7499 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7500 // is either volatile or empty, there exist candidate operator
7501 // functions of the form
7502 //
7503 // VQ T& operator++(VQ T&);
7504 // T operator++(VQ T&, int);
7505 //
7506 // C++ [over.built]p4:
7507 //
7508 // For every pair (T, VQ), where T is an arithmetic type other
7509 // than bool, and VQ is either volatile or empty, there exist
7510 // candidate operator functions of the form
7511 //
7512 // VQ T& operator--(VQ T&);
7513 // T operator--(VQ T&, int);
7514 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007515 if (!HasArithmeticOrEnumeralCandidateType)
7516 return;
7517
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007518 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7519 Arith < NumArithmeticTypes; ++Arith) {
7520 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007521 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007522 VisibleTypeConversionsQuals.hasVolatile(),
7523 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 }
7525 }
7526
7527 // C++ [over.built]p5:
7528 //
7529 // For every pair (T, VQ), where T is a cv-qualified or
7530 // cv-unqualified object type, and VQ is either volatile or
7531 // empty, there exist candidate operator functions of the form
7532 //
7533 // T*VQ& operator++(T*VQ&);
7534 // T*VQ& operator--(T*VQ&);
7535 // T* operator++(T*VQ&, int);
7536 // T* operator--(T*VQ&, int);
7537 void addPlusPlusMinusMinusPointerOverloads() {
7538 for (BuiltinCandidateTypeSet::iterator
7539 Ptr = CandidateTypes[0].pointer_begin(),
7540 PtrEnd = CandidateTypes[0].pointer_end();
7541 Ptr != PtrEnd; ++Ptr) {
7542 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007543 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007544 continue;
7545
7546 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007547 (!(*Ptr).isVolatileQualified() &&
7548 VisibleTypeConversionsQuals.hasVolatile()),
7549 (!(*Ptr).isRestrictQualified() &&
7550 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007551 }
7552 }
7553
7554 // C++ [over.built]p6:
7555 // For every cv-qualified or cv-unqualified object type T, there
7556 // exist candidate operator functions of the form
7557 //
7558 // T& operator*(T*);
7559 //
7560 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007562 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007563 // T& operator*(T*);
7564 void addUnaryStarPointerOverloads() {
7565 for (BuiltinCandidateTypeSet::iterator
7566 Ptr = CandidateTypes[0].pointer_begin(),
7567 PtrEnd = CandidateTypes[0].pointer_end();
7568 Ptr != PtrEnd; ++Ptr) {
7569 QualType ParamTy = *Ptr;
7570 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007571 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7572 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007573
Douglas Gregor02824322011-01-26 19:30:28 +00007574 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7575 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7576 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007577
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007578 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007579 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580 }
7581 }
7582
7583 // C++ [over.built]p9:
7584 // For every promoted arithmetic type T, there exist candidate
7585 // operator functions of the form
7586 //
7587 // T operator+(T);
7588 // T operator-(T);
7589 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007590 if (!HasArithmeticOrEnumeralCandidateType)
7591 return;
7592
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007593 for (unsigned Arith = FirstPromotedArithmeticType;
7594 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007595 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007596 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007597 }
7598
7599 // Extension: We also add these operators for vector types.
7600 for (BuiltinCandidateTypeSet::iterator
7601 Vec = CandidateTypes[0].vector_begin(),
7602 VecEnd = CandidateTypes[0].vector_end();
7603 Vec != VecEnd; ++Vec) {
7604 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007605 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007606 }
7607 }
7608
7609 // C++ [over.built]p8:
7610 // For every type T, there exist candidate operator functions of
7611 // the form
7612 //
7613 // T* operator+(T*);
7614 void addUnaryPlusPointerOverloads() {
7615 for (BuiltinCandidateTypeSet::iterator
7616 Ptr = CandidateTypes[0].pointer_begin(),
7617 PtrEnd = CandidateTypes[0].pointer_end();
7618 Ptr != PtrEnd; ++Ptr) {
7619 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007620 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 }
7622 }
7623
7624 // C++ [over.built]p10:
7625 // For every promoted integral type T, there exist candidate
7626 // operator functions of the form
7627 //
7628 // T operator~(T);
7629 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007630 if (!HasArithmeticOrEnumeralCandidateType)
7631 return;
7632
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007633 for (unsigned Int = FirstPromotedIntegralType;
7634 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007635 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007636 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007637 }
7638
7639 // Extension: We also add this operator for vector types.
7640 for (BuiltinCandidateTypeSet::iterator
7641 Vec = CandidateTypes[0].vector_begin(),
7642 VecEnd = CandidateTypes[0].vector_end();
7643 Vec != VecEnd; ++Vec) {
7644 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007645 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 }
7647 }
7648
7649 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007650 // For every pointer to member type T or type std::nullptr_t, there
7651 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 //
7653 // bool operator==(T,T);
7654 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007655 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007656 /// Set of (canonical) types that we've already handled.
7657 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7658
Richard Smithe54c3072013-05-05 15:51:06 +00007659 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660 for (BuiltinCandidateTypeSet::iterator
7661 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7662 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7663 MemPtr != MemPtrEnd;
7664 ++MemPtr) {
7665 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007666 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 continue;
7668
7669 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007670 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007671 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007672
7673 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7674 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7675 if (AddedTypes.insert(NullPtrTy).second) {
7676 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7677 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7678 CandidateSet);
7679 }
7680 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007681 }
7682 }
7683
7684 // C++ [over.built]p15:
7685 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007686 // For every T, where T is an enumeration type or a pointer type,
7687 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007688 //
7689 // bool operator<(T, T);
7690 // bool operator>(T, T);
7691 // bool operator<=(T, T);
7692 // bool operator>=(T, T);
7693 // bool operator==(T, T);
7694 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007695 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007696 // C++ [over.match.oper]p3:
7697 // [...]the built-in candidates include all of the candidate operator
7698 // functions defined in 13.6 that, compared to the given operator, [...]
7699 // do not have the same parameter-type-list as any non-template non-member
7700 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007701 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007702 // Note that in practice, this only affects enumeration types because there
7703 // aren't any built-in candidates of record type, and a user-defined operator
7704 // must have an operand of record or enumeration type. Also, the only other
7705 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007706 // cannot be overloaded for enumeration types, so this is the only place
7707 // where we must suppress candidates like this.
7708 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7709 UserDefinedBinaryOperators;
7710
Richard Smithe54c3072013-05-05 15:51:06 +00007711 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007712 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7713 CandidateTypes[ArgIdx].enumeration_end()) {
7714 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7715 CEnd = CandidateSet.end();
7716 C != CEnd; ++C) {
7717 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7718 continue;
7719
Eli Friedman14f082b2012-09-18 21:52:24 +00007720 if (C->Function->isFunctionTemplateSpecialization())
7721 continue;
7722
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007723 QualType FirstParamType =
7724 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7725 QualType SecondParamType =
7726 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7727
7728 // Skip if either parameter isn't of enumeral type.
7729 if (!FirstParamType->isEnumeralType() ||
7730 !SecondParamType->isEnumeralType())
7731 continue;
7732
7733 // Add this operator to the set of known user-defined operators.
7734 UserDefinedBinaryOperators.insert(
7735 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7736 S.Context.getCanonicalType(SecondParamType)));
7737 }
7738 }
7739 }
7740
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007741 /// Set of (canonical) types that we've already handled.
7742 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7743
Richard Smithe54c3072013-05-05 15:51:06 +00007744 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007745 for (BuiltinCandidateTypeSet::iterator
7746 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7747 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7748 Ptr != PtrEnd; ++Ptr) {
7749 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007750 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007751 continue;
7752
7753 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007754 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007755 }
7756 for (BuiltinCandidateTypeSet::iterator
7757 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7758 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7759 Enum != EnumEnd; ++Enum) {
7760 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7761
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007762 // Don't add the same builtin candidate twice, or if a user defined
7763 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007764 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007765 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7766 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007767 continue;
7768
7769 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007770 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007771 }
7772 }
7773 }
7774
7775 // C++ [over.built]p13:
7776 //
7777 // For every cv-qualified or cv-unqualified object type T
7778 // there exist candidate operator functions of the form
7779 //
7780 // T* operator+(T*, ptrdiff_t);
7781 // T& operator[](T*, ptrdiff_t); [BELOW]
7782 // T* operator-(T*, ptrdiff_t);
7783 // T* operator+(ptrdiff_t, T*);
7784 // T& operator[](ptrdiff_t, T*); [BELOW]
7785 //
7786 // C++ [over.built]p14:
7787 //
7788 // For every T, where T is a pointer to object type, there
7789 // exist candidate operator functions of the form
7790 //
7791 // ptrdiff_t operator-(T, T);
7792 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7793 /// Set of (canonical) types that we've already handled.
7794 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7795
7796 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007797 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 S.Context.getPointerDiffType(),
7799 S.Context.getPointerDiffType(),
7800 };
7801 for (BuiltinCandidateTypeSet::iterator
7802 Ptr = CandidateTypes[Arg].pointer_begin(),
7803 PtrEnd = CandidateTypes[Arg].pointer_end();
7804 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007805 QualType PointeeTy = (*Ptr)->getPointeeType();
7806 if (!PointeeTy->isObjectType())
7807 continue;
7808
Eric Christopher9207a522015-08-21 16:24:01 +00007809 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 if (Arg == 0 || Op == OO_Plus) {
7811 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7812 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007813 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007814 }
7815 if (Op == OO_Minus) {
7816 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007817 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007818 continue;
7819
7820 QualType ParamTypes[2] = { *Ptr, *Ptr };
7821 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007822 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007823 }
7824 }
7825 }
7826 }
7827
7828 // C++ [over.built]p12:
7829 //
7830 // For every pair of promoted arithmetic types L and R, there
7831 // exist candidate operator functions of the form
7832 //
7833 // LR operator*(L, R);
7834 // LR operator/(L, R);
7835 // LR operator+(L, R);
7836 // LR operator-(L, R);
7837 // bool operator<(L, R);
7838 // bool operator>(L, R);
7839 // bool operator<=(L, R);
7840 // bool operator>=(L, R);
7841 // bool operator==(L, R);
7842 // bool operator!=(L, R);
7843 //
7844 // where LR is the result of the usual arithmetic conversions
7845 // between types L and R.
7846 //
7847 // C++ [over.built]p24:
7848 //
7849 // For every pair of promoted arithmetic types L and R, there exist
7850 // candidate operator functions of the form
7851 //
7852 // LR operator?(bool, L, R);
7853 //
7854 // where LR is the result of the usual arithmetic conversions
7855 // between types L and R.
7856 // Our candidates ignore the first parameter.
7857 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007858 if (!HasArithmeticOrEnumeralCandidateType)
7859 return;
7860
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007861 for (unsigned Left = FirstPromotedArithmeticType;
7862 Left < LastPromotedArithmeticType; ++Left) {
7863 for (unsigned Right = FirstPromotedArithmeticType;
7864 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007865 QualType LandR[2] = { getArithmeticType(Left),
7866 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007867 QualType Result =
7868 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007869 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007870 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 }
7872 }
7873
7874 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7875 // conditional operator for vector types.
7876 for (BuiltinCandidateTypeSet::iterator
7877 Vec1 = CandidateTypes[0].vector_begin(),
7878 Vec1End = CandidateTypes[0].vector_end();
7879 Vec1 != Vec1End; ++Vec1) {
7880 for (BuiltinCandidateTypeSet::iterator
7881 Vec2 = CandidateTypes[1].vector_begin(),
7882 Vec2End = CandidateTypes[1].vector_end();
7883 Vec2 != Vec2End; ++Vec2) {
7884 QualType LandR[2] = { *Vec1, *Vec2 };
7885 QualType Result = S.Context.BoolTy;
7886 if (!isComparison) {
7887 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7888 Result = *Vec1;
7889 else
7890 Result = *Vec2;
7891 }
7892
Richard Smithe54c3072013-05-05 15:51:06 +00007893 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007894 }
7895 }
7896 }
7897
7898 // C++ [over.built]p17:
7899 //
7900 // For every pair of promoted integral types L and R, there
7901 // exist candidate operator functions of the form
7902 //
7903 // LR operator%(L, R);
7904 // LR operator&(L, R);
7905 // LR operator^(L, R);
7906 // LR operator|(L, R);
7907 // L operator<<(L, R);
7908 // L operator>>(L, R);
7909 //
7910 // where LR is the result of the usual arithmetic conversions
7911 // between types L and R.
7912 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007913 if (!HasArithmeticOrEnumeralCandidateType)
7914 return;
7915
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007916 for (unsigned Left = FirstPromotedIntegralType;
7917 Left < LastPromotedIntegralType; ++Left) {
7918 for (unsigned Right = FirstPromotedIntegralType;
7919 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007920 QualType LandR[2] = { getArithmeticType(Left),
7921 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7923 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007924 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007925 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 }
7927 }
7928 }
7929
7930 // C++ [over.built]p20:
7931 //
7932 // For every pair (T, VQ), where T is an enumeration or
7933 // pointer to member type and VQ is either volatile or
7934 // empty, there exist candidate operator functions of the form
7935 //
7936 // VQ T& operator=(VQ T&, T);
7937 void addAssignmentMemberPointerOrEnumeralOverloads() {
7938 /// Set of (canonical) types that we've already handled.
7939 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7940
7941 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7942 for (BuiltinCandidateTypeSet::iterator
7943 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7944 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7945 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007946 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947 continue;
7948
Richard Smithe54c3072013-05-05 15:51:06 +00007949 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 }
7951
7952 for (BuiltinCandidateTypeSet::iterator
7953 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7954 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7955 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007956 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007957 continue;
7958
Richard Smithe54c3072013-05-05 15:51:06 +00007959 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007960 }
7961 }
7962 }
7963
7964 // C++ [over.built]p19:
7965 //
7966 // For every pair (T, VQ), where T is any type and VQ is either
7967 // volatile or empty, there exist candidate operator functions
7968 // of the form
7969 //
7970 // T*VQ& operator=(T*VQ&, T*);
7971 //
7972 // C++ [over.built]p21:
7973 //
7974 // For every pair (T, VQ), where T is a cv-qualified or
7975 // cv-unqualified object type and VQ is either volatile or
7976 // empty, there exist candidate operator functions of the form
7977 //
7978 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7979 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7980 void addAssignmentPointerOverloads(bool isEqualOp) {
7981 /// Set of (canonical) types that we've already handled.
7982 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7983
7984 for (BuiltinCandidateTypeSet::iterator
7985 Ptr = CandidateTypes[0].pointer_begin(),
7986 PtrEnd = CandidateTypes[0].pointer_end();
7987 Ptr != PtrEnd; ++Ptr) {
7988 // If this is operator=, keep track of the builtin candidates we added.
7989 if (isEqualOp)
7990 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007991 else if (!(*Ptr)->getPointeeType()->isObjectType())
7992 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993
7994 // non-volatile version
7995 QualType ParamTypes[2] = {
7996 S.Context.getLValueReferenceType(*Ptr),
7997 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7998 };
Richard Smithe54c3072013-05-05 15:51:06 +00007999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008000 /*IsAssigmentOperator=*/ isEqualOp);
8001
Douglas Gregor5bee2582012-06-04 00:15:09 +00008002 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8003 VisibleTypeConversionsQuals.hasVolatile();
8004 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008005 // volatile version
8006 ParamTypes[0] =
8007 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008009 /*IsAssigmentOperator=*/isEqualOp);
8010 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008011
8012 if (!(*Ptr).isRestrictQualified() &&
8013 VisibleTypeConversionsQuals.hasRestrict()) {
8014 // restrict version
8015 ParamTypes[0]
8016 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008018 /*IsAssigmentOperator=*/isEqualOp);
8019
8020 if (NeedVolatile) {
8021 // volatile restrict version
8022 ParamTypes[0]
8023 = S.Context.getLValueReferenceType(
8024 S.Context.getCVRQualifiedType(*Ptr,
8025 (Qualifiers::Volatile |
8026 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008027 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008028 /*IsAssigmentOperator=*/isEqualOp);
8029 }
8030 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008031 }
8032
8033 if (isEqualOp) {
8034 for (BuiltinCandidateTypeSet::iterator
8035 Ptr = CandidateTypes[1].pointer_begin(),
8036 PtrEnd = CandidateTypes[1].pointer_end();
8037 Ptr != PtrEnd; ++Ptr) {
8038 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008039 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 continue;
8041
Chandler Carruth8e543b32010-12-12 08:17:55 +00008042 QualType ParamTypes[2] = {
8043 S.Context.getLValueReferenceType(*Ptr),
8044 *Ptr,
8045 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046
8047 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008049 /*IsAssigmentOperator=*/true);
8050
Douglas Gregor5bee2582012-06-04 00:15:09 +00008051 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8052 VisibleTypeConversionsQuals.hasVolatile();
8053 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 // volatile version
8055 ParamTypes[0] =
8056 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008057 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8058 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008060
8061 if (!(*Ptr).isRestrictQualified() &&
8062 VisibleTypeConversionsQuals.hasRestrict()) {
8063 // restrict version
8064 ParamTypes[0]
8065 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8067 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008068
8069 if (NeedVolatile) {
8070 // volatile restrict version
8071 ParamTypes[0]
8072 = S.Context.getLValueReferenceType(
8073 S.Context.getCVRQualifiedType(*Ptr,
8074 (Qualifiers::Volatile |
8075 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008076 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8077 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008078 }
8079 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 }
8081 }
8082 }
8083
8084 // C++ [over.built]p18:
8085 //
8086 // For every triple (L, VQ, R), where L is an arithmetic type,
8087 // VQ is either volatile or empty, and R is a promoted
8088 // arithmetic type, there exist candidate operator functions of
8089 // the form
8090 //
8091 // VQ L& operator=(VQ L&, R);
8092 // VQ L& operator*=(VQ L&, R);
8093 // VQ L& operator/=(VQ L&, R);
8094 // VQ L& operator+=(VQ L&, R);
8095 // VQ L& operator-=(VQ L&, R);
8096 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008097 if (!HasArithmeticOrEnumeralCandidateType)
8098 return;
8099
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008100 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8101 for (unsigned Right = FirstPromotedArithmeticType;
8102 Right < LastPromotedArithmeticType; ++Right) {
8103 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008104 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105
8106 // Add this built-in operator as a candidate (VQ is empty).
8107 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008108 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008110 /*IsAssigmentOperator=*/isEqualOp);
8111
8112 // Add this built-in operator as a candidate (VQ is 'volatile').
8113 if (VisibleTypeConversionsQuals.hasVolatile()) {
8114 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008115 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008116 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008117 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118 /*IsAssigmentOperator=*/isEqualOp);
8119 }
8120 }
8121 }
8122
8123 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8124 for (BuiltinCandidateTypeSet::iterator
8125 Vec1 = CandidateTypes[0].vector_begin(),
8126 Vec1End = CandidateTypes[0].vector_end();
8127 Vec1 != Vec1End; ++Vec1) {
8128 for (BuiltinCandidateTypeSet::iterator
8129 Vec2 = CandidateTypes[1].vector_begin(),
8130 Vec2End = CandidateTypes[1].vector_end();
8131 Vec2 != Vec2End; ++Vec2) {
8132 QualType ParamTypes[2];
8133 ParamTypes[1] = *Vec2;
8134 // Add this built-in operator as a candidate (VQ is empty).
8135 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008136 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 /*IsAssigmentOperator=*/isEqualOp);
8138
8139 // Add this built-in operator as a candidate (VQ is 'volatile').
8140 if (VisibleTypeConversionsQuals.hasVolatile()) {
8141 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8142 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008143 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008144 /*IsAssigmentOperator=*/isEqualOp);
8145 }
8146 }
8147 }
8148 }
8149
8150 // C++ [over.built]p22:
8151 //
8152 // For every triple (L, VQ, R), where L is an integral type, VQ
8153 // is either volatile or empty, and R is a promoted integral
8154 // type, there exist candidate operator functions of the form
8155 //
8156 // VQ L& operator%=(VQ L&, R);
8157 // VQ L& operator<<=(VQ L&, R);
8158 // VQ L& operator>>=(VQ L&, R);
8159 // VQ L& operator&=(VQ L&, R);
8160 // VQ L& operator^=(VQ L&, R);
8161 // VQ L& operator|=(VQ L&, R);
8162 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008163 if (!HasArithmeticOrEnumeralCandidateType)
8164 return;
8165
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008166 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8167 for (unsigned Right = FirstPromotedIntegralType;
8168 Right < LastPromotedIntegralType; ++Right) {
8169 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008170 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008171
8172 // Add this built-in operator as a candidate (VQ is empty).
8173 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008174 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008176 if (VisibleTypeConversionsQuals.hasVolatile()) {
8177 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008178 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008179 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8180 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008182 }
8183 }
8184 }
8185 }
8186
8187 // C++ [over.operator]p23:
8188 //
8189 // There also exist candidate operator functions of the form
8190 //
8191 // bool operator!(bool);
8192 // bool operator&&(bool, bool);
8193 // bool operator||(bool, bool);
8194 void addExclaimOverload() {
8195 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008196 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008197 /*IsAssignmentOperator=*/false,
8198 /*NumContextualBoolArguments=*/1);
8199 }
8200 void addAmpAmpOrPipePipeOverload() {
8201 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008202 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008203 /*IsAssignmentOperator=*/false,
8204 /*NumContextualBoolArguments=*/2);
8205 }
8206
8207 // C++ [over.built]p13:
8208 //
8209 // For every cv-qualified or cv-unqualified object type T there
8210 // exist candidate operator functions of the form
8211 //
8212 // T* operator+(T*, ptrdiff_t); [ABOVE]
8213 // T& operator[](T*, ptrdiff_t);
8214 // T* operator-(T*, ptrdiff_t); [ABOVE]
8215 // T* operator+(ptrdiff_t, T*); [ABOVE]
8216 // T& operator[](ptrdiff_t, T*);
8217 void addSubscriptOverloads() {
8218 for (BuiltinCandidateTypeSet::iterator
8219 Ptr = CandidateTypes[0].pointer_begin(),
8220 PtrEnd = CandidateTypes[0].pointer_end();
8221 Ptr != PtrEnd; ++Ptr) {
8222 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8223 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008224 if (!PointeeType->isObjectType())
8225 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008226
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008227 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8228
8229 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008230 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008231 }
8232
8233 for (BuiltinCandidateTypeSet::iterator
8234 Ptr = CandidateTypes[1].pointer_begin(),
8235 PtrEnd = CandidateTypes[1].pointer_end();
8236 Ptr != PtrEnd; ++Ptr) {
8237 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8238 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008239 if (!PointeeType->isObjectType())
8240 continue;
8241
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008242 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8243
8244 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008245 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008246 }
8247 }
8248
8249 // C++ [over.built]p11:
8250 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8251 // C1 is the same type as C2 or is a derived class of C2, T is an object
8252 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8253 // there exist candidate operator functions of the form
8254 //
8255 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8256 //
8257 // where CV12 is the union of CV1 and CV2.
8258 void addArrowStarOverloads() {
8259 for (BuiltinCandidateTypeSet::iterator
8260 Ptr = CandidateTypes[0].pointer_begin(),
8261 PtrEnd = CandidateTypes[0].pointer_end();
8262 Ptr != PtrEnd; ++Ptr) {
8263 QualType C1Ty = (*Ptr);
8264 QualType C1;
8265 QualifierCollector Q1;
8266 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8267 if (!isa<RecordType>(C1))
8268 continue;
8269 // heuristic to reduce number of builtin candidates in the set.
8270 // Add volatile/restrict version only if there are conversions to a
8271 // volatile/restrict type.
8272 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8273 continue;
8274 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8275 continue;
8276 for (BuiltinCandidateTypeSet::iterator
8277 MemPtr = CandidateTypes[1].member_pointer_begin(),
8278 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8279 MemPtr != MemPtrEnd; ++MemPtr) {
8280 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8281 QualType C2 = QualType(mptr->getClass(), 0);
8282 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008283 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284 break;
8285 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8286 // build CV12 T&
8287 QualType T = mptr->getPointeeType();
8288 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8289 T.isVolatileQualified())
8290 continue;
8291 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8292 T.isRestrictQualified())
8293 continue;
8294 T = Q1.apply(S.Context, T);
8295 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008296 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008297 }
8298 }
8299 }
8300
8301 // Note that we don't consider the first argument, since it has been
8302 // contextually converted to bool long ago. The candidates below are
8303 // therefore added as binary.
8304 //
8305 // C++ [over.built]p25:
8306 // For every type T, where T is a pointer, pointer-to-member, or scoped
8307 // enumeration type, there exist candidate operator functions of the form
8308 //
8309 // T operator?(bool, T, T);
8310 //
8311 void addConditionalOperatorOverloads() {
8312 /// Set of (canonical) types that we've already handled.
8313 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8314
8315 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8316 for (BuiltinCandidateTypeSet::iterator
8317 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8318 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8319 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008320 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008321 continue;
8322
8323 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008324 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325 }
8326
8327 for (BuiltinCandidateTypeSet::iterator
8328 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8329 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8330 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008331 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 continue;
8333
8334 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008335 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008336 }
8337
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008338 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008339 for (BuiltinCandidateTypeSet::iterator
8340 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8341 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8342 Enum != EnumEnd; ++Enum) {
8343 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8344 continue;
8345
David Blaikie82e95a32014-11-19 07:49:47 +00008346 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008347 continue;
8348
8349 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008350 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008351 }
8352 }
8353 }
8354 }
8355};
8356
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008357} // end anonymous namespace
8358
8359/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8360/// operator overloads to the candidate set (C++ [over.built]), based
8361/// on the operator @p Op and the arguments given. For example, if the
8362/// operator is a binary '+', this routine might add "int
8363/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008364void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8365 SourceLocation OpLoc,
8366 ArrayRef<Expr *> Args,
8367 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008368 // Find all of the types that the arguments can convert to, but only
8369 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008370 // that make use of these types. Also record whether we encounter non-record
8371 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008372 Qualifiers VisibleTypeConversionsQuals;
8373 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008374 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008375 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008376
8377 bool HasNonRecordCandidateType = false;
8378 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008379 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008380 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008381 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008382 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8383 OpLoc,
8384 true,
8385 (Op == OO_Exclaim ||
8386 Op == OO_AmpAmp ||
8387 Op == OO_PipePipe),
8388 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008389 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8390 CandidateTypes[ArgIdx].hasNonRecordTypes();
8391 HasArithmeticOrEnumeralCandidateType =
8392 HasArithmeticOrEnumeralCandidateType ||
8393 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008394 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008395
Chandler Carruth00a38332010-12-13 01:44:01 +00008396 // Exit early when no non-record types have been added to the candidate set
8397 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008398 //
8399 // We can't exit early for !, ||, or &&, since there we have always have
8400 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008401 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008402 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008403 return;
8404
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008405 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008406 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008407 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008408 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008409 CandidateTypes, CandidateSet);
8410
8411 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008412 switch (Op) {
8413 case OO_None:
8414 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008415 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008416
Chandler Carruth5184de02010-12-12 08:51:33 +00008417 case OO_New:
8418 case OO_Delete:
8419 case OO_Array_New:
8420 case OO_Array_Delete:
8421 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008422 llvm_unreachable(
8423 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008424
8425 case OO_Comma:
8426 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008427 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008428 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008429 // -- For the operator ',', the unary operator '&', the
8430 // operator '->', or the operator 'co_await', the
8431 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008432 break;
8433
8434 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008435 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008436 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008437 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008438
8439 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008440 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008441 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008442 } else {
8443 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8444 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8445 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008446 break;
8447
Chandler Carruth5184de02010-12-12 08:51:33 +00008448 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008449 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008450 OpBuilder.addUnaryStarPointerOverloads();
8451 else
8452 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8453 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008454
Chandler Carruth5184de02010-12-12 08:51:33 +00008455 case OO_Slash:
8456 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008457 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008458
8459 case OO_PlusPlus:
8460 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008461 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8462 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008463 break;
8464
Douglas Gregor84605ae2009-08-24 13:43:27 +00008465 case OO_EqualEqual:
8466 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008467 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008468 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008469
Douglas Gregora11693b2008-11-12 17:17:38 +00008470 case OO_Less:
8471 case OO_Greater:
8472 case OO_LessEqual:
8473 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008474 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008475 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8476 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008477
Douglas Gregora11693b2008-11-12 17:17:38 +00008478 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008479 case OO_Caret:
8480 case OO_Pipe:
8481 case OO_LessLess:
8482 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008483 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008484 break;
8485
Chandler Carruth5184de02010-12-12 08:51:33 +00008486 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008487 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008488 // C++ [over.match.oper]p3:
8489 // -- For the operator ',', the unary operator '&', or the
8490 // operator '->', the built-in candidates set is empty.
8491 break;
8492
8493 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8494 break;
8495
8496 case OO_Tilde:
8497 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8498 break;
8499
Douglas Gregora11693b2008-11-12 17:17:38 +00008500 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008501 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008502 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008503
8504 case OO_PlusEqual:
8505 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008506 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008507 // Fall through.
8508
8509 case OO_StarEqual:
8510 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008511 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008512 break;
8513
8514 case OO_PercentEqual:
8515 case OO_LessLessEqual:
8516 case OO_GreaterGreaterEqual:
8517 case OO_AmpEqual:
8518 case OO_CaretEqual:
8519 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008520 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008521 break;
8522
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008523 case OO_Exclaim:
8524 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008525 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008526
Douglas Gregora11693b2008-11-12 17:17:38 +00008527 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008528 case OO_PipePipe:
8529 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008530 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008531
8532 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008533 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008534 break;
8535
8536 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008537 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008538 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008539
8540 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008541 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008542 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8543 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008544 }
8545}
8546
Douglas Gregore254f902009-02-04 00:32:51 +00008547/// \brief Add function candidates found via argument-dependent lookup
8548/// to the set of overloading candidates.
8549///
8550/// This routine performs argument-dependent name lookup based on the
8551/// given function name (which may also be an operator name) and adds
8552/// all of the overload candidates found by ADL to the overload
8553/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008554void
Douglas Gregore254f902009-02-04 00:32:51 +00008555Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008556 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008557 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008558 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008559 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008560 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008561 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008562
John McCall91f61fc2010-01-26 06:04:06 +00008563 // FIXME: This approach for uniquing ADL results (and removing
8564 // redundant candidates from the set) relies on pointer-equality,
8565 // which means we need to key off the canonical decl. However,
8566 // always going back to the canonical decl might not get us the
8567 // right set of default arguments. What default arguments are
8568 // we supposed to consider on ADL candidates, anyway?
8569
Douglas Gregorcabea402009-09-22 15:41:20 +00008570 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008571 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008572
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008573 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008574 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8575 CandEnd = CandidateSet.end();
8576 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008577 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008578 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008579 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008580 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008581 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008582
8583 // For each of the ADL candidates we found, add it to the overload
8584 // set.
John McCall8fe68082010-01-26 07:16:45 +00008585 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008586 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008587 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008588 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008589 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008590
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008591 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8592 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008593 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008594 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008595 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008596 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008597 }
Douglas Gregore254f902009-02-04 00:32:51 +00008598}
8599
George Burgess IV3dc166912016-05-10 01:59:34 +00008600namespace {
8601enum class Comparison { Equal, Better, Worse };
8602}
8603
8604/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8605/// overload resolution.
8606///
8607/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8608/// Cand1's first N enable_if attributes have precisely the same conditions as
8609/// Cand2's first N enable_if attributes (where N = the number of enable_if
8610/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8611///
8612/// Note that you can have a pair of candidates such that Cand1's enable_if
8613/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8614/// worse than Cand1's.
8615static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8616 const FunctionDecl *Cand2) {
8617 // Common case: One (or both) decls don't have enable_if attrs.
8618 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8619 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8620 if (!Cand1Attr || !Cand2Attr) {
8621 if (Cand1Attr == Cand2Attr)
8622 return Comparison::Equal;
8623 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8624 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008625
8626 // FIXME: The next several lines are just
8627 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8628 // instead of reverse order which is how they're stored in the AST.
8629 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8630 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8631
George Burgess IV3dc166912016-05-10 01:59:34 +00008632 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8633 // has fewer enable_if attributes than Cand2.
8634 if (Cand1Attrs.size() < Cand2Attrs.size())
8635 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008636
8637 auto Cand1I = Cand1Attrs.begin();
8638 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8639 for (auto &Cand2A : Cand2Attrs) {
8640 Cand1ID.clear();
8641 Cand2ID.clear();
8642
8643 auto &Cand1A = *Cand1I++;
8644 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8645 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8646 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008647 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008648 }
8649
George Burgess IV3dc166912016-05-10 01:59:34 +00008650 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008651}
8652
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008653/// isBetterOverloadCandidate - Determines whether the first overload
8654/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008655bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8656 const OverloadCandidate &Cand2,
8657 SourceLocation Loc,
8658 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008659 // Define viable functions to be better candidates than non-viable
8660 // functions.
8661 if (!Cand2.Viable)
8662 return Cand1.Viable;
8663 else if (!Cand1.Viable)
8664 return false;
8665
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008666 // C++ [over.match.best]p1:
8667 //
8668 // -- if F is a static member function, ICS1(F) is defined such
8669 // that ICS1(F) is neither better nor worse than ICS1(G) for
8670 // any function G, and, symmetrically, ICS1(G) is neither
8671 // better nor worse than ICS1(F).
8672 unsigned StartArg = 0;
8673 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8674 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008675
George Burgess IVfbad5b22016-09-07 20:03:19 +00008676 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8677 // We don't allow incompatible pointer conversions in C++.
8678 if (!S.getLangOpts().CPlusPlus)
8679 return ICS.isStandard() &&
8680 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8681
8682 // The only ill-formed conversion we allow in C++ is the string literal to
8683 // char* conversion, which is only considered ill-formed after C++11.
8684 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8685 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8686 };
8687
8688 // Define functions that don't require ill-formed conversions for a given
8689 // argument to be better candidates than functions that do.
8690 unsigned NumArgs = Cand1.NumConversions;
8691 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8692 bool HasBetterConversion = false;
8693 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8694 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8695 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8696 if (Cand1Bad != Cand2Bad) {
8697 if (Cand1Bad)
8698 return false;
8699 HasBetterConversion = true;
8700 }
8701 }
8702
8703 if (HasBetterConversion)
8704 return true;
8705
Douglas Gregord3cb3562009-07-07 23:38:56 +00008706 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008707 // A viable function F1 is defined to be a better function than another
8708 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008709 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008710 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008711 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008712 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008713 Cand2.Conversions[ArgIdx])) {
8714 case ImplicitConversionSequence::Better:
8715 // Cand1 has a better conversion sequence.
8716 HasBetterConversion = true;
8717 break;
8718
8719 case ImplicitConversionSequence::Worse:
8720 // Cand1 can't be better than Cand2.
8721 return false;
8722
8723 case ImplicitConversionSequence::Indistinguishable:
8724 // Do nothing.
8725 break;
8726 }
8727 }
8728
Mike Stump11289f42009-09-09 15:08:12 +00008729 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008730 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008731 if (HasBetterConversion)
8732 return true;
8733
Douglas Gregora1f013e2008-11-07 22:36:19 +00008734 // -- the context is an initialization by user-defined conversion
8735 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8736 // from the return type of F1 to the destination type (i.e.,
8737 // the type of the entity being initialized) is a better
8738 // conversion sequence than the standard conversion sequence
8739 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008740 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008741 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008742 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008743 // First check whether we prefer one of the conversion functions over the
8744 // other. This only distinguishes the results in non-standard, extension
8745 // cases such as the conversion from a lambda closure type to a function
8746 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008747 ImplicitConversionSequence::CompareKind Result =
8748 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8749 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008750 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008751 Cand1.FinalConversion,
8752 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008753
Richard Smithec2748a2014-05-17 04:36:39 +00008754 if (Result != ImplicitConversionSequence::Indistinguishable)
8755 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008756
8757 // FIXME: Compare kind of reference binding if conversion functions
8758 // convert to a reference type used in direct reference binding, per
8759 // C++14 [over.match.best]p1 section 2 bullet 3.
8760 }
8761
8762 // -- F1 is a non-template function and F2 is a function template
8763 // specialization, or, if not that,
8764 bool Cand1IsSpecialization = Cand1.Function &&
8765 Cand1.Function->getPrimaryTemplate();
8766 bool Cand2IsSpecialization = Cand2.Function &&
8767 Cand2.Function->getPrimaryTemplate();
8768 if (Cand1IsSpecialization != Cand2IsSpecialization)
8769 return Cand2IsSpecialization;
8770
8771 // -- F1 and F2 are function template specializations, and the function
8772 // template for F1 is more specialized than the template for F2
8773 // according to the partial ordering rules described in 14.5.5.2, or,
8774 // if not that,
8775 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8776 if (FunctionTemplateDecl *BetterTemplate
8777 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8778 Cand2.Function->getPrimaryTemplate(),
8779 Loc,
8780 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8781 : TPOC_Call,
8782 Cand1.ExplicitCallArguments,
8783 Cand2.ExplicitCallArguments))
8784 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008785 }
8786
Richard Smith5179eb72016-06-28 19:03:57 +00008787 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8788 // A derived-class constructor beats an (inherited) base class constructor.
8789 bool Cand1IsInherited =
8790 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8791 bool Cand2IsInherited =
8792 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8793 if (Cand1IsInherited != Cand2IsInherited)
8794 return Cand2IsInherited;
8795 else if (Cand1IsInherited) {
8796 assert(Cand2IsInherited);
8797 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8798 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8799 if (Cand1Class->isDerivedFrom(Cand2Class))
8800 return true;
8801 if (Cand2Class->isDerivedFrom(Cand1Class))
8802 return false;
8803 // Inherited from sibling base classes: still ambiguous.
8804 }
8805
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008806 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008807 if (Cand1.Function && Cand2.Function) {
8808 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8809 if (Cmp != Comparison::Equal)
8810 return Cmp == Comparison::Better;
8811 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008812
Justin Lebar25c4a812016-03-29 16:24:16 +00008813 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008814 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8815 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8816 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8817 }
8818
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008819 bool HasPS1 = Cand1.Function != nullptr &&
8820 functionHasPassObjectSizeParams(Cand1.Function);
8821 bool HasPS2 = Cand2.Function != nullptr &&
8822 functionHasPassObjectSizeParams(Cand2.Function);
8823 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008824}
8825
Richard Smith2dbe4042015-11-04 19:26:32 +00008826/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008827/// name lookup and overload resolution. This applies when the same internal/no
8828/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008829/// the same header). In such a case, we don't consider the declarations to
8830/// declare the same entity, but we also don't want lookups with both
8831/// declarations visible to be ambiguous in some cases (this happens when using
8832/// a modularized libstdc++).
8833bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8834 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008835 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8836 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8837 if (!VA || !VB)
8838 return false;
8839
8840 // The declarations must be declaring the same name as an internal linkage
8841 // entity in different modules.
8842 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8843 VB->getDeclContext()->getRedeclContext()) ||
8844 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8845 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8846 VA->isExternallyVisible() || VB->isExternallyVisible())
8847 return false;
8848
8849 // Check that the declarations appear to be equivalent.
8850 //
8851 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8852 // For constants and functions, we should check the initializer or body is
8853 // the same. For non-constant variables, we shouldn't allow it at all.
8854 if (Context.hasSameType(VA->getType(), VB->getType()))
8855 return true;
8856
8857 // Enum constants within unnamed enumerations will have different types, but
8858 // may still be similar enough to be interchangeable for our purposes.
8859 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8860 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8861 // Only handle anonymous enums. If the enumerations were named and
8862 // equivalent, they would have been merged to the same type.
8863 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8864 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8865 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8866 !Context.hasSameType(EnumA->getIntegerType(),
8867 EnumB->getIntegerType()))
8868 return false;
8869 // Allow this only if the value is the same for both enumerators.
8870 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8871 }
8872 }
8873
8874 // Nothing else is sufficiently similar.
8875 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008876}
8877
8878void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8879 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8880 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8881
8882 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8883 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8884 << !M << (M ? M->getFullModuleName() : "");
8885
8886 for (auto *E : Equiv) {
8887 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8888 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8889 << !M << (M ? M->getFullModuleName() : "");
8890 }
Richard Smith896c66e2015-10-21 07:13:52 +00008891}
8892
Mike Stump11289f42009-09-09 15:08:12 +00008893/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008894/// within an overload candidate set.
8895///
James Dennettffad8b72012-06-22 08:10:18 +00008896/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008897/// which overload resolution occurs.
8898///
James Dennettffad8b72012-06-22 08:10:18 +00008899/// \param Best If overload resolution was successful or found a deleted
8900/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008901///
8902/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008903OverloadingResult
8904OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008905 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008906 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008907 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8908 std::transform(begin(), end(), std::back_inserter(Candidates),
8909 [](OverloadCandidate &Cand) { return &Cand; });
8910
Justin Lebar66a2ab92016-08-10 00:40:43 +00008911 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8912 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008913 // compilation mode only one call variant is viable. We need to
8914 // exclude non-viable overload candidates from consideration based
8915 // only on their host/device attributes. Specifically, if one
8916 // candidate call is WrongSide and the other is SameSide, we ignore
8917 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008918 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008919 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8920 bool ContainsSameSideCandidate =
8921 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8922 return Cand->Function &&
8923 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8924 Sema::CFP_SameSide;
8925 });
8926 if (ContainsSameSideCandidate) {
8927 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8928 return Cand->Function &&
8929 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8930 Sema::CFP_WrongSide;
8931 };
8932 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8933 IsWrongSideCandidate),
8934 Candidates.end());
8935 }
8936 }
8937
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008938 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008939 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008940 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008941 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008942 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008943 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008944 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008945
8946 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008947 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008948 return OR_No_Viable_Function;
8949
Richard Smith2dbe4042015-11-04 19:26:32 +00008950 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008951
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008952 // Make sure that this function is better than every other viable
8953 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008954 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008955 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008956 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008958 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008959 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8960 Cand->Function)) {
8961 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008962 continue;
8963 }
8964
John McCall5c32be02010-08-24 20:38:10 +00008965 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008966 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008967 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008968 }
Mike Stump11289f42009-09-09 15:08:12 +00008969
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008970 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008971 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008972 (Best->Function->isDeleted() ||
8973 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008974 return OR_Deleted;
8975
Richard Smith2dbe4042015-11-04 19:26:32 +00008976 if (!EquivalentCands.empty())
8977 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8978 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008979
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008980 return OR_Success;
8981}
8982
John McCall53262c92010-01-12 02:15:36 +00008983namespace {
8984
8985enum OverloadCandidateKind {
8986 oc_function,
8987 oc_method,
8988 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008989 oc_function_template,
8990 oc_method_template,
8991 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008992 oc_implicit_default_constructor,
8993 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008994 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008995 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008996 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00008997 oc_inherited_constructor,
8998 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00008999};
9000
George Burgess IVd66d37c2016-10-28 21:42:06 +00009001static OverloadCandidateKind
9002ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9003 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009004 bool isTemplate = false;
9005
9006 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9007 isTemplate = true;
9008 Description = S.getTemplateArgumentBindingsText(
9009 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9010 }
John McCallfd0b2f82010-01-06 09:43:14 +00009011
9012 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009013 if (!Ctor->isImplicit()) {
9014 if (isa<ConstructorUsingShadowDecl>(Found))
9015 return isTemplate ? oc_inherited_constructor_template
9016 : oc_inherited_constructor;
9017 else
9018 return isTemplate ? oc_constructor_template : oc_constructor;
9019 }
Sebastian Redl08905022011-02-05 19:23:19 +00009020
Alexis Hunt119c10e2011-05-25 23:16:36 +00009021 if (Ctor->isDefaultConstructor())
9022 return oc_implicit_default_constructor;
9023
9024 if (Ctor->isMoveConstructor())
9025 return oc_implicit_move_constructor;
9026
9027 assert(Ctor->isCopyConstructor() &&
9028 "unexpected sort of implicit constructor");
9029 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009030 }
9031
9032 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9033 // This actually gets spelled 'candidate function' for now, but
9034 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009035 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009036 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009037
Alexis Hunt119c10e2011-05-25 23:16:36 +00009038 if (Meth->isMoveAssignmentOperator())
9039 return oc_implicit_move_assignment;
9040
Douglas Gregor12695102012-02-10 08:36:38 +00009041 if (Meth->isCopyAssignmentOperator())
9042 return oc_implicit_copy_assignment;
9043
9044 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9045 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009046 }
9047
John McCalle1ac8d12010-01-13 00:25:19 +00009048 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009049}
9050
Richard Smith5179eb72016-06-28 19:03:57 +00009051void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9052 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9053 // set.
9054 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9055 S.Diag(FoundDecl->getLocation(),
9056 diag::note_ovl_candidate_inherited_constructor)
9057 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009058}
9059
John McCall53262c92010-01-12 02:15:36 +00009060} // end anonymous namespace
9061
George Burgess IV5f21c712015-10-12 19:57:04 +00009062static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9063 const FunctionDecl *FD) {
9064 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9065 bool AlwaysTrue;
9066 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9067 return false;
9068 if (!AlwaysTrue)
9069 return false;
9070 }
9071 return true;
9072}
9073
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009074/// \brief Returns true if we can take the address of the function.
9075///
9076/// \param Complain - If true, we'll emit a diagnostic
9077/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9078/// we in overload resolution?
9079/// \param Loc - The location of the statement we're complaining about. Ignored
9080/// if we're not complaining, or if we're in overload resolution.
9081static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9082 bool Complain,
9083 bool InOverloadResolution,
9084 SourceLocation Loc) {
9085 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9086 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009087 if (InOverloadResolution)
9088 S.Diag(FD->getLocStart(),
9089 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9090 else
9091 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9092 }
9093 return false;
9094 }
9095
George Burgess IV21081362016-07-24 23:12:40 +00009096 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9097 return P->hasAttr<PassObjectSizeAttr>();
9098 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009099 if (I == FD->param_end())
9100 return true;
9101
9102 if (Complain) {
9103 // Add one to ParamNo because it's user-facing
9104 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9105 if (InOverloadResolution)
9106 S.Diag(FD->getLocation(),
9107 diag::note_ovl_candidate_has_pass_object_size_params)
9108 << ParamNo;
9109 else
9110 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9111 << FD << ParamNo;
9112 }
9113 return false;
9114}
9115
9116static bool checkAddressOfCandidateIsAvailable(Sema &S,
9117 const FunctionDecl *FD) {
9118 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9119 /*InOverloadResolution=*/true,
9120 /*Loc=*/SourceLocation());
9121}
9122
9123bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9124 bool Complain,
9125 SourceLocation Loc) {
9126 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9127 /*InOverloadResolution=*/false,
9128 Loc);
9129}
9130
John McCall53262c92010-01-12 02:15:36 +00009131// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009132void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9133 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009134 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9135 return;
9136
John McCalle1ac8d12010-01-13 00:25:19 +00009137 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009138 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009139 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9140 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009141
9142 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009143 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009144 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009145}
9146
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009147// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009148// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009149void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9150 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009151 assert(OverloadedExpr->getType() == Context.OverloadTy);
9152
9153 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9154 OverloadExpr *OvlExpr = Ovl.Expression;
9155
9156 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9157 IEnd = OvlExpr->decls_end();
9158 I != IEnd; ++I) {
9159 if (FunctionTemplateDecl *FunTmpl =
9160 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009161 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009162 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009163 } else if (FunctionDecl *Fun
9164 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009165 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009166 }
9167 }
9168}
9169
John McCall0d1da222010-01-12 00:44:57 +00009170/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9171/// "lead" diagnostic; it will be given two arguments, the source and
9172/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009173void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9174 Sema &S,
9175 SourceLocation CaretLoc,
9176 const PartialDiagnostic &PDiag) const {
9177 S.Diag(CaretLoc, PDiag)
9178 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009179 // FIXME: The note limiting machinery is borrowed from
9180 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9181 // refactoring here.
9182 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9183 unsigned CandsShown = 0;
9184 AmbiguousConversionSequence::const_iterator I, E;
9185 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9186 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9187 break;
9188 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009189 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009190 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009191 if (I != E)
9192 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009193}
9194
Richard Smith17c00b42014-11-12 01:24:00 +00009195static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009196 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009197 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9198 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009199 assert(Cand->Function && "for now, candidate must be a function");
9200 FunctionDecl *Fn = Cand->Function;
9201
9202 // There's a conversion slot for the object argument if this is a
9203 // non-constructor method. Note that 'I' corresponds the
9204 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009205 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009206 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009207 if (I == 0)
9208 isObjectArgument = true;
9209 else
9210 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009211 }
9212
John McCalle1ac8d12010-01-13 00:25:19 +00009213 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009214 OverloadCandidateKind FnKind =
9215 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009216
John McCall6a61b522010-01-13 09:16:55 +00009217 Expr *FromExpr = Conv.Bad.FromExpr;
9218 QualType FromTy = Conv.Bad.getFromType();
9219 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009220
John McCallfb7ad0f2010-02-02 02:42:52 +00009221 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009222 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009223 Expr *E = FromExpr->IgnoreParens();
9224 if (isa<UnaryOperator>(E))
9225 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009226 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009227
9228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9229 << (unsigned) FnKind << FnDesc
9230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9231 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009233 return;
9234 }
9235
John McCall6d174642010-01-23 08:10:49 +00009236 // Do some hand-waving analysis to see if the non-viability is due
9237 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009238 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9239 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9240 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9241 CToTy = RT->getPointeeType();
9242 else {
9243 // TODO: detect and diagnose the full richness of const mismatches.
9244 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009245 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9246 CFromTy = FromPT->getPointeeType();
9247 CToTy = ToPT->getPointeeType();
9248 }
John McCall47000992010-01-14 03:28:57 +00009249 }
9250
9251 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9252 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009253 Qualifiers FromQs = CFromTy.getQualifiers();
9254 Qualifiers ToQs = CToTy.getQualifiers();
9255
9256 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9258 << (unsigned) FnKind << FnDesc
9259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9260 << FromTy
9261 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9262 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009263 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009264 return;
9265 }
9266
John McCall31168b02011-06-15 23:02:42 +00009267 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009269 << (unsigned) FnKind << FnDesc
9270 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9271 << FromTy
9272 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9273 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009274 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009275 return;
9276 }
9277
Douglas Gregoraec25842011-04-26 23:16:46 +00009278 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9279 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9280 << (unsigned) FnKind << FnDesc
9281 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9282 << FromTy
9283 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9284 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009285 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009286 return;
9287 }
9288
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009289 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9291 << (unsigned) FnKind << FnDesc
9292 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9293 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009294 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009295 return;
9296 }
9297
John McCall47000992010-01-14 03:28:57 +00009298 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9299 assert(CVR && "unexpected qualifiers mismatch");
9300
9301 if (isObjectArgument) {
9302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9303 << (unsigned) FnKind << FnDesc
9304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9305 << FromTy << (CVR - 1);
9306 } else {
9307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9308 << (unsigned) FnKind << FnDesc
9309 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9310 << FromTy << (CVR - 1) << I+1;
9311 }
Richard Smith5179eb72016-06-28 19:03:57 +00009312 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009313 return;
9314 }
9315
Sebastian Redla72462c2011-09-24 17:48:32 +00009316 // Special diagnostic for failure to convert an initializer list, since
9317 // telling the user that it has type void is not useful.
9318 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9320 << (unsigned) FnKind << FnDesc
9321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9322 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009324 return;
9325 }
9326
John McCall6d174642010-01-23 08:10:49 +00009327 // Diagnose references or pointers to incomplete types differently,
9328 // since it's far from impossible that the incompleteness triggered
9329 // the failure.
9330 QualType TempFromTy = FromTy.getNonReferenceType();
9331 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9332 TempFromTy = PTy->getPointeeType();
9333 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009334 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9336 << (unsigned) FnKind << FnDesc
9337 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009338 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9339 << (unsigned) (Cand->Fix.Kind);
9340
Richard Smith5179eb72016-06-28 19:03:57 +00009341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009342 return;
9343 }
9344
Douglas Gregor56f2e342010-06-30 23:01:39 +00009345 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009346 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009347 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9348 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9349 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9350 FromPtrTy->getPointeeType()) &&
9351 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9352 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009353 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009354 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009355 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009356 }
9357 } else if (const ObjCObjectPointerType *FromPtrTy
9358 = FromTy->getAs<ObjCObjectPointerType>()) {
9359 if (const ObjCObjectPointerType *ToPtrTy
9360 = ToTy->getAs<ObjCObjectPointerType>())
9361 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9362 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9363 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9364 FromPtrTy->getPointeeType()) &&
9365 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009366 BaseToDerivedConversion = 2;
9367 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009368 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9369 !FromTy->isIncompleteType() &&
9370 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009371 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009372 BaseToDerivedConversion = 3;
9373 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9374 ToTy.getNonReferenceType().getCanonicalType() ==
9375 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9377 << (unsigned) FnKind << FnDesc
9378 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9379 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009381 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009382 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009384
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009385 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009386 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009387 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009388 << (unsigned) FnKind << FnDesc
9389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009390 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009391 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009392 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009393 return;
9394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009395
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009396 if (isa<ObjCObjectPointerType>(CFromTy) &&
9397 isa<PointerType>(CToTy)) {
9398 Qualifiers FromQs = CFromTy.getQualifiers();
9399 Qualifiers ToQs = CToTy.getQualifiers();
9400 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9402 << (unsigned) FnKind << FnDesc
9403 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9404 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009405 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009406 return;
9407 }
9408 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009409
9410 if (TakingCandidateAddress &&
9411 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9412 return;
9413
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009414 // Emit the generic diagnostic and, optionally, add the hints to it.
9415 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9416 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009417 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009418 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9419 << (unsigned) (Cand->Fix.Kind);
9420
9421 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009422 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9423 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009424 FDiag << *HI;
9425 S.Diag(Fn->getLocation(), FDiag);
9426
Richard Smith5179eb72016-06-28 19:03:57 +00009427 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009428}
9429
Larisse Voufo98b20f12013-07-19 23:00:19 +00009430/// Additional arity mismatch diagnosis specific to a function overload
9431/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9432/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009433static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9434 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009435 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009436 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009437
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009438 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009439 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009440 // right number of arguments, because only overloaded operators have
9441 // the weird behavior of overloading member and non-member functions.
9442 // Just don't report anything.
9443 if (Fn->isInvalidDecl() &&
9444 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009445 return true;
9446
9447 if (NumArgs < MinParams) {
9448 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9449 (Cand->FailureKind == ovl_fail_bad_deduction &&
9450 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9451 } else {
9452 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9453 (Cand->FailureKind == ovl_fail_bad_deduction &&
9454 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9455 }
9456
9457 return false;
9458}
9459
9460/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009461static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9462 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009463 assert(isa<FunctionDecl>(D) &&
9464 "The templated declaration should at least be a function"
9465 " when diagnosing bad template argument deduction due to too many"
9466 " or too few arguments");
9467
9468 FunctionDecl *Fn = cast<FunctionDecl>(D);
9469
9470 // TODO: treat calls to a missing default constructor as a special case
9471 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9472 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009473
John McCall6a61b522010-01-13 09:16:55 +00009474 // at least / at most / exactly
9475 unsigned mode, modeCount;
9476 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009477 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9478 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009479 mode = 0; // "at least"
9480 else
9481 mode = 2; // "exactly"
9482 modeCount = MinParams;
9483 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009484 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009485 mode = 1; // "at most"
9486 else
9487 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009488 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009489 }
9490
9491 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009492 OverloadCandidateKind FnKind =
9493 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009494
Richard Smith10ff50d2012-05-11 05:16:41 +00009495 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009497 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9498 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009499 else
9500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009501 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9502 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009503 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009504}
9505
Larisse Voufo98b20f12013-07-19 23:00:19 +00009506/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009507static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9508 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009509 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009510 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009511}
Larisse Voufo47c08452013-07-19 22:53:23 +00009512
Richard Smith17c00b42014-11-12 01:24:00 +00009513static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009514 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9515 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009516 llvm_unreachable("Unsupported: Getting the described template declaration"
9517 " for bad deduction diagnosis");
9518}
9519
9520/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009521static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009522 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009523 unsigned NumArgs,
9524 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009525 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009526 NamedDecl *ParamD;
9527 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9528 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9529 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009530 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009531 case Sema::TDK_Success:
9532 llvm_unreachable("TDK_success while diagnosing bad deduction");
9533
9534 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009535 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009536 S.Diag(Templated->getLocation(),
9537 diag::note_ovl_candidate_incomplete_deduction)
9538 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009539 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009540 return;
9541 }
9542
John McCall42d7d192010-08-05 09:05:08 +00009543 case Sema::TDK_Underqualified: {
9544 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9545 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9546
Larisse Voufo98b20f12013-07-19 23:00:19 +00009547 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009548
9549 // Param will have been canonicalized, but it should just be a
9550 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009551 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009552 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009553 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009554 assert(S.Context.hasSameType(Param, NonCanonParam));
9555
9556 // Arg has also been canonicalized, but there's nothing we can do
9557 // about that. It also doesn't matter as much, because it won't
9558 // have any template parameters in it (because deduction isn't
9559 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009560 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009561
Larisse Voufo98b20f12013-07-19 23:00:19 +00009562 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9563 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009564 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009565 return;
9566 }
9567
9568 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009569 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009570 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009571 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009572 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009573 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009574 which = 1;
9575 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009576 which = 2;
9577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578
Larisse Voufo98b20f12013-07-19 23:00:19 +00009579 S.Diag(Templated->getLocation(),
9580 diag::note_ovl_candidate_inconsistent_deduction)
9581 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9582 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009583 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009584 return;
9585 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009586
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009587 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009588 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009589 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009590 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009591 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009592 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009593 else {
9594 int index = 0;
9595 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9596 index = TTP->getIndex();
9597 else if (NonTypeTemplateParmDecl *NTTP
9598 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9599 index = NTTP->getIndex();
9600 else
9601 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009602 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009603 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009604 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009605 }
Richard Smith5179eb72016-06-28 19:03:57 +00009606 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009607 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009608
Douglas Gregor02eb4832010-05-08 18:13:28 +00009609 case Sema::TDK_TooManyArguments:
9610 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009611 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009612 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009613
9614 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009615 S.Diag(Templated->getLocation(),
9616 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009617 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009618 return;
9619
9620 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009621 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009622 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009623 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009624 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009625 TemplateArgString = " ";
9626 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009627 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009628 }
9629
Richard Smith6f8d2c62012-05-09 05:17:00 +00009630 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009631 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009632 if (PDiag && PDiag->second.getDiagID() ==
9633 diag::err_typename_nested_not_found_enable_if) {
9634 // FIXME: Use the source range of the condition, and the fully-qualified
9635 // name of the enable_if template. These are both present in PDiag.
9636 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9637 << "'enable_if'" << TemplateArgString;
9638 return;
9639 }
9640
Richard Smith9ca64612012-05-07 09:03:25 +00009641 // Format the SFINAE diagnostic into the argument string.
9642 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9643 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009644 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009645 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009646 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009647 SFINAEArgString = ": ";
9648 R = SourceRange(PDiag->first, PDiag->first);
9649 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9650 }
9651
Larisse Voufo98b20f12013-07-19 23:00:19 +00009652 S.Diag(Templated->getLocation(),
9653 diag::note_ovl_candidate_substitution_failure)
9654 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009655 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009656 return;
9657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009658
Richard Smith8c6eeb92013-01-31 04:03:12 +00009659 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009660 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9661 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009662 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009663 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009664 return;
9665 }
9666
Richard Smith9b534542015-12-31 02:02:54 +00009667 case Sema::TDK_DeducedMismatch: {
9668 // Format the template argument list into the argument string.
9669 SmallString<128> TemplateArgString;
9670 if (TemplateArgumentList *Args =
9671 DeductionFailure.getTemplateArgumentList()) {
9672 TemplateArgString = " ";
9673 TemplateArgString += S.getTemplateArgumentBindingsText(
9674 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9675 }
9676
9677 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9678 << (*DeductionFailure.getCallArgIndex() + 1)
9679 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9680 << TemplateArgString;
9681 break;
9682 }
9683
Richard Trieue3732352013-04-08 21:11:40 +00009684 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009685 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009686 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9687 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009688 if (FirstTA.getKind() == TemplateArgument::Template &&
9689 SecondTA.getKind() == TemplateArgument::Template) {
9690 TemplateName FirstTN = FirstTA.getAsTemplate();
9691 TemplateName SecondTN = SecondTA.getAsTemplate();
9692 if (FirstTN.getKind() == TemplateName::Template &&
9693 SecondTN.getKind() == TemplateName::Template) {
9694 if (FirstTN.getAsTemplateDecl()->getName() ==
9695 SecondTN.getAsTemplateDecl()->getName()) {
9696 // FIXME: This fixes a bad diagnostic where both templates are named
9697 // the same. This particular case is a bit difficult since:
9698 // 1) It is passed as a string to the diagnostic printer.
9699 // 2) The diagnostic printer only attempts to find a better
9700 // name for types, not decls.
9701 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009702 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009703 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9704 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9705 return;
9706 }
9707 }
9708 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009709
9710 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9711 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9712 return;
9713
Faisal Vali2b391ab2013-09-26 19:54:12 +00009714 // FIXME: For generic lambda parameters, check if the function is a lambda
9715 // call operator, and if so, emit a prettier and more informative
9716 // diagnostic that mentions 'auto' and lambda in addition to
9717 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009718 S.Diag(Templated->getLocation(),
9719 diag::note_ovl_candidate_non_deduced_mismatch)
9720 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009721 return;
Richard Trieue3732352013-04-08 21:11:40 +00009722 }
John McCall8b9ed552010-02-01 18:53:26 +00009723 // TODO: diagnose these individually, then kill off
9724 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009725 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009726 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009727 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009728 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009729 case Sema::TDK_CUDATargetMismatch:
9730 S.Diag(Templated->getLocation(),
9731 diag::note_cuda_ovl_candidate_target_mismatch);
9732 return;
John McCall8b9ed552010-02-01 18:53:26 +00009733 }
9734}
9735
Larisse Voufo98b20f12013-07-19 23:00:19 +00009736/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009737static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009738 unsigned NumArgs,
9739 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009740 unsigned TDK = Cand->DeductionFailure.Result;
9741 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9742 if (CheckArityMismatch(S, Cand, NumArgs))
9743 return;
9744 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009745 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009746 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009747}
9748
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009749/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009750static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009751 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9752 FunctionDecl *Callee = Cand->Function;
9753
9754 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9755 CalleeTarget = S.IdentifyCUDATarget(Callee);
9756
9757 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009758 OverloadCandidateKind FnKind =
9759 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009760
9761 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009762 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9763
9764 // This could be an implicit constructor for which we could not infer the
9765 // target due to a collsion. Diagnose that case.
9766 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9767 if (Meth != nullptr && Meth->isImplicit()) {
9768 CXXRecordDecl *ParentClass = Meth->getParent();
9769 Sema::CXXSpecialMember CSM;
9770
9771 switch (FnKind) {
9772 default:
9773 return;
9774 case oc_implicit_default_constructor:
9775 CSM = Sema::CXXDefaultConstructor;
9776 break;
9777 case oc_implicit_copy_constructor:
9778 CSM = Sema::CXXCopyConstructor;
9779 break;
9780 case oc_implicit_move_constructor:
9781 CSM = Sema::CXXMoveConstructor;
9782 break;
9783 case oc_implicit_copy_assignment:
9784 CSM = Sema::CXXCopyAssignment;
9785 break;
9786 case oc_implicit_move_assignment:
9787 CSM = Sema::CXXMoveAssignment;
9788 break;
9789 };
9790
9791 bool ConstRHS = false;
9792 if (Meth->getNumParams()) {
9793 if (const ReferenceType *RT =
9794 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9795 ConstRHS = RT->getPointeeType().isConstQualified();
9796 }
9797 }
9798
9799 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9800 /* ConstRHS */ ConstRHS,
9801 /* Diagnose */ true);
9802 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009803}
9804
Richard Smith17c00b42014-11-12 01:24:00 +00009805static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009806 FunctionDecl *Callee = Cand->Function;
9807 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9808
9809 S.Diag(Callee->getLocation(),
9810 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9811 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9812}
9813
Yaxun Liu5b746652016-12-18 05:18:55 +00009814static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9815 FunctionDecl *Callee = Cand->Function;
9816
9817 S.Diag(Callee->getLocation(),
9818 diag::note_ovl_candidate_disabled_by_extension);
9819}
9820
John McCall8b9ed552010-02-01 18:53:26 +00009821/// Generates a 'note' diagnostic for an overload candidate. We've
9822/// already generated a primary error at the call site.
9823///
9824/// It really does need to be a single diagnostic with its caret
9825/// pointed at the candidate declaration. Yes, this creates some
9826/// major challenges of technical writing. Yes, this makes pointing
9827/// out problems with specific arguments quite awkward. It's still
9828/// better than generating twenty screens of text for every failed
9829/// overload.
9830///
9831/// It would be great to be able to express per-candidate problems
9832/// more richly for those diagnostic clients that cared, but we'd
9833/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009834static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009835 unsigned NumArgs,
9836 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009837 FunctionDecl *Fn = Cand->Function;
9838
John McCall12f97bc2010-01-08 04:41:39 +00009839 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009840 if (Cand->Viable && (Fn->isDeleted() ||
9841 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009842 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009843 OverloadCandidateKind FnKind =
9844 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009845
9846 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009847 << FnKind << FnDesc
9848 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009849 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009850 return;
John McCall12f97bc2010-01-08 04:41:39 +00009851 }
9852
John McCalle1ac8d12010-01-13 00:25:19 +00009853 // We don't really have anything else to say about viable candidates.
9854 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009855 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009856 return;
9857 }
John McCall0d1da222010-01-12 00:44:57 +00009858
John McCall6a61b522010-01-13 09:16:55 +00009859 switch (Cand->FailureKind) {
9860 case ovl_fail_too_many_arguments:
9861 case ovl_fail_too_few_arguments:
9862 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009863
John McCall6a61b522010-01-13 09:16:55 +00009864 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009865 return DiagnoseBadDeduction(S, Cand, NumArgs,
9866 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009867
John McCall578a1f82014-12-14 01:46:53 +00009868 case ovl_fail_illegal_constructor: {
9869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9870 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009871 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009872 return;
9873 }
9874
John McCallfe796dd2010-01-23 05:17:32 +00009875 case ovl_fail_trivial_conversion:
9876 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009877 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009878 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009879
John McCall65eb8792010-02-25 01:37:24 +00009880 case ovl_fail_bad_conversion: {
9881 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009882 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009883 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009884 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009885
John McCall6a61b522010-01-13 09:16:55 +00009886 // FIXME: this currently happens when we're called from SemaInit
9887 // when user-conversion overload fails. Figure out how to handle
9888 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009889 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009890 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009891
9892 case ovl_fail_bad_target:
9893 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009894
9895 case ovl_fail_enable_if:
9896 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009897
Yaxun Liu5b746652016-12-18 05:18:55 +00009898 case ovl_fail_ext_disabled:
9899 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9900
George Burgess IV7204ed92016-01-07 02:26:57 +00009901 case ovl_fail_addr_not_available: {
9902 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9903 (void)Available;
9904 assert(!Available);
9905 break;
9906 }
John McCall65eb8792010-02-25 01:37:24 +00009907 }
John McCalld3224162010-01-08 00:58:21 +00009908}
9909
Richard Smith17c00b42014-11-12 01:24:00 +00009910static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009911 // Desugar the type of the surrogate down to a function type,
9912 // retaining as many typedefs as possible while still showing
9913 // the function type (and, therefore, its parameter types).
9914 QualType FnType = Cand->Surrogate->getConversionType();
9915 bool isLValueReference = false;
9916 bool isRValueReference = false;
9917 bool isPointer = false;
9918 if (const LValueReferenceType *FnTypeRef =
9919 FnType->getAs<LValueReferenceType>()) {
9920 FnType = FnTypeRef->getPointeeType();
9921 isLValueReference = true;
9922 } else if (const RValueReferenceType *FnTypeRef =
9923 FnType->getAs<RValueReferenceType>()) {
9924 FnType = FnTypeRef->getPointeeType();
9925 isRValueReference = true;
9926 }
9927 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9928 FnType = FnTypePtr->getPointeeType();
9929 isPointer = true;
9930 }
9931 // Desugar down to a function type.
9932 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9933 // Reconstruct the pointer/reference as appropriate.
9934 if (isPointer) FnType = S.Context.getPointerType(FnType);
9935 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9936 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9937
9938 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9939 << FnType;
9940}
9941
Richard Smith17c00b42014-11-12 01:24:00 +00009942static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9943 SourceLocation OpLoc,
9944 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009945 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009946 std::string TypeStr("operator");
9947 TypeStr += Opc;
9948 TypeStr += "(";
9949 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009950 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009951 TypeStr += ")";
9952 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9953 } else {
9954 TypeStr += ", ";
9955 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9956 TypeStr += ")";
9957 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9958 }
9959}
9960
Richard Smith17c00b42014-11-12 01:24:00 +00009961static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9962 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009963 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009964 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9965 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009966 if (ICS.isBad()) break; // all meaningless after first invalid
9967 if (!ICS.isAmbiguous()) continue;
9968
Richard Smithc2bebe92016-05-11 20:37:46 +00009969 ICS.DiagnoseAmbiguousConversion(
9970 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009971 }
9972}
9973
Larisse Voufo98b20f12013-07-19 23:00:19 +00009974static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009975 if (Cand->Function)
9976 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009977 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009978 return Cand->Surrogate->getLocation();
9979 return SourceLocation();
9980}
9981
Larisse Voufo98b20f12013-07-19 23:00:19 +00009982static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009983 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009984 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009985 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009986
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009987 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009988 case Sema::TDK_Incomplete:
9989 return 1;
9990
9991 case Sema::TDK_Underqualified:
9992 case Sema::TDK_Inconsistent:
9993 return 2;
9994
9995 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009996 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009997 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009998 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009999 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010000 return 3;
10001
10002 case Sema::TDK_InstantiationDepth:
10003 case Sema::TDK_FailedOverloadResolution:
10004 return 4;
10005
10006 case Sema::TDK_InvalidExplicitArguments:
10007 return 5;
10008
10009 case Sema::TDK_TooManyArguments:
10010 case Sema::TDK_TooFewArguments:
10011 return 6;
10012 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010013 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010014}
10015
Richard Smith17c00b42014-11-12 01:24:00 +000010016namespace {
John McCallad2587a2010-01-12 00:48:53 +000010017struct CompareOverloadCandidatesForDisplay {
10018 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010019 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010020 size_t NumArgs;
10021
Richard Smith0f59cb32015-12-18 21:45:41 +000010022 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010023 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010024
10025 bool operator()(const OverloadCandidate *L,
10026 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010027 // Fast-path this check.
10028 if (L == R) return false;
10029
John McCall12f97bc2010-01-08 04:41:39 +000010030 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010031 if (L->Viable) {
10032 if (!R->Viable) return true;
10033
10034 // TODO: introduce a tri-valued comparison for overload
10035 // candidates. Would be more worthwhile if we had a sort
10036 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010037 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10038 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010039 } else if (R->Viable)
10040 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010041
John McCall3712d9e2010-01-15 23:32:50 +000010042 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010043
John McCall3712d9e2010-01-15 23:32:50 +000010044 // Criteria by which we can sort non-viable candidates:
10045 if (!L->Viable) {
10046 // 1. Arity mismatches come after other candidates.
10047 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010048 L->FailureKind == ovl_fail_too_few_arguments) {
10049 if (R->FailureKind == ovl_fail_too_many_arguments ||
10050 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010051 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10052 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10053 if (LDist == RDist) {
10054 if (L->FailureKind == R->FailureKind)
10055 // Sort non-surrogates before surrogates.
10056 return !L->IsSurrogate && R->IsSurrogate;
10057 // Sort candidates requiring fewer parameters than there were
10058 // arguments given after candidates requiring more parameters
10059 // than there were arguments given.
10060 return L->FailureKind == ovl_fail_too_many_arguments;
10061 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010062 return LDist < RDist;
10063 }
John McCall3712d9e2010-01-15 23:32:50 +000010064 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010065 }
John McCall3712d9e2010-01-15 23:32:50 +000010066 if (R->FailureKind == ovl_fail_too_many_arguments ||
10067 R->FailureKind == ovl_fail_too_few_arguments)
10068 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010069
John McCallfe796dd2010-01-23 05:17:32 +000010070 // 2. Bad conversions come first and are ordered by the number
10071 // of bad conversions and quality of good conversions.
10072 if (L->FailureKind == ovl_fail_bad_conversion) {
10073 if (R->FailureKind != ovl_fail_bad_conversion)
10074 return true;
10075
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010076 // The conversion that can be fixed with a smaller number of changes,
10077 // comes first.
10078 unsigned numLFixes = L->Fix.NumConversionsFixed;
10079 unsigned numRFixes = R->Fix.NumConversionsFixed;
10080 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10081 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010082 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010083 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010084 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010085
John McCallfe796dd2010-01-23 05:17:32 +000010086 // If there's any ordering between the defined conversions...
10087 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010088 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010089
10090 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010091 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010092 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010093 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010094 L->Conversions[I],
10095 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010096 case ImplicitConversionSequence::Better:
10097 leftBetter++;
10098 break;
10099
10100 case ImplicitConversionSequence::Worse:
10101 leftBetter--;
10102 break;
10103
10104 case ImplicitConversionSequence::Indistinguishable:
10105 break;
10106 }
10107 }
10108 if (leftBetter > 0) return true;
10109 if (leftBetter < 0) return false;
10110
10111 } else if (R->FailureKind == ovl_fail_bad_conversion)
10112 return false;
10113
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010114 if (L->FailureKind == ovl_fail_bad_deduction) {
10115 if (R->FailureKind != ovl_fail_bad_deduction)
10116 return true;
10117
10118 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10119 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010120 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010121 } else if (R->FailureKind == ovl_fail_bad_deduction)
10122 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010123
John McCall3712d9e2010-01-15 23:32:50 +000010124 // TODO: others?
10125 }
10126
10127 // Sort everything else by location.
10128 SourceLocation LLoc = GetLocationForCandidate(L);
10129 SourceLocation RLoc = GetLocationForCandidate(R);
10130
10131 // Put candidates without locations (e.g. builtins) at the end.
10132 if (LLoc.isInvalid()) return false;
10133 if (RLoc.isInvalid()) return true;
10134
10135 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010136 }
10137};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010138}
John McCall12f97bc2010-01-08 04:41:39 +000010139
John McCallfe796dd2010-01-23 05:17:32 +000010140/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010141/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010142static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10143 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010144 assert(!Cand->Viable);
10145
10146 // Don't do anything on failures other than bad conversion.
10147 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10148
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010149 // We only want the FixIts if all the arguments can be corrected.
10150 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010151 // Use a implicit copy initialization to check conversion fixes.
10152 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010153
John McCallfe796dd2010-01-23 05:17:32 +000010154 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010155 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010156 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010157 while (true) {
10158 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10159 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010160 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010161 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010162 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010163 }
John McCallfe796dd2010-01-23 05:17:32 +000010164 }
10165
10166 if (ConvIdx == ConvCount)
10167 return;
10168
John McCall65eb8792010-02-25 01:37:24 +000010169 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10170 "remaining conversion is initialized?");
10171
Douglas Gregoradc7a702010-04-16 17:45:54 +000010172 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010173 // operation somehow.
10174 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010175
10176 const FunctionProtoType* Proto;
10177 unsigned ArgIdx = ConvIdx;
10178
10179 if (Cand->IsSurrogate) {
10180 QualType ConvType
10181 = Cand->Surrogate->getConversionType().getNonReferenceType();
10182 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10183 ConvType = ConvPtrType->getPointeeType();
10184 Proto = ConvType->getAs<FunctionProtoType>();
10185 ArgIdx--;
10186 } else if (Cand->Function) {
10187 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10188 if (isa<CXXMethodDecl>(Cand->Function) &&
10189 !isa<CXXConstructorDecl>(Cand->Function))
10190 ArgIdx--;
10191 } else {
10192 // Builtin binary operator with a bad first conversion.
10193 assert(ConvCount <= 3);
10194 for (; ConvIdx != ConvCount; ++ConvIdx)
10195 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010196 = TryCopyInitialization(S, Args[ConvIdx],
10197 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010198 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010199 /*InOverloadResolution*/ true,
10200 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010201 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010202 return;
10203 }
10204
10205 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010206 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010207 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010208 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010209 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10210 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10211 /*InOverloadResolution=*/true,
10212 /*AllowObjCWritebackConversion=*/
10213 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010214 // Store the FixIt in the candidate if it exists.
10215 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010216 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010217 }
John McCallfe796dd2010-01-23 05:17:32 +000010218 else
10219 Cand->Conversions[ConvIdx].setEllipsis();
10220 }
10221}
10222
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010223/// PrintOverloadCandidates - When overload resolution fails, prints
10224/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010225/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010226void OverloadCandidateSet::NoteCandidates(
10227 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10228 StringRef Opc, SourceLocation OpLoc,
10229 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010230 // Sort the candidates by viability and position. Sorting directly would
10231 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010232 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010233 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10234 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010235 if (!Filter(*Cand))
10236 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010237 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010238 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010239 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010240 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010241 if (Cand->Function || Cand->IsSurrogate)
10242 Cands.push_back(Cand);
10243 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10244 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010245 }
10246 }
10247
John McCallad2587a2010-01-12 00:48:53 +000010248 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010249 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010250
John McCall0d1da222010-01-12 00:44:57 +000010251 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010252
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010253 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010254 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010255 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010256 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10257 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010258
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010259 // Set an arbitrary limit on the number of candidate functions we'll spam
10260 // the user with. FIXME: This limit should depend on details of the
10261 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010262 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010263 break;
10264 }
10265 ++CandsShown;
10266
John McCalld3224162010-01-08 00:58:21 +000010267 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010268 NoteFunctionCandidate(S, Cand, Args.size(),
10269 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010270 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010271 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010272 else {
10273 assert(Cand->Viable &&
10274 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010275 // Generally we only see ambiguities including viable builtin
10276 // operators if overload resolution got screwed up by an
10277 // ambiguous user-defined conversion.
10278 //
10279 // FIXME: It's quite possible for different conversions to see
10280 // different ambiguities, though.
10281 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010282 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010283 ReportedAmbiguousConversions = true;
10284 }
John McCalld3224162010-01-08 00:58:21 +000010285
John McCall0d1da222010-01-12 00:44:57 +000010286 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010287 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010288 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010289 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010290
10291 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010292 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010293}
10294
Larisse Voufo98b20f12013-07-19 23:00:19 +000010295static SourceLocation
10296GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10297 return Cand->Specialization ? Cand->Specialization->getLocation()
10298 : SourceLocation();
10299}
10300
Richard Smith17c00b42014-11-12 01:24:00 +000010301namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010302struct CompareTemplateSpecCandidatesForDisplay {
10303 Sema &S;
10304 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10305
10306 bool operator()(const TemplateSpecCandidate *L,
10307 const TemplateSpecCandidate *R) {
10308 // Fast-path this check.
10309 if (L == R)
10310 return false;
10311
10312 // Assuming that both candidates are not matches...
10313
10314 // Sort by the ranking of deduction failures.
10315 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10316 return RankDeductionFailure(L->DeductionFailure) <
10317 RankDeductionFailure(R->DeductionFailure);
10318
10319 // Sort everything else by location.
10320 SourceLocation LLoc = GetLocationForCandidate(L);
10321 SourceLocation RLoc = GetLocationForCandidate(R);
10322
10323 // Put candidates without locations (e.g. builtins) at the end.
10324 if (LLoc.isInvalid())
10325 return false;
10326 if (RLoc.isInvalid())
10327 return true;
10328
10329 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10330 }
10331};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010332}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010333
10334/// Diagnose a template argument deduction failure.
10335/// We are treating these failures as overload failures due to bad
10336/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010337void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10338 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010339 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010340 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010341}
10342
10343void TemplateSpecCandidateSet::destroyCandidates() {
10344 for (iterator i = begin(), e = end(); i != e; ++i) {
10345 i->DeductionFailure.Destroy();
10346 }
10347}
10348
10349void TemplateSpecCandidateSet::clear() {
10350 destroyCandidates();
10351 Candidates.clear();
10352}
10353
10354/// NoteCandidates - When no template specialization match is found, prints
10355/// diagnostic messages containing the non-matching specializations that form
10356/// the candidate set.
10357/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10358/// OCD == OCD_AllCandidates and Cand->Viable == false.
10359void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10360 // Sort the candidates by position (assuming no candidate is a match).
10361 // Sorting directly would be prohibitive, so we make a set of pointers
10362 // and sort those.
10363 SmallVector<TemplateSpecCandidate *, 32> Cands;
10364 Cands.reserve(size());
10365 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10366 if (Cand->Specialization)
10367 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010368 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010369 // in general, want to list every possible builtin candidate.
10370 }
10371
10372 std::sort(Cands.begin(), Cands.end(),
10373 CompareTemplateSpecCandidatesForDisplay(S));
10374
10375 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10376 // for generalization purposes (?).
10377 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10378
10379 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10380 unsigned CandsShown = 0;
10381 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10382 TemplateSpecCandidate *Cand = *I;
10383
10384 // Set an arbitrary limit on the number of candidates we'll spam
10385 // the user with. FIXME: This limit should depend on details of the
10386 // candidate list.
10387 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10388 break;
10389 ++CandsShown;
10390
10391 assert(Cand->Specialization &&
10392 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010393 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010394 }
10395
10396 if (I != E)
10397 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10398}
10399
Douglas Gregorb491ed32011-02-19 21:32:49 +000010400// [PossiblyAFunctionType] --> [Return]
10401// NonFunctionType --> NonFunctionType
10402// R (A) --> R(A)
10403// R (*)(A) --> R (A)
10404// R (&)(A) --> R (A)
10405// R (S::*)(A) --> R (A)
10406QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10407 QualType Ret = PossiblyAFunctionType;
10408 if (const PointerType *ToTypePtr =
10409 PossiblyAFunctionType->getAs<PointerType>())
10410 Ret = ToTypePtr->getPointeeType();
10411 else if (const ReferenceType *ToTypeRef =
10412 PossiblyAFunctionType->getAs<ReferenceType>())
10413 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010414 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010415 PossiblyAFunctionType->getAs<MemberPointerType>())
10416 Ret = MemTypePtr->getPointeeType();
10417 Ret =
10418 Context.getCanonicalType(Ret).getUnqualifiedType();
10419 return Ret;
10420}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010421
Richard Smith9095e5b2016-11-01 01:31:23 +000010422static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10423 bool Complain = true) {
10424 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10425 S.DeduceReturnType(FD, Loc, Complain))
10426 return true;
10427
10428 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10429 if (S.getLangOpts().CPlusPlus1z &&
10430 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10431 !S.ResolveExceptionSpec(Loc, FPT))
10432 return true;
10433
10434 return false;
10435}
10436
Richard Smith17c00b42014-11-12 01:24:00 +000010437namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010438// A helper class to help with address of function resolution
10439// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010440class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010441 Sema& S;
10442 Expr* SourceExpr;
10443 const QualType& TargetType;
10444 QualType TargetFunctionType; // Extracted function type from target type
10445
10446 bool Complain;
10447 //DeclAccessPair& ResultFunctionAccessPair;
10448 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010449
Douglas Gregorb491ed32011-02-19 21:32:49 +000010450 bool TargetTypeIsNonStaticMemberFunction;
10451 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010452 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010453 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010454
Douglas Gregorb491ed32011-02-19 21:32:49 +000010455 OverloadExpr::FindResult OvlExprInfo;
10456 OverloadExpr *OvlExpr;
10457 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010458 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010459 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010460
Douglas Gregorb491ed32011-02-19 21:32:49 +000010461public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010462 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10463 const QualType &TargetType, bool Complain)
10464 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10465 Complain(Complain), Context(S.getASTContext()),
10466 TargetTypeIsNonStaticMemberFunction(
10467 !!TargetType->getAs<MemberPointerType>()),
10468 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010469 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010470 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010471 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10472 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010473 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010474 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010475
David Majnemera4f7c7a2013-08-01 06:13:59 +000010476 if (TargetFunctionType->isFunctionType()) {
10477 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10478 if (!UME->isImplicitAccess() &&
10479 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10480 StaticMemberFunctionFromBoundPointer = true;
10481 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10482 DeclAccessPair dap;
10483 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10484 OvlExpr, false, &dap)) {
10485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10486 if (!Method->isStatic()) {
10487 // If the target type is a non-function type and the function found
10488 // is a non-static member function, pretend as if that was the
10489 // target, it's the only possible type to end up with.
10490 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010491
David Majnemera4f7c7a2013-08-01 06:13:59 +000010492 // And skip adding the function if its not in the proper form.
10493 // We'll diagnose this due to an empty set of functions.
10494 if (!OvlExprInfo.HasFormOfMemberPointer)
10495 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010496 }
10497
David Majnemera4f7c7a2013-08-01 06:13:59 +000010498 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010499 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010500 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010501 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010502
10503 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010504 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010505
Douglas Gregorb491ed32011-02-19 21:32:49 +000010506 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10507 // C++ [over.over]p4:
10508 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010509 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010510 if (FoundNonTemplateFunction)
10511 EliminateAllTemplateMatches();
10512 else
10513 EliminateAllExceptMostSpecializedTemplate();
10514 }
10515 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010516
Justin Lebar25c4a812016-03-29 16:24:16 +000010517 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010518 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010519 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010520
10521 bool hasComplained() const { return HasComplained; }
10522
Douglas Gregorb491ed32011-02-19 21:32:49 +000010523private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010524 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10525 QualType Discard;
10526 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010527 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010528 }
10529
George Burgess IV6da4c202016-03-23 02:33:58 +000010530 /// \return true if A is considered a better overload candidate for the
10531 /// desired type than B.
10532 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10533 // If A doesn't have exactly the correct type, we don't want to classify it
10534 // as "better" than anything else. This way, the user is required to
10535 // disambiguate for us if there are multiple candidates and no exact match.
10536 return candidateHasExactlyCorrectType(A) &&
10537 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010538 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010539 }
10540
10541 /// \return true if we were able to eliminate all but one overload candidate,
10542 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010543 bool eliminiateSuboptimalOverloadCandidates() {
10544 // Same algorithm as overload resolution -- one pass to pick the "best",
10545 // another pass to be sure that nothing is better than the best.
10546 auto Best = Matches.begin();
10547 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10548 if (isBetterCandidate(I->second, Best->second))
10549 Best = I;
10550
10551 const FunctionDecl *BestFn = Best->second;
10552 auto IsBestOrInferiorToBest = [this, BestFn](
10553 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10554 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10555 };
10556
10557 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10558 // option, so we can potentially give the user a better error
10559 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10560 return false;
10561 Matches[0] = *Best;
10562 Matches.resize(1);
10563 return true;
10564 }
10565
Douglas Gregorb491ed32011-02-19 21:32:49 +000010566 bool isTargetTypeAFunction() const {
10567 return TargetFunctionType->isFunctionType();
10568 }
10569
10570 // [ToType] [Return]
10571
10572 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10573 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10574 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10575 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10576 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10577 }
10578
10579 // return true if any matching specializations were found
10580 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10581 const DeclAccessPair& CurAccessFunPair) {
10582 if (CXXMethodDecl *Method
10583 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10584 // Skip non-static function templates when converting to pointer, and
10585 // static when converting to member pointer.
10586 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10587 return false;
10588 }
10589 else if (TargetTypeIsNonStaticMemberFunction)
10590 return false;
10591
10592 // C++ [over.over]p2:
10593 // If the name is a function template, template argument deduction is
10594 // done (14.8.2.2), and if the argument deduction succeeds, the
10595 // resulting template argument list is used to generate a single
10596 // function template specialization, which is added to the set of
10597 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010598 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010599 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010600 if (Sema::TemplateDeductionResult Result
10601 = S.DeduceTemplateArguments(FunctionTemplate,
10602 &OvlExplicitTemplateArgs,
10603 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010604 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010605 // Make a note of the failed deduction for diagnostics.
10606 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010607 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010608 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010609 return false;
10610 }
10611
Douglas Gregor19a41f12013-04-17 08:45:07 +000010612 // Template argument deduction ensures that we have an exact match or
10613 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010614 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010615 assert(S.isSameOrCompatibleFunctionType(
10616 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010617 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010618
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010619 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010620 return false;
10621
Douglas Gregorb491ed32011-02-19 21:32:49 +000010622 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10623 return true;
10624 }
10625
10626 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10627 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010629 // Skip non-static functions when converting to pointer, and static
10630 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010631 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10632 return false;
10633 }
10634 else if (TargetTypeIsNonStaticMemberFunction)
10635 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010636
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010637 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010638 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010639 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010640 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010641 return false;
10642
Richard Smith2a7d4812013-05-04 07:00:32 +000010643 // If any candidate has a placeholder return type, trigger its deduction
10644 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010645 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10646 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010647 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010648 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010649 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010650
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010651 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010652 return false;
10653
George Burgess IV6da4c202016-03-23 02:33:58 +000010654 // If we're in C, we need to support types that aren't exactly identical.
10655 if (!S.getLangOpts().CPlusPlus ||
10656 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010657 Matches.push_back(std::make_pair(
10658 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010659 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010660 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010661 }
Mike Stump11289f42009-09-09 15:08:12 +000010662 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010663
10664 return false;
10665 }
10666
10667 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10668 bool Ret = false;
10669
10670 // If the overload expression doesn't have the form of a pointer to
10671 // member, don't try to convert it to a pointer-to-member type.
10672 if (IsInvalidFormOfPointerToMemberFunction())
10673 return false;
10674
10675 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10676 E = OvlExpr->decls_end();
10677 I != E; ++I) {
10678 // Look through any using declarations to find the underlying function.
10679 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10680
10681 // C++ [over.over]p3:
10682 // Non-member functions and static member functions match
10683 // targets of type "pointer-to-function" or "reference-to-function."
10684 // Nonstatic member functions match targets of
10685 // type "pointer-to-member-function."
10686 // Note that according to DR 247, the containing class does not matter.
10687 if (FunctionTemplateDecl *FunctionTemplate
10688 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10689 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10690 Ret = true;
10691 }
10692 // If we have explicit template arguments supplied, skip non-templates.
10693 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10694 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10695 Ret = true;
10696 }
10697 assert(Ret || Matches.empty());
10698 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010699 }
10700
Douglas Gregorb491ed32011-02-19 21:32:49 +000010701 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010702 // [...] and any given function template specialization F1 is
10703 // eliminated if the set contains a second function template
10704 // specialization whose function template is more specialized
10705 // than the function template of F1 according to the partial
10706 // ordering rules of 14.5.5.2.
10707
10708 // The algorithm specified above is quadratic. We instead use a
10709 // two-pass algorithm (similar to the one used to identify the
10710 // best viable function in an overload set) that identifies the
10711 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010712
10713 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10714 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10715 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010716
Larisse Voufo98b20f12013-07-19 23:00:19 +000010717 // TODO: It looks like FailedCandidates does not serve much purpose
10718 // here, since the no_viable diagnostic has index 0.
10719 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010720 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010721 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010722 S.PDiag(diag::err_addr_ovl_ambiguous)
10723 << Matches[0].second->getDeclName(),
10724 S.PDiag(diag::note_ovl_candidate)
10725 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010726 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010727
Douglas Gregorb491ed32011-02-19 21:32:49 +000010728 if (Result != MatchesCopy.end()) {
10729 // Make it the first and only element
10730 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10731 Matches[0].second = cast<FunctionDecl>(*Result);
10732 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010733 } else
10734 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010736
Douglas Gregorb491ed32011-02-19 21:32:49 +000010737 void EliminateAllTemplateMatches() {
10738 // [...] any function template specializations in the set are
10739 // eliminated if the set also contains a non-template function, [...]
10740 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010741 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010742 ++I;
10743 else {
10744 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010745 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010746 }
10747 }
10748 }
10749
Artem Belevich94a55e82015-09-22 17:22:59 +000010750 void EliminateSuboptimalCudaMatches() {
10751 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10752 }
10753
Douglas Gregorb491ed32011-02-19 21:32:49 +000010754public:
10755 void ComplainNoMatchesFound() const {
10756 assert(Matches.empty());
10757 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10758 << OvlExpr->getName() << TargetFunctionType
10759 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010760 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010761 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10762 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010763 else {
10764 // We have some deduction failure messages. Use them to diagnose
10765 // the function templates, and diagnose the non-template candidates
10766 // normally.
10767 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10768 IEnd = OvlExpr->decls_end();
10769 I != IEnd; ++I)
10770 if (FunctionDecl *Fun =
10771 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010772 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010773 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010774 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010775 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10776 }
10777 }
10778
Douglas Gregorb491ed32011-02-19 21:32:49 +000010779 bool IsInvalidFormOfPointerToMemberFunction() const {
10780 return TargetTypeIsNonStaticMemberFunction &&
10781 !OvlExprInfo.HasFormOfMemberPointer;
10782 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010783
Douglas Gregorb491ed32011-02-19 21:32:49 +000010784 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10785 // TODO: Should we condition this on whether any functions might
10786 // have matched, or is it more appropriate to do that in callers?
10787 // TODO: a fixit wouldn't hurt.
10788 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10789 << TargetType << OvlExpr->getSourceRange();
10790 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010791
10792 bool IsStaticMemberFunctionFromBoundPointer() const {
10793 return StaticMemberFunctionFromBoundPointer;
10794 }
10795
10796 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10797 S.Diag(OvlExpr->getLocStart(),
10798 diag::err_invalid_form_pointer_member_function)
10799 << OvlExpr->getSourceRange();
10800 }
10801
Douglas Gregorb491ed32011-02-19 21:32:49 +000010802 void ComplainOfInvalidConversion() const {
10803 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10804 << OvlExpr->getName() << TargetType;
10805 }
10806
10807 void ComplainMultipleMatchesFound() const {
10808 assert(Matches.size() > 1);
10809 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10810 << OvlExpr->getName()
10811 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010812 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10813 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010814 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010815
10816 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10817
Douglas Gregorb491ed32011-02-19 21:32:49 +000010818 int getNumMatches() const { return Matches.size(); }
10819
10820 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010821 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010822 return Matches[0].second;
10823 }
10824
10825 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010826 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010827 return &Matches[0].first;
10828 }
10829};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010830}
Richard Smith17c00b42014-11-12 01:24:00 +000010831
Douglas Gregorb491ed32011-02-19 21:32:49 +000010832/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10833/// an overloaded function (C++ [over.over]), where @p From is an
10834/// expression with overloaded function type and @p ToType is the type
10835/// we're trying to resolve to. For example:
10836///
10837/// @code
10838/// int f(double);
10839/// int f(int);
10840///
10841/// int (*pfd)(double) = f; // selects f(double)
10842/// @endcode
10843///
10844/// This routine returns the resulting FunctionDecl if it could be
10845/// resolved, and NULL otherwise. When @p Complain is true, this
10846/// routine will emit diagnostics if there is an error.
10847FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010848Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10849 QualType TargetType,
10850 bool Complain,
10851 DeclAccessPair &FoundResult,
10852 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010853 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010854
10855 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10856 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010857 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010858 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010859 bool ShouldComplain = Complain && !Resolver.hasComplained();
10860 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010861 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10862 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10863 else
10864 Resolver.ComplainNoMatchesFound();
10865 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010866 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010867 Resolver.ComplainMultipleMatchesFound();
10868 else if (NumMatches == 1) {
10869 Fn = Resolver.getMatchingFunctionDecl();
10870 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010871 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10872 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010873 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010874 if (Complain) {
10875 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10876 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10877 else
10878 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10879 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010880 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010881
10882 if (pHadMultipleCandidates)
10883 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010884 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010885}
10886
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010887/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010888/// resolve that function to a single function that can have its address taken.
10889/// This will modify `Pair` iff it returns non-null.
10890///
10891/// This routine can only realistically succeed if all but one candidates in the
10892/// overload set for SrcExpr cannot have their addresses taken.
10893FunctionDecl *
10894Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10895 DeclAccessPair &Pair) {
10896 OverloadExpr::FindResult R = OverloadExpr::find(E);
10897 OverloadExpr *Ovl = R.Expression;
10898 FunctionDecl *Result = nullptr;
10899 DeclAccessPair DAP;
10900 // Don't use the AddressOfResolver because we're specifically looking for
10901 // cases where we have one overload candidate that lacks
10902 // enable_if/pass_object_size/...
10903 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10904 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10905 if (!FD)
10906 return nullptr;
10907
10908 if (!checkAddressOfFunctionIsAvailable(FD))
10909 continue;
10910
10911 // We have more than one result; quit.
10912 if (Result)
10913 return nullptr;
10914 DAP = I.getPair();
10915 Result = FD;
10916 }
10917
10918 if (Result)
10919 Pair = DAP;
10920 return Result;
10921}
10922
George Burgess IVbeca4a32016-06-08 00:34:22 +000010923/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10924/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10925/// will perform access checks, diagnose the use of the resultant decl, and, if
10926/// necessary, perform a function-to-pointer decay.
10927///
10928/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10929/// Otherwise, returns true. This may emit diagnostics and return true.
10930bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10931 ExprResult &SrcExpr) {
10932 Expr *E = SrcExpr.get();
10933 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10934
10935 DeclAccessPair DAP;
10936 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10937 if (!Found)
10938 return false;
10939
10940 // Emitting multiple diagnostics for a function that is both inaccessible and
10941 // unavailable is consistent with our behavior elsewhere. So, always check
10942 // for both.
10943 DiagnoseUseOfDecl(Found, E->getExprLoc());
10944 CheckAddressOfMemberAccess(E, DAP);
10945 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10946 if (Fixed->getType()->isFunctionType())
10947 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10948 else
10949 SrcExpr = Fixed;
10950 return true;
10951}
10952
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010953/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010954/// resolve that overloaded function expression down to a single function.
10955///
10956/// This routine can only resolve template-ids that refer to a single function
10957/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010958/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010959/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010960///
10961/// If no template-ids are found, no diagnostics are emitted and NULL is
10962/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010963FunctionDecl *
10964Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10965 bool Complain,
10966 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010967 // C++ [over.over]p1:
10968 // [...] [Note: any redundant set of parentheses surrounding the
10969 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010970 // C++ [over.over]p1:
10971 // [...] The overloaded function name can be preceded by the &
10972 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010973
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010974 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010975 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010976 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010977
10978 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010979 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010980 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010981
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010982 // Look through all of the overloaded functions, searching for one
10983 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010984 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010985 for (UnresolvedSetIterator I = ovl->decls_begin(),
10986 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010987 // C++0x [temp.arg.explicit]p3:
10988 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010989 // where deduction is not done, if a template argument list is
10990 // specified and it, along with any default template arguments,
10991 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010992 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010993 FunctionTemplateDecl *FunctionTemplate
10994 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010995
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010996 // C++ [over.over]p2:
10997 // If the name is a function template, template argument deduction is
10998 // done (14.8.2.2), and if the argument deduction succeeds, the
10999 // resulting template argument list is used to generate a single
11000 // function template specialization, which is added to the set of
11001 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011002 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011003 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011004 if (TemplateDeductionResult Result
11005 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011006 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011007 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011008 // Make a note of the failed deduction for diagnostics.
11009 // TODO: Actually use the failed-deduction info?
11010 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011011 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011012 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011013 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011014 }
11015
John McCall0009fcc2011-04-26 20:42:42 +000011016 assert(Specialization && "no specialization and no error?");
11017
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011018 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011019 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011020 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011021 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11022 << ovl->getName();
11023 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011024 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011025 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011026 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011027
John McCall0009fcc2011-04-26 20:42:42 +000011028 Matched = Specialization;
11029 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011031
Richard Smith9095e5b2016-11-01 01:31:23 +000011032 if (Matched &&
11033 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011034 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011035
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011036 return Matched;
11037}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011038
Douglas Gregor1beec452011-03-12 01:48:56 +000011039
11040
11041
John McCall50a2c2c2011-10-11 23:14:30 +000011042// Resolve and fix an overloaded expression that can be resolved
11043// because it identifies a single function template specialization.
11044//
Douglas Gregor1beec452011-03-12 01:48:56 +000011045// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011046//
11047// Return true if it was logically possible to so resolve the
11048// expression, regardless of whether or not it succeeded. Always
11049// returns true if 'complain' is set.
11050bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11051 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011052 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011053 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011054 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011055 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011056
John McCall50a2c2c2011-10-11 23:14:30 +000011057 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011058
John McCall0009fcc2011-04-26 20:42:42 +000011059 DeclAccessPair found;
11060 ExprResult SingleFunctionExpression;
11061 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11062 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011063 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011064 SrcExpr = ExprError();
11065 return true;
11066 }
John McCall0009fcc2011-04-26 20:42:42 +000011067
11068 // It is only correct to resolve to an instance method if we're
11069 // resolving a form that's permitted to be a pointer to member.
11070 // Otherwise we'll end up making a bound member expression, which
11071 // is illegal in all the contexts we resolve like this.
11072 if (!ovl.HasFormOfMemberPointer &&
11073 isa<CXXMethodDecl>(fn) &&
11074 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011075 if (!complain) return false;
11076
11077 Diag(ovl.Expression->getExprLoc(),
11078 diag::err_bound_member_function)
11079 << 0 << ovl.Expression->getSourceRange();
11080
11081 // TODO: I believe we only end up here if there's a mix of
11082 // static and non-static candidates (otherwise the expression
11083 // would have 'bound member' type, not 'overload' type).
11084 // Ideally we would note which candidate was chosen and why
11085 // the static candidates were rejected.
11086 SrcExpr = ExprError();
11087 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011088 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011089
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011090 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011091 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011092 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011093
11094 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011095 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011096 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011097 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011098 if (SingleFunctionExpression.isInvalid()) {
11099 SrcExpr = ExprError();
11100 return true;
11101 }
11102 }
John McCall0009fcc2011-04-26 20:42:42 +000011103 }
11104
11105 if (!SingleFunctionExpression.isUsable()) {
11106 if (complain) {
11107 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11108 << ovl.Expression->getName()
11109 << DestTypeForComplaining
11110 << OpRangeForComplaining
11111 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011112 NoteAllOverloadCandidates(SrcExpr.get());
11113
11114 SrcExpr = ExprError();
11115 return true;
11116 }
11117
11118 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011119 }
11120
John McCall50a2c2c2011-10-11 23:14:30 +000011121 SrcExpr = SingleFunctionExpression;
11122 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011123}
11124
Douglas Gregorcabea402009-09-22 15:41:20 +000011125/// \brief Add a single candidate to the overload set.
11126static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011127 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011128 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011129 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011130 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011131 bool PartialOverloading,
11132 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011133 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011134 if (isa<UsingShadowDecl>(Callee))
11135 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11136
Douglas Gregorcabea402009-09-22 15:41:20 +000011137 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011138 if (ExplicitTemplateArgs) {
11139 assert(!KnownValid && "Explicit template arguments?");
11140 return;
11141 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011142 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11143 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011144 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011145 return;
John McCalld14a8642009-11-21 08:51:07 +000011146 }
11147
11148 if (FunctionTemplateDecl *FuncTemplate
11149 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011150 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011151 ExplicitTemplateArgs, Args, CandidateSet,
11152 /*SuppressUsedConversions=*/false,
11153 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011154 return;
11155 }
11156
Richard Smith95ce4f62011-06-26 22:19:54 +000011157 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011158}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011159
Douglas Gregorcabea402009-09-22 15:41:20 +000011160/// \brief Add the overload candidates named by callee and/or found by argument
11161/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011162void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011163 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011164 OverloadCandidateSet &CandidateSet,
11165 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011166
11167#ifndef NDEBUG
11168 // Verify that ArgumentDependentLookup is consistent with the rules
11169 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011170 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011171 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11172 // and let Y be the lookup set produced by argument dependent
11173 // lookup (defined as follows). If X contains
11174 //
11175 // -- a declaration of a class member, or
11176 //
11177 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011178 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011179 //
11180 // -- a declaration that is neither a function or a function
11181 // template
11182 //
11183 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011184
John McCall57500772009-12-16 12:17:52 +000011185 if (ULE->requiresADL()) {
11186 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11187 E = ULE->decls_end(); I != E; ++I) {
11188 assert(!(*I)->getDeclContext()->isRecord());
11189 assert(isa<UsingShadowDecl>(*I) ||
11190 !(*I)->getDeclContext()->isFunctionOrMethod());
11191 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011192 }
11193 }
11194#endif
11195
John McCall57500772009-12-16 12:17:52 +000011196 // It would be nice to avoid this copy.
11197 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011198 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011199 if (ULE->hasExplicitTemplateArgs()) {
11200 ULE->copyTemplateArgumentsInto(TABuffer);
11201 ExplicitTemplateArgs = &TABuffer;
11202 }
11203
11204 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11205 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011206 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11207 CandidateSet, PartialOverloading,
11208 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011209
John McCall57500772009-12-16 12:17:52 +000011210 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011211 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011212 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011213 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011214}
John McCalld681c392009-12-16 08:11:27 +000011215
Richard Smith0603bbb2013-06-12 22:56:54 +000011216/// Determine whether a declaration with the specified name could be moved into
11217/// a different namespace.
11218static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11219 switch (Name.getCXXOverloadedOperator()) {
11220 case OO_New: case OO_Array_New:
11221 case OO_Delete: case OO_Array_Delete:
11222 return false;
11223
11224 default:
11225 return true;
11226 }
11227}
11228
Richard Smith998a5912011-06-05 22:42:48 +000011229/// Attempt to recover from an ill-formed use of a non-dependent name in a
11230/// template, where the non-dependent name was declared after the template
11231/// was defined. This is common in code written for a compilers which do not
11232/// correctly implement two-stage name lookup.
11233///
11234/// Returns true if a viable candidate was found and a diagnostic was issued.
11235static bool
11236DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11237 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011238 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011239 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011240 ArrayRef<Expr *> Args,
11241 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011242 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11243 return false;
11244
11245 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011246 if (DC->isTransparentContext())
11247 continue;
11248
Richard Smith998a5912011-06-05 22:42:48 +000011249 SemaRef.LookupQualifiedName(R, DC);
11250
11251 if (!R.empty()) {
11252 R.suppressDiagnostics();
11253
11254 if (isa<CXXRecordDecl>(DC)) {
11255 // Don't diagnose names we find in classes; we get much better
11256 // diagnostics for these from DiagnoseEmptyLookup.
11257 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011258 if (DoDiagnoseEmptyLookup)
11259 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011260 return false;
11261 }
11262
Richard Smith100b24a2014-04-17 01:52:14 +000011263 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11265 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011266 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011267 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011268
11269 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011270 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011271 // No viable functions. Don't bother the user with notes for functions
11272 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011273 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011274 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011275 }
Richard Smith998a5912011-06-05 22:42:48 +000011276
11277 // Find the namespaces where ADL would have looked, and suggest
11278 // declaring the function there instead.
11279 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11280 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011281 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011282 AssociatedNamespaces,
11283 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011284 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011285 if (canBeDeclaredInNamespace(R.getLookupName())) {
11286 DeclContext *Std = SemaRef.getStdNamespace();
11287 for (Sema::AssociatedNamespaceSet::iterator
11288 it = AssociatedNamespaces.begin(),
11289 end = AssociatedNamespaces.end(); it != end; ++it) {
11290 // Never suggest declaring a function within namespace 'std'.
11291 if (Std && Std->Encloses(*it))
11292 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011293
Richard Smith0603bbb2013-06-12 22:56:54 +000011294 // Never suggest declaring a function within a namespace with a
11295 // reserved name, like __gnu_cxx.
11296 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11297 if (NS &&
11298 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11299 continue;
11300
11301 SuggestedNamespaces.insert(*it);
11302 }
Richard Smith998a5912011-06-05 22:42:48 +000011303 }
11304
11305 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11306 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011307 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011308 SemaRef.Diag(Best->Function->getLocation(),
11309 diag::note_not_found_by_two_phase_lookup)
11310 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011311 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011312 SemaRef.Diag(Best->Function->getLocation(),
11313 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011314 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011315 } else {
11316 // FIXME: It would be useful to list the associated namespaces here,
11317 // but the diagnostics infrastructure doesn't provide a way to produce
11318 // a localized representation of a list of items.
11319 SemaRef.Diag(Best->Function->getLocation(),
11320 diag::note_not_found_by_two_phase_lookup)
11321 << R.getLookupName() << 2;
11322 }
11323
11324 // Try to recover by calling this function.
11325 return true;
11326 }
11327
11328 R.clear();
11329 }
11330
11331 return false;
11332}
11333
11334/// Attempt to recover from ill-formed use of a non-dependent operator in a
11335/// template, where the non-dependent operator was declared after the template
11336/// was defined.
11337///
11338/// Returns true if a viable candidate was found and a diagnostic was issued.
11339static bool
11340DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11341 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011342 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011343 DeclarationName OpName =
11344 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11345 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11346 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011347 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011348 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011349}
11350
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011351namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011352class BuildRecoveryCallExprRAII {
11353 Sema &SemaRef;
11354public:
11355 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11356 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11357 SemaRef.IsBuildingRecoveryCallExpr = true;
11358 }
11359
11360 ~BuildRecoveryCallExprRAII() {
11361 SemaRef.IsBuildingRecoveryCallExpr = false;
11362 }
11363};
11364
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011365}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011366
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011367static std::unique_ptr<CorrectionCandidateCallback>
11368MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11369 bool HasTemplateArgs, bool AllowTypoCorrection) {
11370 if (!AllowTypoCorrection)
11371 return llvm::make_unique<NoTypoCorrectionCCC>();
11372 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11373 HasTemplateArgs, ME);
11374}
11375
John McCalld681c392009-12-16 08:11:27 +000011376/// Attempts to recover from a call where no functions were found.
11377///
11378/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011379static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011380BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011381 UnresolvedLookupExpr *ULE,
11382 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011383 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011384 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011385 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011386 // Do not try to recover if it is already building a recovery call.
11387 // This stops infinite loops for template instantiations like
11388 //
11389 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11390 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11391 //
11392 if (SemaRef.IsBuildingRecoveryCallExpr)
11393 return ExprError();
11394 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011395
11396 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011397 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011398 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011399
John McCall57500772009-12-16 12:17:52 +000011400 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011401 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011402 if (ULE->hasExplicitTemplateArgs()) {
11403 ULE->copyTemplateArgumentsInto(TABuffer);
11404 ExplicitTemplateArgs = &TABuffer;
11405 }
11406
John McCalld681c392009-12-16 08:11:27 +000011407 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11408 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011409 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011410 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011411 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011412 ExplicitTemplateArgs, Args,
11413 &DoDiagnoseEmptyLookup) &&
11414 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11415 S, SS, R,
11416 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11417 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11418 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011419 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011420
John McCall57500772009-12-16 12:17:52 +000011421 assert(!R.empty() && "lookup results empty despite recovery");
11422
Richard Smith22a250c2016-12-19 04:08:53 +000011423 // If recovery created an ambiguity, just bail out.
11424 if (R.isAmbiguous()) {
11425 R.suppressDiagnostics();
11426 return ExprError();
11427 }
11428
John McCall57500772009-12-16 12:17:52 +000011429 // Build an implicit member call if appropriate. Just drop the
11430 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011431 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011432 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011433 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11434 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011435 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011436 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011437 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011438 else
11439 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11440
11441 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011442 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011443
11444 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011445 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011446 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011447 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011448 MultiExprArg(Args.data(), Args.size()),
11449 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011450}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011451
Sam Panzer0f384432012-08-21 00:52:01 +000011452/// \brief Constructs and populates an OverloadedCandidateSet from
11453/// the given function.
11454/// \returns true when an the ExprResult output parameter has been set.
11455bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11456 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011457 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011458 SourceLocation RParenLoc,
11459 OverloadCandidateSet *CandidateSet,
11460 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011461#ifndef NDEBUG
11462 if (ULE->requiresADL()) {
11463 // To do ADL, we must have found an unqualified name.
11464 assert(!ULE->getQualifier() && "qualified name with ADL");
11465
11466 // We don't perform ADL for implicit declarations of builtins.
11467 // Verify that this was correctly set up.
11468 FunctionDecl *F;
11469 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11470 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11471 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011472 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011473
John McCall57500772009-12-16 12:17:52 +000011474 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011475 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011476 }
John McCall57500772009-12-16 12:17:52 +000011477#endif
11478
John McCall4124c492011-10-17 18:40:02 +000011479 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011480 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011481 *Result = ExprError();
11482 return true;
11483 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011484
John McCall57500772009-12-16 12:17:52 +000011485 // Add the functions denoted by the callee to the set of candidate
11486 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011487 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011488
Hans Wennborgb2747382015-06-12 21:23:23 +000011489 if (getLangOpts().MSVCCompat &&
11490 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011491 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11492
11493 OverloadCandidateSet::iterator Best;
11494 if (CandidateSet->empty() ||
11495 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11496 OR_No_Viable_Function) {
11497 // In Microsoft mode, if we are inside a template class member function then
11498 // create a type dependent CallExpr. The goal is to postpone name lookup
11499 // to instantiation time to be able to search into type dependent base
11500 // classes.
11501 CallExpr *CE = new (Context) CallExpr(
11502 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011503 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011504 CE->setValueDependent(true);
11505 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011506 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011507 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011508 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011509 }
John McCalld681c392009-12-16 08:11:27 +000011510
Hans Wennborg64937c62015-06-11 21:21:57 +000011511 if (CandidateSet->empty())
11512 return false;
11513
John McCall4124c492011-10-17 18:40:02 +000011514 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011515 return false;
11516}
John McCall4124c492011-10-17 18:40:02 +000011517
Sam Panzer0f384432012-08-21 00:52:01 +000011518/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11519/// the completed call expression. If overload resolution fails, emits
11520/// diagnostics and returns ExprError()
11521static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11522 UnresolvedLookupExpr *ULE,
11523 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011524 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011525 SourceLocation RParenLoc,
11526 Expr *ExecConfig,
11527 OverloadCandidateSet *CandidateSet,
11528 OverloadCandidateSet::iterator *Best,
11529 OverloadingResult OverloadResult,
11530 bool AllowTypoCorrection) {
11531 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011532 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011533 RParenLoc, /*EmptyLookup=*/true,
11534 AllowTypoCorrection);
11535
11536 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011537 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011538 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011539 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011540 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11541 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011542 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011543 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11544 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011545 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011546
Richard Smith998a5912011-06-05 22:42:48 +000011547 case OR_No_Viable_Function: {
11548 // Try to recover by looking for viable functions which the user might
11549 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011550 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011551 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011552 /*EmptyLookup=*/false,
11553 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011554 if (!Recovery.isInvalid())
11555 return Recovery;
11556
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011557 // If the user passes in a function that we can't take the address of, we
11558 // generally end up emitting really bad error messages. Here, we attempt to
11559 // emit better ones.
11560 for (const Expr *Arg : Args) {
11561 if (!Arg->getType()->isFunctionType())
11562 continue;
11563 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11564 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11565 if (FD &&
11566 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11567 Arg->getExprLoc()))
11568 return ExprError();
11569 }
11570 }
11571
11572 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11573 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011574 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011575 break;
Richard Smith998a5912011-06-05 22:42:48 +000011576 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011577
11578 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011579 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011580 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011581 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011582 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011583
Sam Panzer0f384432012-08-21 00:52:01 +000011584 case OR_Deleted: {
11585 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11586 << (*Best)->Function->isDeleted()
11587 << ULE->getName()
11588 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11589 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011590 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011591
Sam Panzer0f384432012-08-21 00:52:01 +000011592 // We emitted an error for the unvailable/deleted function call but keep
11593 // the call in the AST.
11594 FunctionDecl *FDecl = (*Best)->Function;
11595 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011596 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11597 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011598 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011599 }
11600
Douglas Gregorb412e172010-07-25 18:17:45 +000011601 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011602 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011603}
11604
George Burgess IV7204ed92016-01-07 02:26:57 +000011605static void markUnaddressableCandidatesUnviable(Sema &S,
11606 OverloadCandidateSet &CS) {
11607 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11608 if (I->Viable &&
11609 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11610 I->Viable = false;
11611 I->FailureKind = ovl_fail_addr_not_available;
11612 }
11613 }
11614}
11615
Sam Panzer0f384432012-08-21 00:52:01 +000011616/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11617/// (which eventually refers to the declaration Func) and the call
11618/// arguments Args/NumArgs, attempt to resolve the function call down
11619/// to a specific function. If overload resolution succeeds, returns
11620/// the call expression produced by overload resolution.
11621/// Otherwise, emits diagnostics and returns ExprError.
11622ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11623 UnresolvedLookupExpr *ULE,
11624 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011625 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011626 SourceLocation RParenLoc,
11627 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011628 bool AllowTypoCorrection,
11629 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011630 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11631 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011632 ExprResult result;
11633
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011634 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11635 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011636 return result;
11637
George Burgess IV7204ed92016-01-07 02:26:57 +000011638 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11639 // functions that aren't addressible are considered unviable.
11640 if (CalleesAddressIsTaken)
11641 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11642
Sam Panzer0f384432012-08-21 00:52:01 +000011643 OverloadCandidateSet::iterator Best;
11644 OverloadingResult OverloadResult =
11645 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11646
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011647 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011648 RParenLoc, ExecConfig, &CandidateSet,
11649 &Best, OverloadResult,
11650 AllowTypoCorrection);
11651}
11652
John McCall4c4c1df2010-01-26 03:27:55 +000011653static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011654 return Functions.size() > 1 ||
11655 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11656}
11657
Douglas Gregor084d8552009-03-13 23:49:33 +000011658/// \brief Create a unary operation that may resolve to an overloaded
11659/// operator.
11660///
11661/// \param OpLoc The location of the operator itself (e.g., '*').
11662///
Craig Toppera92ffb02015-12-10 08:51:49 +000011663/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011664///
James Dennett18348b62012-06-22 08:52:37 +000011665/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011666/// considered by overload resolution. The caller needs to build this
11667/// set based on the context using, e.g.,
11668/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11669/// set should not contain any member functions; those will be added
11670/// by CreateOverloadedUnaryOp().
11671///
James Dennett91738ff2012-06-22 10:32:46 +000011672/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011673ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011674Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011675 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011676 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011677 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11678 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11679 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011680 // TODO: provide better source location info.
11681 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011682
John McCall4124c492011-10-17 18:40:02 +000011683 if (checkPlaceholderForOverload(*this, Input))
11684 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011685
Craig Topperc3ec1492014-05-26 06:22:03 +000011686 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011687 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011688
Douglas Gregor084d8552009-03-13 23:49:33 +000011689 // For post-increment and post-decrement, add the implicit '0' as
11690 // the second argument, so that we know this is a post-increment or
11691 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011692 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011693 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011694 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11695 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011696 NumArgs = 2;
11697 }
11698
Richard Smithe54c3072013-05-05 15:51:06 +000011699 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11700
Douglas Gregor084d8552009-03-13 23:49:33 +000011701 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011702 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011703 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11704 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011705
Craig Topperc3ec1492014-05-26 06:22:03 +000011706 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011707 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011708 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011709 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011710 /*ADL*/ true, IsOverloaded(Fns),
11711 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011712 return new (Context)
11713 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11714 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011715 }
11716
11717 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011718 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011719
11720 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011721 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011722
11723 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011724 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011725
John McCall4c4c1df2010-01-26 03:27:55 +000011726 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011727 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011728 /*ExplicitTemplateArgs*/nullptr,
11729 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011730
Douglas Gregor084d8552009-03-13 23:49:33 +000011731 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011732 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011733
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011734 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11735
Douglas Gregor084d8552009-03-13 23:49:33 +000011736 // Perform overload resolution.
11737 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011738 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011739 case OR_Success: {
11740 // We found a built-in operator or an overloaded operator.
11741 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011742
Douglas Gregor084d8552009-03-13 23:49:33 +000011743 if (FnDecl) {
11744 // We matched an overloaded operator. Build a call to that
11745 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011746
Douglas Gregor084d8552009-03-13 23:49:33 +000011747 // Convert the arguments.
11748 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011749 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011750
John Wiegley01296292011-04-08 18:41:53 +000011751 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011752 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011753 Best->FoundDecl, Method);
11754 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011755 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011756 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011757 } else {
11758 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011759 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011760 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011761 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011762 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011763 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011764 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011765 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011766 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011767 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011768 }
11769
Douglas Gregor084d8552009-03-13 23:49:33 +000011770 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011771 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011772 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011773 if (FnExpr.isInvalid())
11774 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011775
Richard Smithc1564702013-11-15 02:58:23 +000011776 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011777 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011778 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11779 ResultTy = ResultTy.getNonLValueExprType(Context);
11780
Eli Friedman030eee42009-11-18 03:58:17 +000011781 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011782 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011783 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011784 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011785
Alp Toker314cc812014-01-25 16:55:45 +000011786 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011787 return ExprError();
11788
John McCallb268a282010-08-23 23:25:46 +000011789 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011790 } else {
11791 // We matched a built-in operator. Convert the arguments, then
11792 // break out so that we will build the appropriate built-in
11793 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011794 ExprResult InputRes =
11795 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11796 Best->Conversions[0], AA_Passing);
11797 if (InputRes.isInvalid())
11798 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011799 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011800 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011801 }
John Wiegley01296292011-04-08 18:41:53 +000011802 }
11803
11804 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011805 // This is an erroneous use of an operator which can be overloaded by
11806 // a non-member function. Check for non-member operators which were
11807 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011808 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011809 // FIXME: Recover by calling the found function.
11810 return ExprError();
11811
John Wiegley01296292011-04-08 18:41:53 +000011812 // No viable function; fall through to handling this as a
11813 // built-in operator, which will produce an error message for us.
11814 break;
11815
11816 case OR_Ambiguous:
11817 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11818 << UnaryOperator::getOpcodeStr(Opc)
11819 << Input->getType()
11820 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011821 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011822 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11823 return ExprError();
11824
11825 case OR_Deleted:
11826 Diag(OpLoc, diag::err_ovl_deleted_oper)
11827 << Best->Function->isDeleted()
11828 << UnaryOperator::getOpcodeStr(Opc)
11829 << getDeletedOrUnavailableSuffix(Best->Function)
11830 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011831 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011832 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011833 return ExprError();
11834 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011835
11836 // Either we found no viable overloaded operator or we matched a
11837 // built-in operator. In either case, fall through to trying to
11838 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011839 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011840}
11841
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011842/// \brief Create a binary operation that may resolve to an overloaded
11843/// operator.
11844///
11845/// \param OpLoc The location of the operator itself (e.g., '+').
11846///
Craig Toppera92ffb02015-12-10 08:51:49 +000011847/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011848///
James Dennett18348b62012-06-22 08:52:37 +000011849/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011850/// considered by overload resolution. The caller needs to build this
11851/// set based on the context using, e.g.,
11852/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11853/// set should not contain any member functions; those will be added
11854/// by CreateOverloadedBinOp().
11855///
11856/// \param LHS Left-hand argument.
11857/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011858ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011859Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011860 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011861 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011862 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011863 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011864 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011865
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011866 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11867 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11868
11869 // If either side is type-dependent, create an appropriate dependent
11870 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011871 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011872 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011873 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011874 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011875 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011876 return new (Context) BinaryOperator(
11877 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11878 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011879
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011880 return new (Context) CompoundAssignOperator(
11881 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11882 Context.DependentTy, Context.DependentTy, OpLoc,
11883 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011884 }
John McCall4c4c1df2010-01-26 03:27:55 +000011885
11886 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011887 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011888 // TODO: provide better source location info in DNLoc component.
11889 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011890 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011891 = UnresolvedLookupExpr::Create(Context, NamingClass,
11892 NestedNameSpecifierLoc(), OpNameInfo,
11893 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011894 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011895 return new (Context)
11896 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11897 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011898 }
11899
John McCall4124c492011-10-17 18:40:02 +000011900 // Always do placeholder-like conversions on the RHS.
11901 if (checkPlaceholderForOverload(*this, Args[1]))
11902 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011903
John McCall526ab472011-10-25 17:37:35 +000011904 // Do placeholder-like conversion on the LHS; note that we should
11905 // not get here with a PseudoObject LHS.
11906 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011907 if (checkPlaceholderForOverload(*this, Args[0]))
11908 return ExprError();
11909
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011910 // If this is the assignment operator, we only perform overload resolution
11911 // if the left-hand side is a class or enumeration type. This is actually
11912 // a hack. The standard requires that we do overload resolution between the
11913 // various built-in candidates, but as DR507 points out, this can lead to
11914 // problems. So we do it this way, which pretty much follows what GCC does.
11915 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011916 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011917 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011918
John McCalle26a8722010-12-04 08:14:53 +000011919 // If this is the .* operator, which is not overloadable, just
11920 // create a built-in binary operator.
11921 if (Opc == BO_PtrMemD)
11922 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11923
Douglas Gregor084d8552009-03-13 23:49:33 +000011924 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011925 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011926
11927 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011928 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011929
11930 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011931 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011932
Richard Smith0daabd72014-09-23 20:31:39 +000011933 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11934 // performed for an assignment operator (nor for operator[] nor operator->,
11935 // which don't get here).
11936 if (Opc != BO_Assign)
11937 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11938 /*ExplicitTemplateArgs*/ nullptr,
11939 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011940
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011941 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011942 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011943
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011944 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11945
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011946 // Perform overload resolution.
11947 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011948 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011949 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011950 // We found a built-in operator or an overloaded operator.
11951 FunctionDecl *FnDecl = Best->Function;
11952
11953 if (FnDecl) {
11954 // We matched an overloaded operator. Build a call to that
11955 // operator.
11956
11957 // Convert the arguments.
11958 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011959 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011960 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011961
Chandler Carruth8e543b32010-12-12 08:17:55 +000011962 ExprResult Arg1 =
11963 PerformCopyInitialization(
11964 InitializedEntity::InitializeParameter(Context,
11965 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011966 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011967 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011968 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011969
John Wiegley01296292011-04-08 18:41:53 +000011970 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011971 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011972 Best->FoundDecl, Method);
11973 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011974 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011975 Args[0] = Arg0.getAs<Expr>();
11976 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011977 } else {
11978 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011979 ExprResult Arg0 = PerformCopyInitialization(
11980 InitializedEntity::InitializeParameter(Context,
11981 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011982 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011983 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011984 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011985
Chandler Carruth8e543b32010-12-12 08:17:55 +000011986 ExprResult Arg1 =
11987 PerformCopyInitialization(
11988 InitializedEntity::InitializeParameter(Context,
11989 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011990 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011991 if (Arg1.isInvalid())
11992 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011993 Args[0] = LHS = Arg0.getAs<Expr>();
11994 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011995 }
11996
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011997 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011998 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011999 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012000 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012001 if (FnExpr.isInvalid())
12002 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012003
Richard Smithc1564702013-11-15 02:58:23 +000012004 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012005 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012006 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12007 ResultTy = ResultTy.getNonLValueExprType(Context);
12008
John McCallb268a282010-08-23 23:25:46 +000012009 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012010 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012011 Args, ResultTy, VK, OpLoc,
12012 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012013
Alp Toker314cc812014-01-25 16:55:45 +000012014 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012015 FnDecl))
12016 return ExprError();
12017
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012018 ArrayRef<const Expr *> ArgsArray(Args, 2);
12019 // Cut off the implicit 'this'.
12020 if (isa<CXXMethodDecl>(FnDecl))
12021 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012022
12023 // Check for a self move.
12024 if (Op == OO_Equal)
12025 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12026
Douglas Gregorb4866e82015-06-19 18:13:19 +000012027 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012028 TheCall->getSourceRange(), VariadicDoesNotApply);
12029
John McCallb268a282010-08-23 23:25:46 +000012030 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012031 } else {
12032 // We matched a built-in operator. Convert the arguments, then
12033 // break out so that we will build the appropriate built-in
12034 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012035 ExprResult ArgsRes0 =
12036 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12037 Best->Conversions[0], AA_Passing);
12038 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012039 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012040 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012041
John Wiegley01296292011-04-08 18:41:53 +000012042 ExprResult ArgsRes1 =
12043 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12044 Best->Conversions[1], AA_Passing);
12045 if (ArgsRes1.isInvalid())
12046 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012047 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012048 break;
12049 }
12050 }
12051
Douglas Gregor66950a32009-09-30 21:46:01 +000012052 case OR_No_Viable_Function: {
12053 // C++ [over.match.oper]p9:
12054 // If the operator is the operator , [...] and there are no
12055 // viable functions, then the operator is assumed to be the
12056 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012057 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012058 break;
12059
Chandler Carruth8e543b32010-12-12 08:17:55 +000012060 // For class as left operand for assignment or compound assigment
12061 // operator do not fall through to handling in built-in, but report that
12062 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012063 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012064 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012065 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012066 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12067 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012068 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012069 if (Args[0]->getType()->isIncompleteType()) {
12070 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12071 << Args[0]->getType()
12072 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12073 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012074 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012075 // This is an erroneous use of an operator which can be overloaded by
12076 // a non-member function. Check for non-member operators which were
12077 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012078 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012079 // FIXME: Recover by calling the found function.
12080 return ExprError();
12081
Douglas Gregor66950a32009-09-30 21:46:01 +000012082 // No viable function; try to create a built-in operation, which will
12083 // produce an error. Then, show the non-viable candidates.
12084 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012086 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012087 "C++ binary operator overloading is missing candidates!");
12088 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012089 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012090 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012091 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012092 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012093
12094 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012095 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012096 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012097 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012098 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012099 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012100 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012101 return ExprError();
12102
12103 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012104 if (isImplicitlyDeleted(Best->Function)) {
12105 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12106 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012107 << Context.getRecordType(Method->getParent())
12108 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012109
Richard Smithde1a4872012-12-28 12:23:24 +000012110 // The user probably meant to call this special member. Just
12111 // explain why it's deleted.
12112 NoteDeletedFunction(Method);
12113 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012114 } else {
12115 Diag(OpLoc, diag::err_ovl_deleted_oper)
12116 << Best->Function->isDeleted()
12117 << BinaryOperator::getOpcodeStr(Opc)
12118 << getDeletedOrUnavailableSuffix(Best->Function)
12119 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12120 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012122 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012123 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012124 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012125
Douglas Gregor66950a32009-09-30 21:46:01 +000012126 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012127 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012128}
12129
John McCalldadc5752010-08-24 06:29:42 +000012130ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012131Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12132 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012133 Expr *Base, Expr *Idx) {
12134 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012135 DeclarationName OpName =
12136 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12137
12138 // If either side is type-dependent, create an appropriate dependent
12139 // expression.
12140 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12141
Craig Topperc3ec1492014-05-26 06:22:03 +000012142 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012143 // CHECKME: no 'operator' keyword?
12144 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12145 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012146 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012147 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012148 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012149 /*ADL*/ true, /*Overloaded*/ false,
12150 UnresolvedSetIterator(),
12151 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012152 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012153
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012154 return new (Context)
12155 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12156 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012157 }
12158
John McCall4124c492011-10-17 18:40:02 +000012159 // Handle placeholders on both operands.
12160 if (checkPlaceholderForOverload(*this, Args[0]))
12161 return ExprError();
12162 if (checkPlaceholderForOverload(*this, Args[1]))
12163 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012164
Sebastian Redladba46e2009-10-29 20:17:01 +000012165 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012166 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012167
12168 // Subscript can only be overloaded as a member function.
12169
12170 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012171 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012172
12173 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012174 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012175
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012176 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12177
Sebastian Redladba46e2009-10-29 20:17:01 +000012178 // Perform overload resolution.
12179 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012180 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012181 case OR_Success: {
12182 // We found a built-in operator or an overloaded operator.
12183 FunctionDecl *FnDecl = Best->Function;
12184
12185 if (FnDecl) {
12186 // We matched an overloaded operator. Build a call to that
12187 // operator.
12188
John McCalla0296f72010-03-19 07:35:19 +000012189 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012190
Sebastian Redladba46e2009-10-29 20:17:01 +000012191 // Convert the arguments.
12192 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012193 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012194 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012195 Best->FoundDecl, Method);
12196 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012197 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012198 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012199
Anders Carlssona68e51e2010-01-29 18:37:50 +000012200 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012201 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012202 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012203 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012204 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012205 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012206 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012207 if (InputInit.isInvalid())
12208 return ExprError();
12209
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012210 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012211
Sebastian Redladba46e2009-10-29 20:17:01 +000012212 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012213 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12214 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012215 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012216 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012217 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012218 OpLocInfo.getLoc(),
12219 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012220 if (FnExpr.isInvalid())
12221 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012222
Richard Smithc1564702013-11-15 02:58:23 +000012223 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012224 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012225 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12226 ResultTy = ResultTy.getNonLValueExprType(Context);
12227
John McCallb268a282010-08-23 23:25:46 +000012228 CXXOperatorCallExpr *TheCall =
12229 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012230 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012231 ResultTy, VK, RLoc,
12232 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012233
Alp Toker314cc812014-01-25 16:55:45 +000012234 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012235 return ExprError();
12236
John McCallb268a282010-08-23 23:25:46 +000012237 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012238 } else {
12239 // We matched a built-in operator. Convert the arguments, then
12240 // break out so that we will build the appropriate built-in
12241 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012242 ExprResult ArgsRes0 =
12243 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12244 Best->Conversions[0], AA_Passing);
12245 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012246 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012247 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012248
12249 ExprResult ArgsRes1 =
12250 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12251 Best->Conversions[1], AA_Passing);
12252 if (ArgsRes1.isInvalid())
12253 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012254 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012255
12256 break;
12257 }
12258 }
12259
12260 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012261 if (CandidateSet.empty())
12262 Diag(LLoc, diag::err_ovl_no_oper)
12263 << Args[0]->getType() << /*subscript*/ 0
12264 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12265 else
12266 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12267 << Args[0]->getType()
12268 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012270 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012271 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012272 }
12273
12274 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012275 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012276 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012277 << Args[0]->getType() << Args[1]->getType()
12278 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012279 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012280 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012281 return ExprError();
12282
12283 case OR_Deleted:
12284 Diag(LLoc, diag::err_ovl_deleted_oper)
12285 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012286 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012287 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012288 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012289 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012290 return ExprError();
12291 }
12292
12293 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012294 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012295}
12296
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012297/// BuildCallToMemberFunction - Build a call to a member
12298/// function. MemExpr is the expression that refers to the member
12299/// function (and includes the object parameter), Args/NumArgs are the
12300/// arguments to the function call (not including the object
12301/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012302/// expression refers to a non-static member function or an overloaded
12303/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012304ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012305Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012306 SourceLocation LParenLoc,
12307 MultiExprArg Args,
12308 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012309 assert(MemExprE->getType() == Context.BoundMemberTy ||
12310 MemExprE->getType() == Context.OverloadTy);
12311
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012312 // Dig out the member expression. This holds both the object
12313 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012314 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012315
John McCall0009fcc2011-04-26 20:42:42 +000012316 // Determine whether this is a call to a pointer-to-member function.
12317 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12318 assert(op->getType() == Context.BoundMemberTy);
12319 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12320
12321 QualType fnType =
12322 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12323
12324 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12325 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012326 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012327
12328 // Check that the object type isn't more qualified than the
12329 // member function we're calling.
12330 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12331
12332 QualType objectType = op->getLHS()->getType();
12333 if (op->getOpcode() == BO_PtrMemI)
12334 objectType = objectType->castAs<PointerType>()->getPointeeType();
12335 Qualifiers objectQuals = objectType.getQualifiers();
12336
12337 Qualifiers difference = objectQuals - funcQuals;
12338 difference.removeObjCGCAttr();
12339 difference.removeAddressSpace();
12340 if (difference) {
12341 std::string qualsString = difference.getAsString();
12342 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12343 << fnType.getUnqualifiedType()
12344 << qualsString
12345 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12346 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012347
John McCall0009fcc2011-04-26 20:42:42 +000012348 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012349 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012350 resultType, valueKind, RParenLoc);
12351
Alp Toker314cc812014-01-25 16:55:45 +000012352 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012353 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012354 return ExprError();
12355
Craig Topperc3ec1492014-05-26 06:22:03 +000012356 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012357 return ExprError();
12358
Richard Trieu9be9c682013-06-22 02:30:38 +000012359 if (CheckOtherCall(call, proto))
12360 return ExprError();
12361
John McCall0009fcc2011-04-26 20:42:42 +000012362 return MaybeBindToTemporary(call);
12363 }
12364
David Majnemerced8bdf2015-02-25 17:36:15 +000012365 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12366 return new (Context)
12367 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12368
John McCall4124c492011-10-17 18:40:02 +000012369 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012370 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012371 return ExprError();
12372
John McCall10eae182009-11-30 22:42:35 +000012373 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012374 CXXMethodDecl *Method = nullptr;
12375 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12376 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012377 if (isa<MemberExpr>(NakedMemExpr)) {
12378 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012379 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012380 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012381 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012382 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012383 } else {
12384 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012385 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012386
John McCall6e9f8f62009-12-03 04:06:58 +000012387 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012388 Expr::Classification ObjectClassification
12389 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12390 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012391
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012392 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012393 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12394 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012395
John McCall2d74de92009-12-01 22:10:20 +000012396 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012397 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012398 if (UnresExpr->hasExplicitTemplateArgs()) {
12399 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12400 TemplateArgs = &TemplateArgsBuffer;
12401 }
12402
John McCall10eae182009-11-30 22:42:35 +000012403 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12404 E = UnresExpr->decls_end(); I != E; ++I) {
12405
John McCall6e9f8f62009-12-03 04:06:58 +000012406 NamedDecl *Func = *I;
12407 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12408 if (isa<UsingShadowDecl>(Func))
12409 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12410
Douglas Gregor02824322011-01-26 19:30:28 +000012411
Francois Pichet64225792011-01-18 05:04:39 +000012412 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012413 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012414 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012415 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012416 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012417 // If explicit template arguments were provided, we can't call a
12418 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012419 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012420 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012421
John McCalla0296f72010-03-19 07:35:19 +000012422 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012423 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012424 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012425 } else {
John McCall10eae182009-11-30 22:42:35 +000012426 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012427 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012428 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012429 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012430 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012431 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012432 }
Mike Stump11289f42009-09-09 15:08:12 +000012433
John McCall10eae182009-11-30 22:42:35 +000012434 DeclarationName DeclName = UnresExpr->getMemberName();
12435
John McCall4124c492011-10-17 18:40:02 +000012436 UnbridgedCasts.restore();
12437
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012438 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012439 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012440 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012441 case OR_Success:
12442 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012443 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012444 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012445 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12446 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012447 // If FoundDecl is different from Method (such as if one is a template
12448 // and the other a specialization), make sure DiagnoseUseOfDecl is
12449 // called on both.
12450 // FIXME: This would be more comprehensively addressed by modifying
12451 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12452 // being used.
12453 if (Method != FoundDecl.getDecl() &&
12454 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12455 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012456 break;
12457
12458 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012459 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012460 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012461 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012462 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012463 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012464 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012465
12466 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012467 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012468 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012469 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012470 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012471 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012472
12473 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012474 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012475 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012476 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012477 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012478 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012480 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012481 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012482 }
12483
John McCall16df1e52010-03-30 21:47:33 +000012484 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012485
John McCall2d74de92009-12-01 22:10:20 +000012486 // If overload resolution picked a static member, build a
12487 // non-member call based on that function.
12488 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012489 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12490 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012491 }
12492
John McCall10eae182009-11-30 22:42:35 +000012493 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012494 }
12495
Alp Toker314cc812014-01-25 16:55:45 +000012496 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012497 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12498 ResultType = ResultType.getNonLValueExprType(Context);
12499
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012500 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012501 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012502 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012503 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012504
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012505 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012506 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012507 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012508 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012509
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012510 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012511 // We only need to do this if there was actually an overload; otherwise
12512 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012513 if (!Method->isStatic()) {
12514 ExprResult ObjectArg =
12515 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12516 FoundDecl, Method);
12517 if (ObjectArg.isInvalid())
12518 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012519 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012520 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012521
12522 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012523 const FunctionProtoType *Proto =
12524 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012525 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012526 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012527 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012528
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012529 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012530
Richard Smith55ce3522012-06-25 20:30:08 +000012531 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012532 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012533
George Burgess IVaea6ade2015-09-25 17:53:16 +000012534 // In the case the method to call was not selected by the overloading
12535 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012536 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012537 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012538 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012539 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012540 diag::err_ovl_no_viable_member_function_in_call)
12541 << Method << Method->getSourceRange();
12542 Diag(Method->getLocation(),
12543 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12544 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12545 return ExprError();
12546 }
12547 }
12548
Anders Carlsson47061ee2011-05-06 14:25:31 +000012549 if ((isa<CXXConstructorDecl>(CurContext) ||
12550 isa<CXXDestructorDecl>(CurContext)) &&
12551 TheCall->getMethodDecl()->isPure()) {
12552 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12553
Davide Italianoccb37382015-07-14 23:36:10 +000012554 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12555 MemExpr->performsVirtualDispatch(getLangOpts())) {
12556 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012557 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12558 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12559 << MD->getParent()->getDeclName();
12560
12561 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012562 if (getLangOpts().AppleKext)
12563 Diag(MemExpr->getLocStart(),
12564 diag::note_pure_qualified_call_kext)
12565 << MD->getParent()->getDeclName()
12566 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012567 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012568 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012569
12570 if (CXXDestructorDecl *DD =
12571 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12572 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012573 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012574 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12575 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12576 MemExpr->getMemberLoc());
12577 }
12578
John McCallb268a282010-08-23 23:25:46 +000012579 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012580}
12581
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012582/// BuildCallToObjectOfClassType - Build a call to an object of class
12583/// type (C++ [over.call.object]), which can end up invoking an
12584/// overloaded function call operator (@c operator()) or performing a
12585/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012586ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012587Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012588 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012589 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012590 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012591 if (checkPlaceholderForOverload(*this, Obj))
12592 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012593 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012594
12595 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012596 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012597 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012598
Nico Weberb58e51c2014-11-19 05:21:39 +000012599 assert(Object.get()->getType()->isRecordType() &&
12600 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012601 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012602
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012603 // C++ [over.call.object]p1:
12604 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012605 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012606 // candidate functions includes at least the function call
12607 // operators of T. The function call operators of T are obtained by
12608 // ordinary lookup of the name operator() in the context of
12609 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012610 OverloadCandidateSet CandidateSet(LParenLoc,
12611 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012612 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012613
John Wiegley01296292011-04-08 18:41:53 +000012614 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012615 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012616 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012617
John McCall27b18f82009-11-17 02:14:36 +000012618 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12619 LookupQualifiedName(R, Record->getDecl());
12620 R.suppressDiagnostics();
12621
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012622 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012623 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012624 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012625 Object.get()->Classify(Context),
12626 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012627 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012629
Douglas Gregorab7897a2008-11-19 22:57:39 +000012630 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012631 // In addition, for each (non-explicit in C++0x) conversion function
12632 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012633 //
12634 // operator conversion-type-id () cv-qualifier;
12635 //
12636 // where cv-qualifier is the same cv-qualification as, or a
12637 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012638 // denotes the type "pointer to function of (P1,...,Pn) returning
12639 // R", or the type "reference to pointer to function of
12640 // (P1,...,Pn) returning R", or the type "reference to function
12641 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012642 // is also considered as a candidate function. Similarly,
12643 // surrogate call functions are added to the set of candidate
12644 // functions for each conversion function declared in an
12645 // accessible base class provided the function is not hidden
12646 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012647 const auto &Conversions =
12648 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12649 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012650 NamedDecl *D = *I;
12651 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12652 if (isa<UsingShadowDecl>(D))
12653 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012654
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012655 // Skip over templated conversion functions; they aren't
12656 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012657 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012658 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012659
John McCall6e9f8f62009-12-03 04:06:58 +000012660 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012661 if (!Conv->isExplicit()) {
12662 // Strip the reference type (if any) and then the pointer type (if
12663 // any) to get down to what might be a function type.
12664 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12665 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12666 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012667
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012668 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12669 {
12670 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012671 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012672 }
12673 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012674 }
Mike Stump11289f42009-09-09 15:08:12 +000012675
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012676 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12677
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012678 // Perform overload resolution.
12679 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012680 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012681 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012682 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012683 // Overload resolution succeeded; we'll build the appropriate call
12684 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012685 break;
12686
12687 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012688 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012689 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012690 << Object.get()->getType() << /*call*/ 1
12691 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012692 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012693 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012694 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012695 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012696 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012697 break;
12698
12699 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012700 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012701 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012702 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012703 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012704 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012705
12706 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012707 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012708 diag::err_ovl_deleted_object_call)
12709 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012710 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012711 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012712 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012713 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012714 break;
Mike Stump11289f42009-09-09 15:08:12 +000012715 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012716
Douglas Gregorb412e172010-07-25 18:17:45 +000012717 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012718 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012719
John McCall4124c492011-10-17 18:40:02 +000012720 UnbridgedCasts.restore();
12721
Craig Topperc3ec1492014-05-26 06:22:03 +000012722 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012723 // Since there is no function declaration, this is one of the
12724 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012725 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012726 = cast<CXXConversionDecl>(
12727 Best->Conversions[0].UserDefined.ConversionFunction);
12728
Craig Topperc3ec1492014-05-26 06:22:03 +000012729 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12730 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012731 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12732 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012733 assert(Conv == Best->FoundDecl.getDecl() &&
12734 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012735 // We selected one of the surrogate functions that converts the
12736 // object parameter to a function pointer. Perform the conversion
12737 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012738
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012739 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012740 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012741 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12742 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012743 if (Call.isInvalid())
12744 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012745 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012746 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12747 CK_UserDefinedConversion, Call.get(),
12748 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012749
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012750 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012751 }
12752
Craig Topperc3ec1492014-05-26 06:22:03 +000012753 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012754
Douglas Gregorab7897a2008-11-19 22:57:39 +000012755 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12756 // that calls this method, using Object for the implicit object
12757 // parameter and passing along the remaining arguments.
12758 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012759
12760 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012761 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012762 return ExprError();
12763
Chandler Carruth8e543b32010-12-12 08:17:55 +000012764 const FunctionProtoType *Proto =
12765 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012766
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012767 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012768
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012769 DeclarationNameInfo OpLocInfo(
12770 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12771 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012772 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012773 HadMultipleCandidates,
12774 OpLocInfo.getLoc(),
12775 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012776 if (NewFn.isInvalid())
12777 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012778
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012779 // Build the full argument list for the method call (the implicit object
12780 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000012781 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012782 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000012783 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012784
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012785 // Once we've built TheCall, all of the expressions are properly
12786 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012787 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012788 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12789 ResultTy = ResultTy.getNonLValueExprType(Context);
12790
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012791 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000012792 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12793 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012794
Alp Toker314cc812014-01-25 16:55:45 +000012795 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012796 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012797
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012798 // We may have default arguments. If so, we need to allocate more
12799 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012800 if (Args.size() < NumParams)
12801 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012802
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012803 bool IsError = false;
12804
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012805 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012806 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012807 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012808 Best->FoundDecl, Method);
12809 if (ObjRes.isInvalid())
12810 IsError = true;
12811 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012812 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012813 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012814
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012815 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012816 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012817 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012818 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012819 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012820
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012821 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012822
John McCalldadc5752010-08-24 06:29:42 +000012823 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012824 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012825 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012826 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012827 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012828
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012829 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012830 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012831 } else {
John McCalldadc5752010-08-24 06:29:42 +000012832 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012833 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12834 if (DefArg.isInvalid()) {
12835 IsError = true;
12836 break;
12837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012838
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012839 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012840 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012841
12842 TheCall->setArg(i + 1, Arg);
12843 }
12844
12845 // If this is a variadic call, handle args passed through "...".
12846 if (Proto->isVariadic()) {
12847 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012848 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012849 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12850 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012851 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012852 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012853 }
12854 }
12855
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012856 if (IsError) return true;
12857
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012858 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012859
Richard Smith55ce3522012-06-25 20:30:08 +000012860 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012861 return true;
12862
John McCalle172be52010-08-24 06:09:16 +000012863 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012864}
12865
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012866/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012867/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012868/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012869ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012870Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12871 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012872 assert(Base->getType()->isRecordType() &&
12873 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012874
John McCall4124c492011-10-17 18:40:02 +000012875 if (checkPlaceholderForOverload(*this, Base))
12876 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012877
John McCallbc077cf2010-02-08 23:07:23 +000012878 SourceLocation Loc = Base->getExprLoc();
12879
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012880 // C++ [over.ref]p1:
12881 //
12882 // [...] An expression x->m is interpreted as (x.operator->())->m
12883 // for a class object x of type T if T::operator->() exists and if
12884 // the operator is selected as the best match function by the
12885 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012886 DeclarationName OpName =
12887 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012888 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012889 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012890
John McCallbc077cf2010-02-08 23:07:23 +000012891 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012892 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012893 return ExprError();
12894
John McCall27b18f82009-11-17 02:14:36 +000012895 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12896 LookupQualifiedName(R, BaseRecord->getDecl());
12897 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012898
12899 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012900 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012901 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012902 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012903 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012904
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012905 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12906
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012907 // Perform overload resolution.
12908 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012909 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012910 case OR_Success:
12911 // Overload resolution succeeded; we'll build the call below.
12912 break;
12913
12914 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012915 if (CandidateSet.empty()) {
12916 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012917 if (NoArrowOperatorFound) {
12918 // Report this specific error to the caller instead of emitting a
12919 // diagnostic, as requested.
12920 *NoArrowOperatorFound = true;
12921 return ExprError();
12922 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012923 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12924 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012925 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012926 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012927 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012928 }
12929 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012930 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012931 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012933 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012934
12935 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012936 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12937 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012938 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012939 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012940
12941 case OR_Deleted:
12942 Diag(OpLoc, diag::err_ovl_deleted_oper)
12943 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012944 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012945 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012946 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012947 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012948 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012949 }
12950
Craig Topperc3ec1492014-05-26 06:22:03 +000012951 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012952
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012953 // Convert the object parameter.
12954 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012955 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012956 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012957 Best->FoundDecl, Method);
12958 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012959 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012960 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012961
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012962 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012963 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012964 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012965 if (FnExpr.isInvalid())
12966 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012967
Alp Toker314cc812014-01-25 16:55:45 +000012968 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012969 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12970 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012971 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012972 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012973 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012974
Alp Toker314cc812014-01-25 16:55:45 +000012975 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012976 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012977
12978 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012979}
12980
Richard Smithbcc22fc2012-03-09 08:00:36 +000012981/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12982/// a literal operator described by the provided lookup results.
12983ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12984 DeclarationNameInfo &SuffixInfo,
12985 ArrayRef<Expr*> Args,
12986 SourceLocation LitEndLoc,
12987 TemplateArgumentListInfo *TemplateArgs) {
12988 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012989
Richard Smith100b24a2014-04-17 01:52:14 +000012990 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12991 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012992 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12993 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012994
Richard Smithbcc22fc2012-03-09 08:00:36 +000012995 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12996
Richard Smithbcc22fc2012-03-09 08:00:36 +000012997 // Perform overload resolution. This will usually be trivial, but might need
12998 // to perform substitutions for a literal operator template.
12999 OverloadCandidateSet::iterator Best;
13000 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13001 case OR_Success:
13002 case OR_Deleted:
13003 break;
13004
13005 case OR_No_Viable_Function:
13006 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13007 << R.getLookupName();
13008 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13009 return ExprError();
13010
13011 case OR_Ambiguous:
13012 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13013 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13014 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013015 }
13016
Richard Smithbcc22fc2012-03-09 08:00:36 +000013017 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013018 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13019 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013020 SuffixInfo.getLoc(),
13021 SuffixInfo.getInfo());
13022 if (Fn.isInvalid())
13023 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013024
13025 // Check the argument types. This should almost always be a no-op, except
13026 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013027 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013028 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013029 ExprResult InputInit = PerformCopyInitialization(
13030 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13031 SourceLocation(), Args[ArgIdx]);
13032 if (InputInit.isInvalid())
13033 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013034 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013035 }
13036
Alp Toker314cc812014-01-25 16:55:45 +000013037 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013038 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13039 ResultTy = ResultTy.getNonLValueExprType(Context);
13040
Richard Smithc67fdd42012-03-07 08:35:16 +000013041 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013042 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013043 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013044 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13045
Alp Toker314cc812014-01-25 16:55:45 +000013046 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013047 return ExprError();
13048
Craig Topperc3ec1492014-05-26 06:22:03 +000013049 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013050 return ExprError();
13051
13052 return MaybeBindToTemporary(UDL);
13053}
13054
Sam Panzer0f384432012-08-21 00:52:01 +000013055/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13056/// given LookupResult is non-empty, it is assumed to describe a member which
13057/// will be invoked. Otherwise, the function will be found via argument
13058/// dependent lookup.
13059/// CallExpr is set to a valid expression and FRS_Success returned on success,
13060/// otherwise CallExpr is set to ExprError() and some non-success value
13061/// is returned.
13062Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013063Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13064 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013065 const DeclarationNameInfo &NameInfo,
13066 LookupResult &MemberLookup,
13067 OverloadCandidateSet *CandidateSet,
13068 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013069 Scope *S = nullptr;
13070
Sam Panzer0f384432012-08-21 00:52:01 +000013071 CandidateSet->clear();
13072 if (!MemberLookup.empty()) {
13073 ExprResult MemberRef =
13074 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13075 /*IsPtr=*/false, CXXScopeSpec(),
13076 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013077 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013078 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013079 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013080 if (MemberRef.isInvalid()) {
13081 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013082 return FRS_DiagnosticIssued;
13083 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013084 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013085 if (CallExpr->isInvalid()) {
13086 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013087 return FRS_DiagnosticIssued;
13088 }
13089 } else {
13090 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013091 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013092 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013093 NestedNameSpecifierLoc(), NameInfo,
13094 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013095 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013096
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013097 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013098 CandidateSet, CallExpr);
13099 if (CandidateSet->empty() || CandidateSetError) {
13100 *CallExpr = ExprError();
13101 return FRS_NoViableFunction;
13102 }
13103 OverloadCandidateSet::iterator Best;
13104 OverloadingResult OverloadResult =
13105 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13106
13107 if (OverloadResult == OR_No_Viable_Function) {
13108 *CallExpr = ExprError();
13109 return FRS_NoViableFunction;
13110 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013111 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013112 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013113 OverloadResult,
13114 /*AllowTypoCorrection=*/false);
13115 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13116 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013117 return FRS_DiagnosticIssued;
13118 }
13119 }
13120 return FRS_Success;
13121}
13122
13123
Douglas Gregorcd695e52008-11-10 20:40:00 +000013124/// FixOverloadedFunctionReference - E is an expression that refers to
13125/// a C++ overloaded function (possibly with some parentheses and
13126/// perhaps a '&' around it). We have resolved the overloaded function
13127/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013128/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013129Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013130 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013131 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013132 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13133 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013134 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013135 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013136
Douglas Gregor51c538b2009-11-20 19:42:02 +000013137 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013138 }
13139
Douglas Gregor51c538b2009-11-20 19:42:02 +000013140 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013141 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13142 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013143 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013144 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013145 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013146 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013147 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013148 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013149
13150 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013151 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013152 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013153 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013154 }
13155
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013156 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13157 if (!GSE->isResultDependent()) {
13158 Expr *SubExpr =
13159 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13160 if (SubExpr == GSE->getResultExpr())
13161 return GSE;
13162
13163 // Replace the resulting type information before rebuilding the generic
13164 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013165 ArrayRef<Expr *> A = GSE->getAssocExprs();
13166 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013167 unsigned ResultIdx = GSE->getResultIndex();
13168 AssocExprs[ResultIdx] = SubExpr;
13169
13170 return new (Context) GenericSelectionExpr(
13171 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13172 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13173 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13174 ResultIdx);
13175 }
13176 // Rather than fall through to the unreachable, return the original generic
13177 // selection expression.
13178 return GSE;
13179 }
13180
Douglas Gregor51c538b2009-11-20 19:42:02 +000013181 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013182 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013183 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13185 if (Method->isStatic()) {
13186 // Do nothing: static member functions aren't any different
13187 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013188 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013189 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013190 // UnresolvedLookupExpr holding an overloaded member function
13191 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013192 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13193 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013194 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013195 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013196
John McCalld14a8642009-11-21 08:51:07 +000013197 assert(isa<DeclRefExpr>(SubExpr)
13198 && "fixed to something other than a decl ref");
13199 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13200 && "fixed to a member ref with no nested name qualifier");
13201
13202 // We have taken the address of a pointer to member
13203 // function. Perform the computation here so that we get the
13204 // appropriate pointer to member type.
13205 QualType ClassType
13206 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13207 QualType MemPtrType
13208 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013209 // Under the MS ABI, lock down the inheritance model now.
13210 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13211 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013212
John McCall7decc9e2010-11-18 06:31:45 +000013213 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13214 VK_RValue, OK_Ordinary,
13215 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013216 }
13217 }
John McCall16df1e52010-03-30 21:47:33 +000013218 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13219 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013220 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013221 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013222
John McCalle3027922010-08-25 11:45:40 +000013223 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013224 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013225 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013226 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013227 }
John McCalld14a8642009-11-21 08:51:07 +000013228
Richard Smith84a0b6d2016-10-18 23:39:12 +000013229 // C++ [except.spec]p17:
13230 // An exception-specification is considered to be needed when:
13231 // - in an expression the function is the unique lookup result or the
13232 // selected member of a set of overloaded functions
13233 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13234 ResolveExceptionSpec(E->getExprLoc(), FPT);
13235
John McCalld14a8642009-11-21 08:51:07 +000013236 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013237 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013238 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013239 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013240 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13241 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013242 }
13243
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013244 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13245 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013246 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013247 Fn,
John McCall113bee02012-03-10 09:33:50 +000013248 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013249 ULE->getNameLoc(),
13250 Fn->getType(),
13251 VK_LValue,
13252 Found.getDecl(),
13253 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013254 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013255 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13256 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013257 }
13258
John McCall10eae182009-11-30 22:42:35 +000013259 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013260 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013261 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013262 if (MemExpr->hasExplicitTemplateArgs()) {
13263 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13264 TemplateArgs = &TemplateArgsBuffer;
13265 }
John McCall6b51f282009-11-23 01:53:49 +000013266
John McCall2d74de92009-12-01 22:10:20 +000013267 Expr *Base;
13268
John McCall7decc9e2010-11-18 06:31:45 +000013269 // If we're filling in a static method where we used to have an
13270 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013271 if (MemExpr->isImplicitAccess()) {
13272 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013273 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13274 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013275 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013276 Fn,
John McCall113bee02012-03-10 09:33:50 +000013277 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013278 MemExpr->getMemberLoc(),
13279 Fn->getType(),
13280 VK_LValue,
13281 Found.getDecl(),
13282 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013283 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013284 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13285 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013286 } else {
13287 SourceLocation Loc = MemExpr->getMemberLoc();
13288 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013289 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013290 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013291 Base = new (Context) CXXThisExpr(Loc,
13292 MemExpr->getBaseType(),
13293 /*isImplicit=*/true);
13294 }
John McCall2d74de92009-12-01 22:10:20 +000013295 } else
John McCallc3007a22010-10-26 07:05:15 +000013296 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013297
John McCall4adb38c2011-04-27 00:36:17 +000013298 ExprValueKind valueKind;
13299 QualType type;
13300 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13301 valueKind = VK_LValue;
13302 type = Fn->getType();
13303 } else {
13304 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013305 type = Context.BoundMemberTy;
13306 }
13307
13308 MemberExpr *ME = MemberExpr::Create(
13309 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13310 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13311 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13312 OK_Ordinary);
13313 ME->setHadMultipleCandidates(true);
13314 MarkMemberReferenced(ME);
13315 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013317
John McCallc3007a22010-10-26 07:05:15 +000013318 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013319}
13320
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013321ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013322 DeclAccessPair Found,
13323 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013324 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013325}