blob: ef38aceb15ee4f843970c36111a2b348a9815f4b [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) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
Nick Lewycky134af912013-02-07 05:08:22 +000046/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000047static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000048CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000050 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000052 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000053 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000061 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000062 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000066
67 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000068 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000070}
71
John McCall5c32be02010-08-24 20:38:10 +000072static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000074 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000075 bool CStyle,
76 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000077
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000078static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000083static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000087 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000089
90
91static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000092CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000093 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000102CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000108ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 };
140 return Rank[(int)Kind];
141}
142
143/// GetImplicitConversionName - Return the name of this kind of
144/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000145static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000151 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000155 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Integral conversion",
157 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000162 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000163 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000167 "Complex-real conversion",
168 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000169 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000184 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000185 ReferenceBinding = false;
186 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000191 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000192 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000193}
194
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195/// getRank - Retrieve the rank of this standard conversion sequence
196/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197/// implicit conversions.
198ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207}
208
209/// isPointerConversionToBool - Determines whether this conversion is
210/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000211/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000213bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000218 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000222 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227}
228
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229/// isPointerConversionToVoidPointer - Determines whether this
230/// conversion is a conversion of a pointer to a void pointer. This is
231/// used as part of the ranking of standard conversion sequences (C++
232/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000233bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000235isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000236 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000237 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250}
251
Richard Smith66e05fe2012-01-18 05:21:49 +0000252/// Skip any implicit casts which could be either part of a narrowing conversion
253/// or after one in an implicit conversion.
254static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000261 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274}
275
276/// Check if this standard conversion sequence represents a narrowing
277/// conversion, according to C++11 [dcl.init.list]p7.
278///
279/// \param Ctx The AST context.
280/// \param Converted The result of applying this standard conversion sequence.
281/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000283/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000285NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000286StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000288 APValue &ConstantValue,
289 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
296 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000297 // 'bool' is an integral type; dispatch to the right place to handle it.
298 case ICK_Boolean_Conversion:
299 if (FromType->isRealFloatingType())
300 goto FloatingIntegralConversion;
301 if (FromType->isIntegralOrUnscopedEnumerationType())
302 goto IntegralConversion;
303 // Boolean conversions can be from pointers and pointers to members
304 // [conv.bool], and those aren't considered narrowing conversions.
305 return NK_Not_Narrowing;
306
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000314 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000315 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
316 return NK_Type_Narrowing;
317 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
318 llvm::APSInt IntConstantValue;
319 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
320 if (Initializer &&
321 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
322 // Convert the integer to the floating type.
323 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
324 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
325 llvm::APFloat::rmNearestTiesToEven);
326 // And back.
327 llvm::APSInt ConvertedValue = IntConstantValue;
328 bool ignored;
329 Result.convertToInteger(ConvertedValue,
330 llvm::APFloat::rmTowardZero, &ignored);
331 // If the resulting value is different, this was a narrowing conversion.
332 if (IntConstantValue != ConvertedValue) {
333 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000334 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000335 return NK_Constant_Narrowing;
336 }
337 } else {
338 // Variables are always narrowings.
339 return NK_Variable_Narrowing;
340 }
341 }
342 return NK_Not_Narrowing;
343
344 // -- from long double to double or float, or from double to float, except
345 // where the source is a constant expression and the actual value after
346 // conversion is within the range of values that can be represented (even
347 // if it cannot be represented exactly), or
348 case ICK_Floating_Conversion:
349 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
350 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
351 // FromType is larger than ToType.
352 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
353 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
354 // Constant!
355 assert(ConstantValue.isFloat());
356 llvm::APFloat FloatVal = ConstantValue.getFloat();
357 // Convert the source value into the target type.
358 bool ignored;
359 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
360 Ctx.getFloatTypeSemantics(ToType),
361 llvm::APFloat::rmNearestTiesToEven, &ignored);
362 // If there was no overflow, the source value is within the range of
363 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000364 if (ConvertStatus & llvm::APFloat::opOverflow) {
365 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000367 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000368 } else {
369 return NK_Variable_Narrowing;
370 }
371 }
372 return NK_Not_Narrowing;
373
374 // -- from an integer type or unscoped enumeration type to an integer type
375 // that cannot represent all the values of the original type, except where
376 // the source is a constant expression and the actual value after
377 // conversion will fit into the target type and will produce the original
378 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000379 case ICK_Integral_Conversion:
380 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000381 assert(FromType->isIntegralOrUnscopedEnumerationType());
382 assert(ToType->isIntegralOrUnscopedEnumerationType());
383 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
384 const unsigned FromWidth = Ctx.getIntWidth(FromType);
385 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
386 const unsigned ToWidth = Ctx.getIntWidth(ToType);
387
388 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000389 (FromWidth == ToWidth && FromSigned != ToSigned) ||
390 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Not all values of FromType can be represented in ToType.
392 llvm::APSInt InitializerValue;
393 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000394 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
395 // Such conversions on variables are always narrowing.
396 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000397 }
398 bool Narrowing = false;
399 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000400 // Negative -> unsigned is narrowing. Otherwise, more bits is never
401 // narrowing.
402 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000403 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000404 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000405 // Add a bit to the InitializerValue so we don't have to worry about
406 // signed vs. unsigned comparisons.
407 InitializerValue = InitializerValue.extend(
408 InitializerValue.getBitWidth() + 1);
409 // Convert the initializer to and from the target width and signed-ness.
410 llvm::APSInt ConvertedValue = InitializerValue;
411 ConvertedValue = ConvertedValue.trunc(ToWidth);
412 ConvertedValue.setIsSigned(ToSigned);
413 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
414 ConvertedValue.setIsSigned(InitializerValue.isSigned());
415 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 if (ConvertedValue != InitializerValue)
417 Narrowing = true;
418 }
419 if (Narrowing) {
420 ConstantType = Initializer->getType();
421 ConstantValue = APValue(InitializerValue);
422 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000423 }
424 }
425 return NK_Not_Narrowing;
426 }
427
428 default:
429 // Other kinds of conversions are not narrowings.
430 return NK_Not_Narrowing;
431 }
432}
433
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000434/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000435/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000436LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438 bool PrintedSomething = false;
439 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 PrintedSomething = true;
442 }
443
444 if (Second != ICK_Identity) {
445 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449
450 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (Third != ICK_Identity) {
461 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 }
471}
472
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000475void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000478 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000481 if (ConversionFunction)
482 OS << '\'' << *ConversionFunction << '\'';
483 else
484 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000487 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 }
489}
490
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000491/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000493void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000495 if (isStdInitializerListElement())
496 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 switch (ConversionKind) {
498 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 break;
502 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000504 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 break;
506 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 break;
John McCall0d1da222010-01-12 00:44:57 +0000509 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000510 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000511 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 break;
515 }
516
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518}
519
John McCall0d1da222010-01-12 00:44:57 +0000520void AmbiguousConversionSequence::construct() {
521 new (&conversions()) ConversionSet();
522}
523
524void AmbiguousConversionSequence::destruct() {
525 conversions().~ConversionSet();
526}
527
528void
529AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
530 FromTypePtr = O.FromTypePtr;
531 ToTypePtr = O.ToTypePtr;
532 new (&conversions()) ConversionSet(O.conversions());
533}
534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000536 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 // template argument information.
538 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000539 TemplateArgument FirstArg;
540 TemplateArgument SecondArg;
541 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000542 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000543 // template parameter and template argument information.
544 struct DFIParamWithArguments : DFIArguments {
545 TemplateParameter Param;
546 };
Richard Smith9b534542015-12-31 02:02:54 +0000547 // Structure used by DeductionFailureInfo to store template argument
548 // information and the index of the problematic call argument.
549 struct DFIDeducedMismatchArgs : DFIArguments {
550 TemplateArgumentList *TemplateArgs;
551 unsigned CallArgIndex;
552 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000557DeductionFailureInfo
558clang::MakeDeductionFailureInfo(ASTContext &Context,
559 Sema::TemplateDeductionResult TDK,
560 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000563 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 switch (TDK) {
565 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000566 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000568 case Sema::TDK_TooManyArguments:
569 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000570 case Sema::TDK_MiscellaneousDeductionFailure:
571 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000575 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = Info.Param.getOpaqueValue();
577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Richard Smith9b534542015-12-31 02:02:54 +0000579 case Sema::TDK_DeducedMismatch: {
580 // FIXME: Should allocate from normal heap so that we can free this later.
581 auto *Saved = new (Context) DFIDeducedMismatchArgs;
582 Saved->FirstArg = Info.FirstArg;
583 Saved->SecondArg = Info.SecondArg;
584 Saved->TemplateArgs = Info.take();
585 Saved->CallArgIndex = Info.CallArgIndex;
586 Result.Data = Saved;
587 break;
588 }
589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000625 return Result;
626}
John McCall0d1da222010-01-12 00:44:57 +0000627
Larisse Voufo98b20f12013-07-19 23:00:19 +0000628void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000642 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000643 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000644 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000647
648 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000649 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000650 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
652 Diag->~PartialDiagnosticAt();
653 HasDiagnostic = false;
654 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000658 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 break;
660 }
661}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Larisse Voufo98b20f12013-07-19 23:00:19 +0000663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000666 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000667}
668
Larisse Voufo98b20f12013-07-19 23:00:19 +0000669TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
671 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000672 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000674 case Sema::TDK_TooManyArguments:
675 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000676 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000677 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Larisse Voufo98b20f12013-07-19 23:00:19 +0000698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
705 case Sema::TDK_Incomplete:
706 case Sema::TDK_InvalidExplicitArguments:
707 case Sema::TDK_Inconsistent:
708 case Sema::TDK_Underqualified:
709 case Sema::TDK_NonDeducedMismatch:
710 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000712
Richard Smith9b534542015-12-31 02:02:54 +0000713 case Sema::TDK_DeducedMismatch:
714 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
715
Richard Smith44ecdbd2013-01-31 05:19:49 +0000716 case Sema::TDK_SubstitutionFailure:
717 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718
Richard Smith44ecdbd2013-01-31 05:19:49 +0000719 // Unhandled
720 case Sema::TDK_MiscellaneousDeductionFailure:
721 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000722 }
723
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000725}
726
Larisse Voufo98b20f12013-07-19 23:00:19 +0000727const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
729 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000730 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_InstantiationDepth:
732 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000733 case Sema::TDK_TooManyArguments:
734 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000735 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000736 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000737 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000738 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000741 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000742 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000743 case Sema::TDK_NonDeducedMismatch:
744 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745
Douglas Gregor461761d2010-05-08 18:20:53 +0000746 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 break;
749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750
Craig Topperc3ec1492014-05-26 06:22:03 +0000751 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000753
Larisse Voufo98b20f12013-07-19 23:00:19 +0000754const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
756 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000757 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000758 case Sema::TDK_InstantiationDepth:
759 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000760 case Sema::TDK_TooManyArguments:
761 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000762 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000763 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000764 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000765 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000768 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000769 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_NonDeducedMismatch:
771 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772
Douglas Gregor461761d2010-05-08 18:20:53 +0000773 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000774 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 break;
776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Craig Topperc3ec1492014-05-26 06:22:03 +0000778 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779}
780
Larisse Voufo98b20f12013-07-19 23:00:19 +0000781Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000782 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
783 Sema::TDK_FailedOverloadResolution)
784 return static_cast<Expr*>(Data);
785
Craig Topperc3ec1492014-05-26 06:22:03 +0000786 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000787}
788
Richard Smith9b534542015-12-31 02:02:54 +0000789llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
790 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
791 Sema::TDK_DeducedMismatch)
792 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
793
794 return llvm::None;
795}
796
Benjamin Kramer97e59492012-10-09 15:52:25 +0000797void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000798 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000799 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
800 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000801 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
802 i->DeductionFailure.Destroy();
803 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000804}
805
806void OverloadCandidateSet::clear() {
807 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000808 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000809 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000810 Functions.clear();
811}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
John McCall4124c492011-10-17 18:40:02 +0000813namespace {
814 class UnbridgedCastsSet {
815 struct Entry {
816 Expr **Addr;
817 Expr *Saved;
818 };
819 SmallVector<Entry, 2> Entries;
820
821 public:
822 void save(Sema &S, Expr *&E) {
823 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
824 Entry entry = { &E, E };
825 Entries.push_back(entry);
826 E = S.stripARCUnbridgedCast(E);
827 }
828
829 void restore() {
830 for (SmallVectorImpl<Entry>::iterator
831 i = Entries.begin(), e = Entries.end(); i != e; ++i)
832 *i->Addr = i->Saved;
833 }
834 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000835}
John McCall4124c492011-10-17 18:40:02 +0000836
837/// checkPlaceholderForOverload - Do any interesting placeholder-like
838/// preprocessing on the given expression.
839///
840/// \param unbridgedCasts a collection to which to add unbridged casts;
841/// without this, they will be immediately diagnosed as errors
842///
843/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000844static bool
845checkPlaceholderForOverload(Sema &S, Expr *&E,
846 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000847 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
848 // We can't handle overloaded expressions here because overload
849 // resolution might reasonably tweak them.
850 if (placeholder->getKind() == BuiltinType::Overload) return false;
851
852 // If the context potentially accepts unbridged ARC casts, strip
853 // the unbridged cast and add it to the collection for later restoration.
854 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
855 unbridgedCasts) {
856 unbridgedCasts->save(S, E);
857 return false;
858 }
859
860 // Go ahead and check everything else.
861 ExprResult result = S.CheckPlaceholderExpr(E);
862 if (result.isInvalid())
863 return true;
864
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000865 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000866 return false;
867 }
868
869 // Nothing to do.
870 return false;
871}
872
873/// checkArgPlaceholdersForOverload - Check a set of call operands for
874/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000875static bool checkArgPlaceholdersForOverload(Sema &S,
876 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000877 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000878 for (unsigned i = 0, e = Args.size(); i != e; ++i)
879 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000880 return true;
881
882 return false;
883}
884
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000886// overload of the declarations in Old. This routine returns false if
887// New and Old cannot be overloaded, e.g., if New has the same
888// signature as some function in Old (C++ 1.3.10) or if the Old
889// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000890// it does return false, MatchedDecl will point to the decl that New
891// cannot be overloaded with. This decl may be a UsingShadowDecl on
892// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000893//
894// Example: Given the following input:
895//
896// void f(int, float); // #1
897// void f(int, int); // #2
898// int f(int, int); // #3
899//
900// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000901// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000902//
John McCall3d988d92009-12-02 08:47:38 +0000903// When we process #2, Old contains only the FunctionDecl for #1. By
904// comparing the parameter types, we see that #1 and #2 are overloaded
905// (since they have different signatures), so this routine returns
906// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000907//
John McCall3d988d92009-12-02 08:47:38 +0000908// When we process #3, Old is an overload set containing #1 and #2. We
909// compare the signatures of #3 to #1 (they're overloaded, so we do
910// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
911// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912// signature), IsOverload returns false and MatchedDecl will be set to
913// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000914//
915// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
916// into a class by a using declaration. The rules for whether to hide
917// shadow declarations ignore some properties which otherwise figure
918// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000919Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000920Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
921 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000922 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000923 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000924 NamedDecl *OldD = *I;
925
926 bool OldIsUsingDecl = false;
927 if (isa<UsingShadowDecl>(OldD)) {
928 OldIsUsingDecl = true;
929
930 // We can always introduce two using declarations into the same
931 // context, even if they have identical signatures.
932 if (NewIsUsingDecl) continue;
933
934 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
935 }
936
Richard Smithf091e122015-09-15 01:28:55 +0000937 // A using-declaration does not conflict with another declaration
938 // if one of them is hidden.
939 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
940 continue;
941
John McCalle9cccd82010-06-16 08:42:20 +0000942 // If either declaration was introduced by a using declaration,
943 // we'll need to use slightly different rules for matching.
944 // Essentially, these rules are the normal rules, except that
945 // function templates hide function templates with different
946 // return types or template parameter lists.
947 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000948 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
949 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000950
Alp Tokera2794f92014-01-22 07:29:52 +0000951 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000952 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
953 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
954 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
955 continue;
956 }
957
Alp Tokera2794f92014-01-22 07:29:52 +0000958 if (!isa<FunctionTemplateDecl>(OldD) &&
959 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000960 continue;
961
John McCalldaa3d6b2009-12-09 03:35:25 +0000962 Match = *I;
963 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000964 }
John McCalla8987a2942010-11-10 03:01:53 +0000965 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000966 // We can overload with these, which can show up when doing
967 // redeclaration checks for UsingDecls.
968 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000969 } else if (isa<TagDecl>(OldD)) {
970 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000971 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
972 // Optimistically assume that an unresolved using decl will
973 // overload; if it doesn't, we'll have to diagnose during
974 // template instantiation.
975 } else {
John McCall1f82f242009-11-18 22:49:29 +0000976 // (C++ 13p1):
977 // Only function declarations can be overloaded; object and type
978 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000979 Match = *I;
980 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000981 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000982 }
John McCall1f82f242009-11-18 22:49:29 +0000983
John McCalldaa3d6b2009-12-09 03:35:25 +0000984 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000985}
986
Richard Smithac974a32013-06-30 09:48:50 +0000987bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
988 bool UseUsingDeclRules) {
989 // C++ [basic.start.main]p2: This function shall not be overloaded.
990 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000991 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000992
David Majnemerc729b0b2013-09-16 22:44:20 +0000993 // MSVCRT user defined entry points cannot be overloaded.
994 if (New->isMSVCRTEntryPoint())
995 return false;
996
John McCall1f82f242009-11-18 22:49:29 +0000997 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
998 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
999
1000 // C++ [temp.fct]p2:
1001 // A function template can be overloaded with other function templates
1002 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001003 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001004 return true;
1005
1006 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001007 QualType OldQType = Context.getCanonicalType(Old->getType());
1008 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001009
1010 // Compare the signatures (C++ 1.3.10) of the two functions to
1011 // determine whether they are overloads. If we find any mismatch
1012 // in the signature, they are overloads.
1013
1014 // If either of these functions is a K&R-style function (no
1015 // prototype), then we consider them to have matching signatures.
1016 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1017 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1018 return false;
1019
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001020 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1021 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001022
1023 // The signature of a function includes the types of its
1024 // parameters (C++ 1.3.10), which includes the presence or absence
1025 // of the ellipsis; see C++ DR 357).
1026 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001027 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001028 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001029 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001030 return true;
1031
1032 // C++ [temp.over.link]p4:
1033 // The signature of a function template consists of its function
1034 // signature, its return type and its template parameter list. The names
1035 // of the template parameters are significant only for establishing the
1036 // relationship between the template parameters and the rest of the
1037 // signature.
1038 //
1039 // We check the return type and template parameter lists for function
1040 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001041 //
1042 // However, we don't consider either of these when deciding whether
1043 // a member introduced by a shadow declaration is hidden.
1044 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001045 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1046 OldTemplate->getTemplateParameters(),
1047 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001048 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001049 return true;
1050
1051 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001052 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001053 //
1054 // As part of this, also check whether one of the member functions
1055 // is static, in which case they are not overloads (C++
1056 // 13.1p2). While not part of the definition of the signature,
1057 // this check is important to determine whether these functions
1058 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001059 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1060 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001061 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001062 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1063 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1064 if (!UseUsingDeclRules &&
1065 (OldMethod->getRefQualifier() == RQ_None ||
1066 NewMethod->getRefQualifier() == RQ_None)) {
1067 // C++0x [over.load]p2:
1068 // - Member function declarations with the same name and the same
1069 // parameter-type-list as well as member function template
1070 // declarations with the same name, the same parameter-type-list, and
1071 // the same template parameter lists cannot be overloaded if any of
1072 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001073 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001074 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001075 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001076 }
1077 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Richard Smith574f4f62013-01-14 05:37:29 +00001080 // We may not have applied the implicit const for a constexpr member
1081 // function yet (because we haven't yet resolved whether this is a static
1082 // or non-static member function). Add it now, on the assumption that this
1083 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001084 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001085 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001086 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001087 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001088 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001089
1090 // We do not allow overloading based off of '__restrict'.
1091 OldQuals &= ~Qualifiers::Restrict;
1092 NewQuals &= ~Qualifiers::Restrict;
1093 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001094 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001097 // Though pass_object_size is placed on parameters and takes an argument, we
1098 // consider it to be a function-level modifier for the sake of function
1099 // identity. Either the function has one or more parameters with
1100 // pass_object_size or it doesn't.
1101 if (functionHasPassObjectSizeParams(New) !=
1102 functionHasPassObjectSizeParams(Old))
1103 return true;
1104
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001105 // enable_if attributes are an order-sensitive part of the signature.
1106 for (specific_attr_iterator<EnableIfAttr>
1107 NewI = New->specific_attr_begin<EnableIfAttr>(),
1108 NewE = New->specific_attr_end<EnableIfAttr>(),
1109 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1110 OldE = Old->specific_attr_end<EnableIfAttr>();
1111 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1112 if (NewI == NewE || OldI == OldE)
1113 return true;
1114 llvm::FoldingSetNodeID NewID, OldID;
1115 NewI->getCond()->Profile(NewID, Context, true);
1116 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001117 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001118 return true;
1119 }
1120
Artem Belevich94a55e82015-09-22 17:22:59 +00001121 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1122 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1123 OldTarget = IdentifyCUDATarget(Old);
1124 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1125 return false;
1126
1127 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1128
1129 // Don't allow mixing of HD with other kinds. This guarantees that
1130 // we have only one viable function with this signature on any
1131 // side of CUDA compilation .
Artem Belevich1ef9b592016-02-24 21:54:45 +00001132 // __global__ functions can't be overloaded based on attribute
1133 // difference because, like HD, they also exist on both sides.
1134 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1135 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001136 return false;
1137
1138 // Allow overloading of functions with same signature, but
1139 // different CUDA target attributes.
1140 return NewTarget != OldTarget;
1141 }
1142
John McCall1f82f242009-11-18 22:49:29 +00001143 // The signatures match; this is not an overload.
1144 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145}
1146
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001147/// \brief Checks availability of the function depending on the current
1148/// function context. Inside an unavailable function, unavailability is ignored.
1149///
1150/// \returns true if \arg FD is unavailable and current context is inside
1151/// an available function, false otherwise.
1152bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1153 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1154}
1155
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001156/// \brief Tries a user-defined conversion from From to ToType.
1157///
1158/// Produces an implicit conversion sequence for when a standard conversion
1159/// is not an option. See TryImplicitConversion for more information.
1160static ImplicitConversionSequence
1161TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1162 bool SuppressUserConversions,
1163 bool AllowExplicit,
1164 bool InOverloadResolution,
1165 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001166 bool AllowObjCWritebackConversion,
1167 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001168 ImplicitConversionSequence ICS;
1169
1170 if (SuppressUserConversions) {
1171 // We're not in the case above, so there is no conversion that
1172 // we can perform.
1173 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1174 return ICS;
1175 }
1176
1177 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001178 OverloadCandidateSet Conversions(From->getExprLoc(),
1179 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001180 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1181 Conversions, AllowExplicit,
1182 AllowObjCConversionOnExplicit)) {
1183 case OR_Success:
1184 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001185 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001186 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001187 // C++ [over.ics.user]p4:
1188 // A conversion of an expression of class type to the same class
1189 // type is given Exact Match rank, and a conversion of an
1190 // expression of class type to a base class of that type is
1191 // given Conversion rank, in spite of the fact that a copy
1192 // constructor (i.e., a user-defined conversion function) is
1193 // called for those cases.
1194 if (CXXConstructorDecl *Constructor
1195 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1196 QualType FromCanon
1197 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1198 QualType ToCanon
1199 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1200 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001201 (FromCanon == ToCanon ||
1202 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001203 // Turn this into a "standard" conversion sequence, so that it
1204 // gets ranked with standard conversion sequences.
1205 ICS.setStandard();
1206 ICS.Standard.setAsIdentityConversion();
1207 ICS.Standard.setFromType(From->getType());
1208 ICS.Standard.setAllToTypes(ToType);
1209 ICS.Standard.CopyConstructor = Constructor;
1210 if (ToCanon != FromCanon)
1211 ICS.Standard.Second = ICK_Derived_To_Base;
1212 }
1213 }
Richard Smith48372b62015-01-27 03:30:40 +00001214 break;
1215
1216 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001217 ICS.setAmbiguous();
1218 ICS.Ambiguous.setFromType(From->getType());
1219 ICS.Ambiguous.setToType(ToType);
1220 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1221 Cand != Conversions.end(); ++Cand)
1222 if (Cand->Viable)
1223 ICS.Ambiguous.addConversion(Cand->Function);
1224 break;
Richard Smith48372b62015-01-27 03:30:40 +00001225
1226 // Fall through.
1227 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001229 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001230 }
1231
1232 return ICS;
1233}
1234
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001235/// TryImplicitConversion - Attempt to perform an implicit conversion
1236/// from the given expression (Expr) to the given type (ToType). This
1237/// function returns an implicit conversion sequence that can be used
1238/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239///
1240/// void f(float f);
1241/// void g(int i) { f(i); }
1242///
1243/// this routine would produce an implicit conversion sequence to
1244/// describe the initialization of f from i, which will be a standard
1245/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1246/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1247//
1248/// Note that this routine only determines how the conversion can be
1249/// performed; it does not actually perform the conversion. As such,
1250/// it will not produce any diagnostics if no conversion is available,
1251/// but will instead return an implicit conversion sequence of kind
1252/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001253///
1254/// If @p SuppressUserConversions, then user-defined conversions are
1255/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001256/// If @p AllowExplicit, then explicit user-defined conversions are
1257/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001258///
1259/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1260/// writeback conversion, which allows __autoreleasing id* parameters to
1261/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001262static ImplicitConversionSequence
1263TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1264 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001266 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001267 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001268 bool AllowObjCWritebackConversion,
1269 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001270 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001271 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001272 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001273 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001274 return ICS;
1275 }
1276
David Blaikiebbafb8a2012-03-11 07:00:24 +00001277 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001278 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001279 return ICS;
1280 }
1281
Douglas Gregor836a7e82010-08-11 02:15:33 +00001282 // C++ [over.ics.user]p4:
1283 // A conversion of an expression of class type to the same class
1284 // type is given Exact Match rank, and a conversion of an
1285 // expression of class type to a base class of that type is
1286 // given Conversion rank, in spite of the fact that a copy/move
1287 // constructor (i.e., a user-defined conversion function) is
1288 // called for those cases.
1289 QualType FromType = From->getType();
1290 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001291 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001292 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001293 ICS.setStandard();
1294 ICS.Standard.setAsIdentityConversion();
1295 ICS.Standard.setFromType(FromType);
1296 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297
Douglas Gregor5ab11652010-04-17 22:01:05 +00001298 // We don't actually check at this point whether there is a valid
1299 // copy/move constructor, since overloading just assumes that it
1300 // exists. When we actually perform initialization, we'll find the
1301 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001302 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
Douglas Gregor5ab11652010-04-17 22:01:05 +00001304 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001305 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001306 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001307
Douglas Gregor836a7e82010-08-11 02:15:33 +00001308 return ICS;
1309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001311 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1312 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001313 AllowObjCWritebackConversion,
1314 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001315}
1316
John McCall31168b02011-06-15 23:02:42 +00001317ImplicitConversionSequence
1318Sema::TryImplicitConversion(Expr *From, QualType ToType,
1319 bool SuppressUserConversions,
1320 bool AllowExplicit,
1321 bool InOverloadResolution,
1322 bool CStyle,
1323 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001324 return ::TryImplicitConversion(*this, From, ToType,
1325 SuppressUserConversions, AllowExplicit,
1326 InOverloadResolution, CStyle,
1327 AllowObjCWritebackConversion,
1328 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001329}
1330
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001331/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001332/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001333/// converted expression. Flavor is the kind of conversion we're
1334/// performing, used in the error message. If @p AllowExplicit,
1335/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001336ExprResult
1337Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001338 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001339 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001340 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001341}
1342
John Wiegley01296292011-04-08 18:41:53 +00001343ExprResult
1344Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001345 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001346 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001347 if (checkPlaceholderForOverload(*this, From))
1348 return ExprError();
1349
John McCall31168b02011-06-15 23:02:42 +00001350 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1351 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001352 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001353 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001354 if (getLangOpts().ObjC1)
1355 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1356 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001357 ICS = ::TryImplicitConversion(*this, From, ToType,
1358 /*SuppressUserConversions=*/false,
1359 AllowExplicit,
1360 /*InOverloadResolution=*/false,
1361 /*CStyle=*/false,
1362 AllowObjCWritebackConversion,
1363 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001364 return PerformImplicitConversion(From, ToType, ICS, Action);
1365}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
1367/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001368/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001369bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1370 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001371 if (Context.hasSameUnqualifiedType(FromType, ToType))
1372 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
John McCall991eb4b2010-12-21 00:44:39 +00001374 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1375 // where F adds one of the following at most once:
1376 // - a pointer
1377 // - a member pointer
1378 // - a block pointer
1379 CanQualType CanTo = Context.getCanonicalType(ToType);
1380 CanQualType CanFrom = Context.getCanonicalType(FromType);
1381 Type::TypeClass TyClass = CanTo->getTypeClass();
1382 if (TyClass != CanFrom->getTypeClass()) return false;
1383 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1384 if (TyClass == Type::Pointer) {
1385 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1386 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1387 } else if (TyClass == Type::BlockPointer) {
1388 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1389 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1390 } else if (TyClass == Type::MemberPointer) {
1391 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1392 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1393 } else {
1394 return false;
1395 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001396
John McCall991eb4b2010-12-21 00:44:39 +00001397 TyClass = CanTo->getTypeClass();
1398 if (TyClass != CanFrom->getTypeClass()) return false;
1399 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1400 return false;
1401 }
1402
1403 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1404 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1405 if (!EInfo.getNoReturn()) return false;
1406
1407 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1408 assert(QualType(FromFn, 0).isCanonical());
1409 if (QualType(FromFn, 0) != CanTo) return false;
1410
1411 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001412 return true;
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
Douglas Gregor46188682010-05-18 22:42:18 +00001415/// \brief Determine whether the conversion from FromType to ToType is a valid
1416/// vector conversion.
1417///
1418/// \param ICK Will be set to the vector conversion kind, if this is a vector
1419/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001420static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001422 // We need at least one of these types to be a vector type to have a vector
1423 // conversion.
1424 if (!ToType->isVectorType() && !FromType->isVectorType())
1425 return false;
1426
1427 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001428 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001429 return false;
1430
1431 // There are no conversions between extended vector types, only identity.
1432 if (ToType->isExtVectorType()) {
1433 // There are no conversions between extended vector types other than the
1434 // identity conversion.
1435 if (FromType->isExtVectorType())
1436 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001437
Douglas Gregor46188682010-05-18 22:42:18 +00001438 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001439 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001440 ICK = ICK_Vector_Splat;
1441 return true;
1442 }
1443 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001444
1445 // We can perform the conversion between vector types in the following cases:
1446 // 1)vector types are equivalent AltiVec and GCC vector types
1447 // 2)lax vector conversions are permitted and the vector types are of the
1448 // same size
1449 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001450 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1451 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001452 ICK = ICK_Vector_Conversion;
1453 return true;
1454 }
Douglas Gregor46188682010-05-18 22:42:18 +00001455 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001456
Douglas Gregor46188682010-05-18 22:42:18 +00001457 return false;
1458}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001460static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1461 bool InOverloadResolution,
1462 StandardConversionSequence &SCS,
1463 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001464
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001465/// IsStandardConversion - Determines whether there is a standard
1466/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1467/// expression From to the type ToType. Standard conversion sequences
1468/// only consider non-class types; for conversions that involve class
1469/// types, use TryImplicitConversion. If a conversion exists, SCS will
1470/// contain the standard conversion sequence required to perform this
1471/// conversion and this routine will return true. Otherwise, this
1472/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001473static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1474 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001475 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001476 bool CStyle,
1477 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001478 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001480 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001481 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001482 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001483 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001484 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001486 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001487 // abort early. When overloading in C, however, we do permit them.
1488 if (S.getLangOpts().CPlusPlus &&
1489 (FromType->isRecordType() || ToType->isRecordType()))
1490 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001491
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492 // The first conversion can be an lvalue-to-rvalue conversion,
1493 // array-to-pointer conversion, or function-to-pointer conversion
1494 // (C++ 4p1).
1495
John McCall5c32be02010-08-24 20:38:10 +00001496 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001497 DeclAccessPair AccessPair;
1498 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001500 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001501 // We were able to resolve the address of the overloaded function,
1502 // so we can convert to the type of that function.
1503 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001504 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001505
1506 // we can sometimes resolve &foo<int> regardless of ToType, so check
1507 // if the type matches (identity) or we are converting to bool
1508 if (!S.Context.hasSameUnqualifiedType(
1509 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1510 QualType resultTy;
1511 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001512 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001513 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1514 // otherwise, only a boolean conversion is standard
1515 if (!ToType->isBooleanType())
1516 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Chandler Carruthffce2452011-03-29 08:08:18 +00001519 // Check if the "from" expression is taking the address of an overloaded
1520 // function and recompute the FromType accordingly. Take advantage of the
1521 // fact that non-static member functions *must* have such an address-of
1522 // expression.
1523 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1524 if (Method && !Method->isStatic()) {
1525 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1526 "Non-unary operator on non-static member address");
1527 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1528 == UO_AddrOf &&
1529 "Non-address-of operator on non-static member address");
1530 const Type *ClassType
1531 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1532 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001533 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1534 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1535 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001536 "Non-address-of operator for overloaded function expression");
1537 FromType = S.Context.getPointerType(FromType);
1538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539
Douglas Gregor980fb162010-04-29 18:24:40 +00001540 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001541 assert(S.Context.hasSameType(
1542 FromType,
1543 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001544 } else {
1545 return false;
1546 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001547 }
John McCall154a2fd2011-08-30 00:57:29 +00001548 // Lvalue-to-rvalue conversion (C++11 4.1):
1549 // A glvalue (3.10) of a non-function, non-array type T can
1550 // be converted to a prvalue.
1551 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001552 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001553 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001554 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556
Douglas Gregorc79862f2012-04-12 17:51:55 +00001557 // C11 6.3.2.1p2:
1558 // ... if the lvalue has atomic type, the value has the non-atomic version
1559 // of the type of the lvalue ...
1560 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1561 FromType = Atomic->getValueType();
1562
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001563 // If T is a non-class type, the type of the rvalue is the
1564 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001565 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1566 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001568 } else if (FromType->isArrayType()) {
1569 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571
1572 // An lvalue or rvalue of type "array of N T" or "array of unknown
1573 // bound of T" can be converted to an rvalue of type "pointer to
1574 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001575 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576
John McCall5c32be02010-08-24 20:38:10 +00001577 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001578 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001579 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580
1581 // For the purpose of ranking in overload resolution
1582 // (13.3.3.1.1), this conversion is considered an
1583 // array-to-pointer conversion followed by a qualification
1584 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001585 SCS.Second = ICK_Identity;
1586 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001587 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001588 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 }
John McCall086a4642010-11-24 05:12:34 +00001591 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001592 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001595 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1596 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1597 if (!S.checkAddressOfFunctionIsAvailable(FD))
1598 return false;
1599
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600 // An lvalue of function type T can be converted to an rvalue of
1601 // type "pointer to T." The result is a pointer to the
1602 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001603 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001604 } else {
1605 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001606 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001607 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001608 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609
1610 // The second conversion can be an integral promotion, floating
1611 // point promotion, integral conversion, floating point conversion,
1612 // floating-integral conversion, pointer conversion,
1613 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001614 // For overloading in C, this can also be a "compatible-type"
1615 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001616 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001617 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001618 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 // The unqualified versions of the types are the same: there's no
1620 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001622 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001623 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001626 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001630 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001631 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001632 SCS.Second = ICK_Complex_Promotion;
1633 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001634 } else if (ToType->isBooleanType() &&
1635 (FromType->isArithmeticType() ||
1636 FromType->isAnyPointerType() ||
1637 FromType->isBlockPointerType() ||
1638 FromType->isMemberPointerType() ||
1639 FromType->isNullPtrType())) {
1640 // Boolean conversions (C++ 4.12).
1641 SCS.Second = ICK_Boolean_Conversion;
1642 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001643 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001644 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001645 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001646 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001648 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001649 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001650 SCS.Second = ICK_Complex_Conversion;
1651 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001652 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1653 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001654 // Complex-real conversions (C99 6.3.1.7)
1655 SCS.Second = ICK_Complex_Real;
1656 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001657 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001658 // Floating point conversions (C++ 4.8).
1659 SCS.Second = ICK_Floating_Conversion;
1660 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001662 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001663 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001664 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001665 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001668 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001669 SCS.Second = ICK_Block_Pointer_Conversion;
1670 } else if (AllowObjCWritebackConversion &&
1671 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1672 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001673 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1674 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001675 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001677 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001678 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001680 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001681 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001682 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001683 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001684 SCS.Second = SecondICK;
1685 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001686 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001687 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001688 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001689 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001690 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001691 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001692 // Treat a conversion that strips "noreturn" as an identity conversion.
1693 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001694 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1695 InOverloadResolution,
1696 SCS, CStyle)) {
1697 SCS.Second = ICK_TransparentUnionConversion;
1698 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001699 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1700 CStyle)) {
1701 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001702 // appropriately.
1703 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001704 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001705 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001706 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001707 SCS.Second = ICK_Zero_Event_Conversion;
1708 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 } else {
1710 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001713 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001715 QualType CanonFrom;
1716 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001718 bool ObjCLifetimeConversion;
1719 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1720 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001721 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001722 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001724 CanonFrom = S.Context.getCanonicalType(FromType);
1725 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 } else {
1727 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001728 SCS.Third = ICK_Identity;
1729
Mike Stump11289f42009-09-09 15:08:12 +00001730 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001731 // [...] Any difference in top-level cv-qualification is
1732 // subsumed by the initialization itself and does not constitute
1733 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001734 CanonFrom = S.Context.getCanonicalType(FromType);
1735 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001737 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001738 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001739 FromType = ToType;
1740 CanonFrom = CanonTo;
1741 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001743 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744
George Burgess IV45461812015-10-11 20:13:20 +00001745 if (CanonFrom == CanonTo)
1746 return true;
1747
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001749 // this is a bad conversion sequence, unless we're resolving an overload in C.
1750 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001751 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001752
George Burgess IV45461812015-10-11 20:13:20 +00001753 ExprResult ER = ExprResult{From};
1754 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1755 /*Diagnose=*/false,
1756 /*DiagnoseCFAudited=*/false,
1757 /*ConvertRHS=*/false);
1758 if (Conv != Sema::Compatible)
1759 return false;
1760
1761 SCS.setAllToTypes(ToType);
1762 // We need to set all three because we want this conversion to rank terribly,
1763 // and we don't know what conversions it may overlap with.
1764 SCS.First = ICK_C_Only_Conversion;
1765 SCS.Second = ICK_C_Only_Conversion;
1766 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001767 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001769
1770static bool
1771IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1772 QualType &ToType,
1773 bool InOverloadResolution,
1774 StandardConversionSequence &SCS,
1775 bool CStyle) {
1776
1777 const RecordType *UT = ToType->getAsUnionType();
1778 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1779 return false;
1780 // The field to initialize within the transparent union.
1781 RecordDecl *UD = UT->getDecl();
1782 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001783 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001784 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1785 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001786 ToType = it->getType();
1787 return true;
1788 }
1789 }
1790 return false;
1791}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001792
1793/// IsIntegralPromotion - Determines whether the conversion from the
1794/// expression From (whose potentially-adjusted type is FromType) to
1795/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1796/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001797bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001798 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001799 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001800 if (!To) {
1801 return false;
1802 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803
1804 // An rvalue of type char, signed char, unsigned char, short int, or
1805 // unsigned short int can be converted to an rvalue of type int if
1806 // int can represent all the values of the source type; otherwise,
1807 // the source rvalue can be converted to an rvalue of type unsigned
1808 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001809 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1810 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 if (// We can promote any signed, promotable integer type to an int
1812 (FromType->isSignedIntegerType() ||
1813 // We can promote any unsigned integer type whose size is
1814 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001815 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001816 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001818 }
1819
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 return To->getKind() == BuiltinType::UInt;
1821 }
1822
Richard Smithb9c5a602012-09-13 21:18:54 +00001823 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824 // A prvalue of an unscoped enumeration type whose underlying type is not
1825 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1826 // following types that can represent all the values of the enumeration
1827 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1828 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001829 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001831 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832 // with lowest integer conversion rank (4.13) greater than the rank of long
1833 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001834 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001835 // C++11 [conv.prom]p4:
1836 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1837 // can be converted to a prvalue of its underlying type. Moreover, if
1838 // integral promotion can be applied to its underlying type, a prvalue of an
1839 // unscoped enumeration type whose underlying type is fixed can also be
1840 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001841 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1842 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1843 // provided for a scoped enumeration.
1844 if (FromEnumType->getDecl()->isScoped())
1845 return false;
1846
Richard Smithb9c5a602012-09-13 21:18:54 +00001847 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001848 // even if that's not the promoted type. Note that the check for promoting
1849 // the underlying type is based on the type alone, and does not consider
1850 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001851 if (FromEnumType->getDecl()->isFixed()) {
1852 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1853 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001854 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001855 }
1856
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001857 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001859 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001860 return Context.hasSameUnqualifiedType(
1861 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001862 }
John McCall56774992009-12-09 09:09:27 +00001863
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001864 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1866 // to an rvalue a prvalue of the first of the following types that can
1867 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001868 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001870 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001871 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001872 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001874 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001875 // Determine whether the type we're converting from is signed or
1876 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001877 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001878 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001880 // The types we'll try to promote to, in the appropriate
1881 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001882 QualType PromoteTypes[6] = {
1883 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001884 Context.LongTy, Context.UnsignedLongTy ,
1885 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001886 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001887 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1889 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001890 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001891 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1892 // We found the type that we can promote to. If this is the
1893 // type we wanted, we have a promotion. Otherwise, no
1894 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001895 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 }
1897 }
1898 }
1899
1900 // An rvalue for an integral bit-field (9.6) can be converted to an
1901 // rvalue of type int if int can represent all the values of the
1902 // bit-field; otherwise, it can be converted to unsigned int if
1903 // unsigned int can represent all the values of the bit-field. If
1904 // the bit-field is larger yet, no integral promotion applies to
1905 // it. If the bit-field has an enumerated type, it is treated as any
1906 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001907 // FIXME: We should delay checking of bit-fields until we actually perform the
1908 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001909 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001910 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001911 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001912 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001913 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001914 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001915 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001917 // Are we promoting to an int from a bitfield that fits in an int?
1918 if (BitWidth < ToSize ||
1919 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1920 return To->getKind() == BuiltinType::Int;
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001923 // Are we promoting to an unsigned int from an unsigned bitfield
1924 // that fits into an unsigned int?
1925 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1926 return To->getKind() == BuiltinType::UInt;
1927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001929 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001930 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001932 }
Mike Stump11289f42009-09-09 15:08:12 +00001933
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 // An rvalue of type bool can be converted to an rvalue of type int,
1935 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001936 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001937 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001939
1940 return false;
1941}
1942
1943/// IsFloatingPointPromotion - Determines whether the conversion from
1944/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1945/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001946bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001947 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1948 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001949 /// An rvalue of type float can be converted to an rvalue of type
1950 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001951 if (FromBuiltin->getKind() == BuiltinType::Float &&
1952 ToBuiltin->getKind() == BuiltinType::Double)
1953 return true;
1954
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001955 // C99 6.3.1.5p1:
1956 // When a float is promoted to double or long double, or a
1957 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001958 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001959 (FromBuiltin->getKind() == BuiltinType::Float ||
1960 FromBuiltin->getKind() == BuiltinType::Double) &&
1961 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1962 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001963
1964 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001965 if (!getLangOpts().NativeHalfType &&
1966 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001967 ToBuiltin->getKind() == BuiltinType::Float)
1968 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001969 }
1970
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001971 return false;
1972}
1973
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001974/// \brief Determine if a conversion is a complex promotion.
1975///
1976/// A complex promotion is defined as a complex -> complex conversion
1977/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001978/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001979bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001980 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001981 if (!FromComplex)
1982 return false;
1983
John McCall9dd450b2009-09-21 23:43:11 +00001984 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001985 if (!ToComplex)
1986 return false;
1987
1988 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001989 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001990 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001991 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001992}
1993
Douglas Gregor237f96c2008-11-26 23:31:11 +00001994/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1995/// the pointer type FromPtr to a pointer to type ToPointee, with the
1996/// same type qualifiers as FromPtr has on its pointee type. ToType,
1997/// if non-empty, will be a pointer to ToType that may or may not have
1998/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001999///
Mike Stump11289f42009-09-09 15:08:12 +00002000static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002001BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002002 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002003 ASTContext &Context,
2004 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002005 assert((FromPtr->getTypeClass() == Type::Pointer ||
2006 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2007 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
John McCall31168b02011-06-15 23:02:42 +00002009 /// Conversions to 'id' subsume cv-qualifier conversions.
2010 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002011 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012
2013 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002014 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002015 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002016 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002017
John McCall31168b02011-06-15 23:02:42 +00002018 if (StripObjCLifetime)
2019 Quals.removeObjCLifetime();
2020
Mike Stump11289f42009-09-09 15:08:12 +00002021 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002022 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002023 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002024 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002025 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002026
2027 // Build a pointer to ToPointee. It has the right qualifiers
2028 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002029 if (isa<ObjCObjectPointerType>(ToType))
2030 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002031 return Context.getPointerType(ToPointee);
2032 }
2033
2034 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002035 QualType QualifiedCanonToPointee
2036 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002038 if (isa<ObjCObjectPointerType>(ToType))
2039 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2040 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002041}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Mike Stump11289f42009-09-09 15:08:12 +00002043static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002044 bool InOverloadResolution,
2045 ASTContext &Context) {
2046 // Handle value-dependent integral null pointer constants correctly.
2047 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2048 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002049 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002050 return !InOverloadResolution;
2051
Douglas Gregor56751b52009-09-25 04:25:58 +00002052 return Expr->isNullPointerConstant(Context,
2053 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2054 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002055}
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057/// IsPointerConversion - Determines whether the conversion of the
2058/// expression From, which has the (possibly adjusted) type FromType,
2059/// can be converted to the type ToType via a pointer conversion (C++
2060/// 4.10). If so, returns true and places the converted type (that
2061/// might differ from ToType in its cv-qualifiers at some level) into
2062/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002063///
Douglas Gregora29dc052008-11-27 01:19:21 +00002064/// This routine also supports conversions to and from block pointers
2065/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2066/// pointers to interfaces. FIXME: Once we've determined the
2067/// appropriate overloading rules for Objective-C, we may want to
2068/// split the Objective-C checks into a different routine; however,
2069/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002070/// conversions, so for now they live here. IncompatibleObjC will be
2071/// set if the conversion is an allowed Objective-C conversion that
2072/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002074 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002075 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002076 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002077 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002078 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2079 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002080 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002081
Mike Stump11289f42009-09-09 15:08:12 +00002082 // Conversion from a null pointer constant to any Objective-C pointer type.
2083 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002085 ConvertedType = ToType;
2086 return true;
2087 }
2088
Douglas Gregor231d1c62008-11-27 00:15:41 +00002089 // Blocks: Block pointers can be converted to void*.
2090 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002091 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002092 ConvertedType = ToType;
2093 return true;
2094 }
2095 // Blocks: A null pointer constant can be converted to a block
2096 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002097 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002098 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002099 ConvertedType = ToType;
2100 return true;
2101 }
2102
Sebastian Redl576fd422009-05-10 18:38:11 +00002103 // If the left-hand-side is nullptr_t, the right side can be a null
2104 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002105 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002106 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002107 ConvertedType = ToType;
2108 return true;
2109 }
2110
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002111 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002112 if (!ToTypePtr)
2113 return false;
2114
2115 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002116 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002117 ConvertedType = ToType;
2118 return true;
2119 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002120
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002122 // , including objective-c pointers.
2123 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002124 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002125 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002126 ConvertedType = BuildSimilarlyQualifiedPointerType(
2127 FromType->getAs<ObjCObjectPointerType>(),
2128 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002129 ToType, Context);
2130 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002131 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002132 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133 if (!FromTypePtr)
2134 return false;
2135
2136 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002139 // pointer conversion, so don't do all of the work below.
2140 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2141 return false;
2142
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002143 // An rvalue of type "pointer to cv T," where T is an object type,
2144 // can be converted to an rvalue of type "pointer to cv void" (C++
2145 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002146 if (FromPointeeType->isIncompleteOrObjectType() &&
2147 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002148 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002149 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002150 ToType, Context,
2151 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002152 return true;
2153 }
2154
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002155 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002156 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002157 ToPointeeType->isVoidType()) {
2158 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2159 ToPointeeType,
2160 ToType, Context);
2161 return true;
2162 }
2163
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002164 // When we're overloading in C, we allow a special kind of pointer
2165 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002166 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002167 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002169 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002170 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002171 return true;
2172 }
2173
Douglas Gregor5c407d92008-10-23 00:40:37 +00002174 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002175 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002176 // An rvalue of type "pointer to cv D," where D is a class type,
2177 // can be converted to an rvalue of type "pointer to cv B," where
2178 // B is a base class (clause 10) of D. If B is an inaccessible
2179 // (clause 11) or ambiguous (10.2) base class of D, a program that
2180 // necessitates this conversion is ill-formed. The result of the
2181 // conversion is a pointer to the base class sub-object of the
2182 // derived class object. The null pointer value is converted to
2183 // the null pointer value of the destination type.
2184 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002185 // Note that we do not check for ambiguity or inaccessibility
2186 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002187 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002188 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002189 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002190 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002191 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002192 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002193 ToType, Context);
2194 return true;
2195 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002196
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002197 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2198 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2200 ToPointeeType,
2201 ToType, Context);
2202 return true;
2203 }
2204
Douglas Gregora119f102008-12-19 19:13:09 +00002205 return false;
2206}
Douglas Gregoraec25842011-04-26 23:16:46 +00002207
2208/// \brief Adopt the given qualifiers for the given type.
2209static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2210 Qualifiers TQs = T.getQualifiers();
2211
2212 // Check whether qualifiers already match.
2213 if (TQs == Qs)
2214 return T;
2215
2216 if (Qs.compatiblyIncludes(TQs))
2217 return Context.getQualifiedType(T, Qs);
2218
2219 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2220}
Douglas Gregora119f102008-12-19 19:13:09 +00002221
2222/// isObjCPointerConversion - Determines whether this is an
2223/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2224/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002225bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002226 QualType& ConvertedType,
2227 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002228 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002229 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002230
Douglas Gregoraec25842011-04-26 23:16:46 +00002231 // The set of qualifiers on the type we're converting from.
2232 Qualifiers FromQualifiers = FromType.getQualifiers();
2233
Steve Naroff7cae42b2009-07-10 23:34:53 +00002234 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002235 const ObjCObjectPointerType* ToObjCPtr =
2236 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002237 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002238 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002239
Steve Naroff7cae42b2009-07-10 23:34:53 +00002240 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002241 // If the pointee types are the same (ignoring qualifications),
2242 // then this is not a pointer conversion.
2243 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2244 FromObjCPtr->getPointeeType()))
2245 return false;
2246
Douglas Gregorab209d82015-07-07 03:58:42 +00002247 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002248 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002249 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2250 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002251 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002252 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2253 FromObjCPtr->getPointeeType()))
2254 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002255 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002256 ToObjCPtr->getPointeeType(),
2257 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002259 return true;
2260 }
2261
2262 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2263 // Okay: this is some kind of implicit downcast of Objective-C
2264 // interfaces, which is permitted. However, we're going to
2265 // complain about it.
2266 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002268 ToObjCPtr->getPointeeType(),
2269 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002271 return true;
2272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002274 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002275 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002276 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002277 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002278 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002279 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002280 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002281 // to a block pointer type.
2282 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002283 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002284 return true;
2285 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002286 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002289 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002291 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002292 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002293 return true;
2294 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002295 else
Douglas Gregora119f102008-12-19 19:13:09 +00002296 return false;
2297
Douglas Gregor033f56d2008-12-23 00:53:59 +00002298 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002299 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002300 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002301 else if (const BlockPointerType *FromBlockPtr =
2302 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002303 FromPointeeType = FromBlockPtr->getPointeeType();
2304 else
Douglas Gregora119f102008-12-19 19:13:09 +00002305 return false;
2306
Douglas Gregora119f102008-12-19 19:13:09 +00002307 // If we have pointers to pointers, recursively check whether this
2308 // is an Objective-C conversion.
2309 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2310 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2311 IncompatibleObjC)) {
2312 // We always complain about this conversion.
2313 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002314 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002315 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002316 return true;
2317 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002318 // Allow conversion of pointee being objective-c pointer to another one;
2319 // as in I* to id.
2320 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2321 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2322 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2323 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002324
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002325 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002326 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002327 return true;
2328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
Douglas Gregor033f56d2008-12-23 00:53:59 +00002330 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002331 // differences in the argument and result types are in Objective-C
2332 // pointer conversions. If so, we permit the conversion (but
2333 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002334 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002335 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002336 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002337 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002338 if (FromFunctionType && ToFunctionType) {
2339 // If the function types are exactly the same, this isn't an
2340 // Objective-C pointer conversion.
2341 if (Context.getCanonicalType(FromPointeeType)
2342 == Context.getCanonicalType(ToPointeeType))
2343 return false;
2344
2345 // Perform the quick checks that will tell us whether these
2346 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002347 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002348 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2349 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2350 return false;
2351
2352 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002353 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2354 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002355 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002356 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2357 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002358 ConvertedType, IncompatibleObjC)) {
2359 // Okay, we have an Objective-C pointer conversion.
2360 HasObjCConversion = true;
2361 } else {
2362 // Function types are too different. Abort.
2363 return false;
2364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregora119f102008-12-19 19:13:09 +00002366 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002367 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002368 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002369 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2370 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002371 if (Context.getCanonicalType(FromArgType)
2372 == Context.getCanonicalType(ToArgType)) {
2373 // Okay, the types match exactly. Nothing to do.
2374 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2375 ConvertedType, IncompatibleObjC)) {
2376 // Okay, we have an Objective-C pointer conversion.
2377 HasObjCConversion = true;
2378 } else {
2379 // Argument types are too different. Abort.
2380 return false;
2381 }
2382 }
2383
2384 if (HasObjCConversion) {
2385 // We had an Objective-C conversion. Allow this pointer
2386 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002387 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002388 IncompatibleObjC = true;
2389 return true;
2390 }
2391 }
2392
Sebastian Redl72b597d2009-01-25 19:43:20 +00002393 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002394}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002395
John McCall31168b02011-06-15 23:02:42 +00002396/// \brief Determine whether this is an Objective-C writeback conversion,
2397/// used for parameter passing when performing automatic reference counting.
2398///
2399/// \param FromType The type we're converting form.
2400///
2401/// \param ToType The type we're converting to.
2402///
2403/// \param ConvertedType The type that will be produced after applying
2404/// this conversion.
2405bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2406 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002407 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002408 Context.hasSameUnqualifiedType(FromType, ToType))
2409 return false;
2410
2411 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2412 QualType ToPointee;
2413 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2414 ToPointee = ToPointer->getPointeeType();
2415 else
2416 return false;
2417
2418 Qualifiers ToQuals = ToPointee.getQualifiers();
2419 if (!ToPointee->isObjCLifetimeType() ||
2420 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002421 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002422 return false;
2423
2424 // Argument must be a pointer to __strong to __weak.
2425 QualType FromPointee;
2426 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2427 FromPointee = FromPointer->getPointeeType();
2428 else
2429 return false;
2430
2431 Qualifiers FromQuals = FromPointee.getQualifiers();
2432 if (!FromPointee->isObjCLifetimeType() ||
2433 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2434 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2435 return false;
2436
2437 // Make sure that we have compatible qualifiers.
2438 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2439 if (!ToQuals.compatiblyIncludes(FromQuals))
2440 return false;
2441
2442 // Remove qualifiers from the pointee type we're converting from; they
2443 // aren't used in the compatibility check belong, and we'll be adding back
2444 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2445 FromPointee = FromPointee.getUnqualifiedType();
2446
2447 // The unqualified form of the pointee types must be compatible.
2448 ToPointee = ToPointee.getUnqualifiedType();
2449 bool IncompatibleObjC;
2450 if (Context.typesAreCompatible(FromPointee, ToPointee))
2451 FromPointee = ToPointee;
2452 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2453 IncompatibleObjC))
2454 return false;
2455
2456 /// \brief Construct the type we're converting to, which is a pointer to
2457 /// __autoreleasing pointee.
2458 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2459 ConvertedType = Context.getPointerType(FromPointee);
2460 return true;
2461}
2462
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002463bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2464 QualType& ConvertedType) {
2465 QualType ToPointeeType;
2466 if (const BlockPointerType *ToBlockPtr =
2467 ToType->getAs<BlockPointerType>())
2468 ToPointeeType = ToBlockPtr->getPointeeType();
2469 else
2470 return false;
2471
2472 QualType FromPointeeType;
2473 if (const BlockPointerType *FromBlockPtr =
2474 FromType->getAs<BlockPointerType>())
2475 FromPointeeType = FromBlockPtr->getPointeeType();
2476 else
2477 return false;
2478 // We have pointer to blocks, check whether the only
2479 // differences in the argument and result types are in Objective-C
2480 // pointer conversions. If so, we permit the conversion.
2481
2482 const FunctionProtoType *FromFunctionType
2483 = FromPointeeType->getAs<FunctionProtoType>();
2484 const FunctionProtoType *ToFunctionType
2485 = ToPointeeType->getAs<FunctionProtoType>();
2486
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002487 if (!FromFunctionType || !ToFunctionType)
2488 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002489
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002490 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002491 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002492
2493 // Perform the quick checks that will tell us whether these
2494 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002495 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002496 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2497 return false;
2498
2499 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2500 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2501 if (FromEInfo != ToEInfo)
2502 return false;
2503
2504 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002505 if (Context.hasSameType(FromFunctionType->getReturnType(),
2506 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002507 // Okay, the types match exactly. Nothing to do.
2508 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002509 QualType RHS = FromFunctionType->getReturnType();
2510 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002511 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002512 !RHS.hasQualifiers() && LHS.hasQualifiers())
2513 LHS = LHS.getUnqualifiedType();
2514
2515 if (Context.hasSameType(RHS,LHS)) {
2516 // OK exact match.
2517 } else if (isObjCPointerConversion(RHS, LHS,
2518 ConvertedType, IncompatibleObjC)) {
2519 if (IncompatibleObjC)
2520 return false;
2521 // Okay, we have an Objective-C pointer conversion.
2522 }
2523 else
2524 return false;
2525 }
2526
2527 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002528 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002529 ArgIdx != NumArgs; ++ArgIdx) {
2530 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002531 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2532 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002533 if (Context.hasSameType(FromArgType, ToArgType)) {
2534 // Okay, the types match exactly. Nothing to do.
2535 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2536 ConvertedType, IncompatibleObjC)) {
2537 if (IncompatibleObjC)
2538 return false;
2539 // Okay, we have an Objective-C pointer conversion.
2540 } else
2541 // Argument types are too different. Abort.
2542 return false;
2543 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002544 if (LangOpts.ObjCAutoRefCount &&
2545 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2546 ToFunctionType))
2547 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002548
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002549 ConvertedType = ToType;
2550 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002551}
2552
Richard Trieucaff2472011-11-23 22:32:32 +00002553enum {
2554 ft_default,
2555 ft_different_class,
2556 ft_parameter_arity,
2557 ft_parameter_mismatch,
2558 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002559 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002560};
2561
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002562/// Attempts to get the FunctionProtoType from a Type. Handles
2563/// MemberFunctionPointers properly.
2564static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2565 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2566 return FPT;
2567
2568 if (auto *MPT = FromType->getAs<MemberPointerType>())
2569 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2570
2571 return nullptr;
2572}
2573
Richard Trieucaff2472011-11-23 22:32:32 +00002574/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2575/// function types. Catches different number of parameter, mismatch in
2576/// parameter types, and different return types.
2577void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2578 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002579 // If either type is not valid, include no extra info.
2580 if (FromType.isNull() || ToType.isNull()) {
2581 PDiag << ft_default;
2582 return;
2583 }
2584
Richard Trieucaff2472011-11-23 22:32:32 +00002585 // Get the function type from the pointers.
2586 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2587 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2588 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002589 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002590 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2591 << QualType(FromMember->getClass(), 0);
2592 return;
2593 }
2594 FromType = FromMember->getPointeeType();
2595 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002596 }
2597
Richard Trieu96ed5b62011-12-13 23:19:45 +00002598 if (FromType->isPointerType())
2599 FromType = FromType->getPointeeType();
2600 if (ToType->isPointerType())
2601 ToType = ToType->getPointeeType();
2602
2603 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002604 FromType = FromType.getNonReferenceType();
2605 ToType = ToType.getNonReferenceType();
2606
Richard Trieucaff2472011-11-23 22:32:32 +00002607 // Don't print extra info for non-specialized template functions.
2608 if (FromType->isInstantiationDependentType() &&
2609 !FromType->getAs<TemplateSpecializationType>()) {
2610 PDiag << ft_default;
2611 return;
2612 }
2613
Richard Trieu96ed5b62011-12-13 23:19:45 +00002614 // No extra info for same types.
2615 if (Context.hasSameType(FromType, ToType)) {
2616 PDiag << ft_default;
2617 return;
2618 }
2619
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002620 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2621 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002622
2623 // Both types need to be function types.
2624 if (!FromFunction || !ToFunction) {
2625 PDiag << ft_default;
2626 return;
2627 }
2628
Alp Toker9cacbab2014-01-20 20:26:09 +00002629 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2630 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2631 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002632 return;
2633 }
2634
2635 // Handle different parameter types.
2636 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002637 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002638 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002639 << ToFunction->getParamType(ArgPos)
2640 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002641 return;
2642 }
2643
2644 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002645 if (!Context.hasSameType(FromFunction->getReturnType(),
2646 ToFunction->getReturnType())) {
2647 PDiag << ft_return_type << ToFunction->getReturnType()
2648 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002649 return;
2650 }
2651
2652 unsigned FromQuals = FromFunction->getTypeQuals(),
2653 ToQuals = ToFunction->getTypeQuals();
2654 if (FromQuals != ToQuals) {
2655 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2656 return;
2657 }
2658
2659 // Unable to find a difference, so add no extra info.
2660 PDiag << ft_default;
2661}
2662
Alp Toker9cacbab2014-01-20 20:26:09 +00002663/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002664/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002665/// they have same number of arguments. If the parameters are different,
2666/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002667bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2668 const FunctionProtoType *NewType,
2669 unsigned *ArgPos) {
2670 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2671 N = NewType->param_type_begin(),
2672 E = OldType->param_type_end();
2673 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002674 if (!Context.hasSameType(O->getUnqualifiedType(),
2675 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002676 if (ArgPos)
2677 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002678 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002679 }
2680 }
2681 return true;
2682}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002683
Douglas Gregor39c16d42008-10-24 04:54:22 +00002684/// CheckPointerConversion - Check the pointer conversion from the
2685/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002686/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002687/// conversions for which IsPointerConversion has already returned
2688/// true. It returns true and produces a diagnostic if there was an
2689/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002690bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002691 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002692 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002693 bool IgnoreBaseAccess,
2694 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002695 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002696 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002697
John McCall8cb679e2010-11-15 09:13:47 +00002698 Kind = CK_BitCast;
2699
George Burgess IV60bc9722016-01-13 23:36:34 +00002700 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002701 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002702 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002703 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2704 DiagRuntimeBehavior(From->getExprLoc(), From,
2705 PDiag(diag::warn_impcast_bool_to_null_pointer)
2706 << ToType << From->getSourceRange());
2707 else if (!isUnevaluatedContext())
2708 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2709 << ToType << From->getSourceRange();
2710 }
John McCall9320b872011-09-09 05:25:32 +00002711 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2712 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002713 QualType FromPointeeType = FromPtrType->getPointeeType(),
2714 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002715
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002716 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2717 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002718 // We must have a derived-to-base conversion. Check an
2719 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002720 unsigned InaccessibleID = 0;
2721 unsigned AmbigiousID = 0;
2722 if (Diagnose) {
2723 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2724 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2725 }
2726 if (CheckDerivedToBaseConversion(
2727 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2728 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2729 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002730 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002731
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002732 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002733 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002734 }
David Majnemer6bf02822015-10-31 08:42:14 +00002735
George Burgess IV60bc9722016-01-13 23:36:34 +00002736 if (Diagnose && !IsCStyleOrFunctionalCast &&
2737 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002738 assert(getLangOpts().MSVCCompat &&
2739 "this should only be possible with MSVCCompat!");
2740 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2741 << From->getSourceRange();
2742 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002743 }
John McCall9320b872011-09-09 05:25:32 +00002744 } else if (const ObjCObjectPointerType *ToPtrType =
2745 ToType->getAs<ObjCObjectPointerType>()) {
2746 if (const ObjCObjectPointerType *FromPtrType =
2747 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002748 // Objective-C++ conversions are always okay.
2749 // FIXME: We should have a different class of conversions for the
2750 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002751 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002752 return false;
John McCall9320b872011-09-09 05:25:32 +00002753 } else if (FromType->isBlockPointerType()) {
2754 Kind = CK_BlockPointerToObjCPointerCast;
2755 } else {
2756 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002757 }
John McCall9320b872011-09-09 05:25:32 +00002758 } else if (ToType->isBlockPointerType()) {
2759 if (!FromType->isBlockPointerType())
2760 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002761 }
John McCall8cb679e2010-11-15 09:13:47 +00002762
2763 // We shouldn't fall into this case unless it's valid for other
2764 // reasons.
2765 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2766 Kind = CK_NullToPointer;
2767
Douglas Gregor39c16d42008-10-24 04:54:22 +00002768 return false;
2769}
2770
Sebastian Redl72b597d2009-01-25 19:43:20 +00002771/// IsMemberPointerConversion - Determines whether the conversion of the
2772/// expression From, which has the (possibly adjusted) type FromType, can be
2773/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2774/// If so, returns true and places the converted type (that might differ from
2775/// ToType in its cv-qualifiers at some level) into ConvertedType.
2776bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002777 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002778 bool InOverloadResolution,
2779 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002780 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002781 if (!ToTypePtr)
2782 return false;
2783
2784 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002785 if (From->isNullPointerConstant(Context,
2786 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2787 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002788 ConvertedType = ToType;
2789 return true;
2790 }
2791
2792 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002793 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002794 if (!FromTypePtr)
2795 return false;
2796
2797 // A pointer to member of B can be converted to a pointer to member of D,
2798 // where D is derived from B (C++ 4.11p2).
2799 QualType FromClass(FromTypePtr->getClass(), 0);
2800 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002801
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002802 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002803 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002804 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2805 ToClass.getTypePtr());
2806 return true;
2807 }
2808
2809 return false;
2810}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811
Sebastian Redl72b597d2009-01-25 19:43:20 +00002812/// CheckMemberPointerConversion - Check the member pointer conversion from the
2813/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002814/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002815/// for which IsMemberPointerConversion has already returned true. It returns
2816/// true and produces a diagnostic if there was an error, or returns false
2817/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002818bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002819 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002820 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002821 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002822 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002823 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002824 if (!FromPtrType) {
2825 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002827 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002828 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002829 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002830 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002831 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002832
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002833 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002834 assert(ToPtrType && "No member pointer cast has a target type "
2835 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002836
Sebastian Redled8f2002009-01-28 18:33:18 +00002837 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2838 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002839
Sebastian Redled8f2002009-01-28 18:33:18 +00002840 // FIXME: What about dependent types?
2841 assert(FromClass->isRecordType() && "Pointer into non-class.");
2842 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002843
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002844 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002845 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002846 bool DerivationOkay =
2847 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002848 assert(DerivationOkay &&
2849 "Should not have been called if derivation isn't OK.");
2850 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002851
Sebastian Redled8f2002009-01-28 18:33:18 +00002852 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2853 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002854 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2855 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2856 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2857 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002858 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002859
Douglas Gregor89ee6822009-02-28 01:32:25 +00002860 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002861 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2862 << FromClass << ToClass << QualType(VBase, 0)
2863 << From->getSourceRange();
2864 return true;
2865 }
2866
John McCall5b0829a2010-02-10 09:31:12 +00002867 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002868 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2869 Paths.front(),
2870 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002871
Anders Carlssond7923c62009-08-22 23:33:40 +00002872 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002873 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002874 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002875 return false;
2876}
2877
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002878/// Determine whether the lifetime conversion between the two given
2879/// qualifiers sets is nontrivial.
2880static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2881 Qualifiers ToQuals) {
2882 // Converting anything to const __unsafe_unretained is trivial.
2883 if (ToQuals.hasConst() &&
2884 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2885 return false;
2886
2887 return true;
2888}
2889
Douglas Gregor9a657932008-10-21 23:43:52 +00002890/// IsQualificationConversion - Determines whether the conversion from
2891/// an rvalue of type FromType to ToType is a qualification conversion
2892/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002893///
2894/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2895/// when the qualification conversion involves a change in the Objective-C
2896/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002897bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002899 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002900 FromType = Context.getCanonicalType(FromType);
2901 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002902 ObjCLifetimeConversion = false;
2903
Douglas Gregor9a657932008-10-21 23:43:52 +00002904 // If FromType and ToType are the same type, this is not a
2905 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002906 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002907 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002908
Douglas Gregor9a657932008-10-21 23:43:52 +00002909 // (C++ 4.4p4):
2910 // A conversion can add cv-qualifiers at levels other than the first
2911 // in multi-level pointers, subject to the following rules: [...]
2912 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002913 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002914 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002915 // Within each iteration of the loop, we check the qualifiers to
2916 // determine if this still looks like a qualification
2917 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002918 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002919 // until there are no more pointers or pointers-to-members left to
2920 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002921 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002922
Douglas Gregor90609aa2011-04-25 18:40:17 +00002923 Qualifiers FromQuals = FromType.getQualifiers();
2924 Qualifiers ToQuals = ToType.getQualifiers();
2925
John McCall31168b02011-06-15 23:02:42 +00002926 // Objective-C ARC:
2927 // Check Objective-C lifetime conversions.
2928 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2929 UnwrappedAnyPointer) {
2930 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002931 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2932 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002933 FromQuals.removeObjCLifetime();
2934 ToQuals.removeObjCLifetime();
2935 } else {
2936 // Qualification conversions cannot cast between different
2937 // Objective-C lifetime qualifiers.
2938 return false;
2939 }
2940 }
2941
Douglas Gregorf30053d2011-05-08 06:09:53 +00002942 // Allow addition/removal of GC attributes but not changing GC attributes.
2943 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2944 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2945 FromQuals.removeObjCGCAttr();
2946 ToQuals.removeObjCGCAttr();
2947 }
2948
Douglas Gregor9a657932008-10-21 23:43:52 +00002949 // -- for every j > 0, if const is in cv 1,j then const is in cv
2950 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002951 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002952 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002953
Douglas Gregor9a657932008-10-21 23:43:52 +00002954 // -- if the cv 1,j and cv 2,j are different, then const is in
2955 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002956 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002957 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002958 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregor9a657932008-10-21 23:43:52 +00002960 // Keep track of whether all prior cv-qualifiers in the "to" type
2961 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002962 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002963 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002964 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002965
2966 // We are left with FromType and ToType being the pointee types
2967 // after unwrapping the original FromType and ToType the same number
2968 // of types. If we unwrapped any pointers, and if FromType and
2969 // ToType have the same unqualified type (since we checked
2970 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002971 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002972}
2973
Douglas Gregorc79862f2012-04-12 17:51:55 +00002974/// \brief - Determine whether this is a conversion from a scalar type to an
2975/// atomic type.
2976///
2977/// If successful, updates \c SCS's second and third steps in the conversion
2978/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002979static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2980 bool InOverloadResolution,
2981 StandardConversionSequence &SCS,
2982 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002983 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2984 if (!ToAtomic)
2985 return false;
2986
2987 StandardConversionSequence InnerSCS;
2988 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2989 InOverloadResolution, InnerSCS,
2990 CStyle, /*AllowObjCWritebackConversion=*/false))
2991 return false;
2992
2993 SCS.Second = InnerSCS.Second;
2994 SCS.setToType(1, InnerSCS.getToType(1));
2995 SCS.Third = InnerSCS.Third;
2996 SCS.QualificationIncludesObjCLifetime
2997 = InnerSCS.QualificationIncludesObjCLifetime;
2998 SCS.setToType(2, InnerSCS.getToType(2));
2999 return true;
3000}
3001
Sebastian Redle5417162012-03-27 18:33:03 +00003002static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3003 CXXConstructorDecl *Constructor,
3004 QualType Type) {
3005 const FunctionProtoType *CtorType =
3006 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003007 if (CtorType->getNumParams() > 0) {
3008 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003009 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3010 return true;
3011 }
3012 return false;
3013}
3014
Sebastian Redl82ace982012-02-11 23:51:08 +00003015static OverloadingResult
3016IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3017 CXXRecordDecl *To,
3018 UserDefinedConversionSequence &User,
3019 OverloadCandidateSet &CandidateSet,
3020 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003021 DeclContext::lookup_result R = S.LookupConstructors(To);
3022 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003023 Con != ConEnd; ++Con) {
3024 NamedDecl *D = *Con;
3025 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3026
3027 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003028 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003029 FunctionTemplateDecl *ConstructorTmpl
3030 = dyn_cast<FunctionTemplateDecl>(D);
3031 if (ConstructorTmpl)
3032 Constructor
3033 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3034 else
3035 Constructor = cast<CXXConstructorDecl>(D);
3036
3037 bool Usable = !Constructor->isInvalidDecl() &&
3038 S.isInitListConstructor(Constructor) &&
3039 (AllowExplicit || !Constructor->isExplicit());
3040 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003041 // If the first argument is (a reference to) the target type,
3042 // suppress conversions.
3043 bool SuppressUserConversions =
3044 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003045 if (ConstructorTmpl)
3046 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003047 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003048 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003049 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003050 else
3051 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003052 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003053 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003054 }
3055 }
3056
3057 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3058
3059 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003060 switch (auto Result =
3061 CandidateSet.BestViableFunction(S, From->getLocStart(),
3062 Best, true)) {
3063 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003064 case OR_Success: {
3065 // Record the standard conversion we used and the conversion function.
3066 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003067 QualType ThisType = Constructor->getThisType(S.Context);
3068 // Initializer lists don't have conversions as such.
3069 User.Before.setAsIdentityConversion();
3070 User.HadMultipleCandidates = HadMultipleCandidates;
3071 User.ConversionFunction = Constructor;
3072 User.FoundConversionFunction = Best->FoundDecl;
3073 User.After.setAsIdentityConversion();
3074 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3075 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003076 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003077 }
3078
3079 case OR_No_Viable_Function:
3080 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003081 case OR_Ambiguous:
3082 return OR_Ambiguous;
3083 }
3084
3085 llvm_unreachable("Invalid OverloadResult!");
3086}
3087
Douglas Gregor576e98c2009-01-30 23:27:23 +00003088/// Determines whether there is a user-defined conversion sequence
3089/// (C++ [over.ics.user]) that converts expression From to the type
3090/// ToType. If such a conversion exists, User will contain the
3091/// user-defined conversion sequence that performs such a conversion
3092/// and this routine will return true. Otherwise, this routine returns
3093/// false and User is unspecified.
3094///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003095/// \param AllowExplicit true if the conversion should consider C++0x
3096/// "explicit" conversion functions as well as non-explicit conversion
3097/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003098///
3099/// \param AllowObjCConversionOnExplicit true if the conversion should
3100/// allow an extra Objective-C pointer conversion on uses of explicit
3101/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003102static OverloadingResult
3103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003104 UserDefinedConversionSequence &User,
3105 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003106 bool AllowExplicit,
3107 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003108 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003109
Douglas Gregor5ab11652010-04-17 22:01:05 +00003110 // Whether we will only visit constructors.
3111 bool ConstructorsOnly = false;
3112
3113 // If the type we are conversion to is a class type, enumerate its
3114 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003115 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003116 // C++ [over.match.ctor]p1:
3117 // When objects of class type are direct-initialized (8.5), or
3118 // copy-initialized from an expression of the same or a
3119 // derived class type (8.5), overload resolution selects the
3120 // constructor. [...] For copy-initialization, the candidate
3121 // functions are all the converting constructors (12.3.1) of
3122 // that class. The argument list is the expression-list within
3123 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003124 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003125 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003126 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003127 ConstructorsOnly = true;
3128
Richard Smithdb0ac552015-12-18 22:40:25 +00003129 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003130 // We're not going to find any constructors.
3131 } else if (CXXRecordDecl *ToRecordDecl
3132 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003133
3134 Expr **Args = &From;
3135 unsigned NumArgs = 1;
3136 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003137 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003138 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003139 OverloadingResult Result = IsInitializerListConstructorConversion(
3140 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3141 if (Result != OR_No_Viable_Function)
3142 return Result;
3143 // Never mind.
3144 CandidateSet.clear();
3145
3146 // If we're list-initializing, we pass the individual elements as
3147 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003148 Args = InitList->getInits();
3149 NumArgs = InitList->getNumInits();
3150 ListInitializing = true;
3151 }
3152
David Blaikieff7d47a2012-12-19 00:45:41 +00003153 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3154 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003155 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003156 NamedDecl *D = *Con;
3157 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3158
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003159 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003160 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003161 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003162 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003163 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003164 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003165 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3166 else
John McCalla0296f72010-03-19 07:35:19 +00003167 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003169 bool Usable = !Constructor->isInvalidDecl();
3170 if (ListInitializing)
3171 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3172 else
3173 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3174 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003175 bool SuppressUserConversions = !ConstructorsOnly;
3176 if (SuppressUserConversions && ListInitializing) {
3177 SuppressUserConversions = false;
3178 if (NumArgs == 1) {
3179 // If the first argument is (a reference to) the target type,
3180 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003181 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3182 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003183 }
3184 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003185 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003186 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003187 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003188 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003189 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003190 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003191 // Allow one user-defined conversion when user specifies a
3192 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003193 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003194 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003195 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003196 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003197 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003198 }
3199 }
3200
Douglas Gregor5ab11652010-04-17 22:01:05 +00003201 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003202 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003203 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003204 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003205 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003206 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003207 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003208 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3209 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003210 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3211 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003212 DeclAccessPair FoundDecl = I.getPair();
3213 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003214 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3215 if (isa<UsingShadowDecl>(D))
3216 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3217
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003218 CXXConversionDecl *Conv;
3219 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003220 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3221 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003222 else
John McCallda4458e2010-03-31 01:36:47 +00003223 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003224
3225 if (AllowExplicit || !Conv->isExplicit()) {
3226 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003227 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3228 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003229 CandidateSet,
3230 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003231 else
John McCall5c32be02010-08-24 20:38:10 +00003232 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003233 From, ToType, CandidateSet,
3234 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003235 }
3236 }
3237 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003238 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003239
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003240 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3241
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003242 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003243 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3244 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003245 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003246 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003247 // Record the standard conversion we used and the conversion function.
3248 if (CXXConstructorDecl *Constructor
3249 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3250 // C++ [over.ics.user]p1:
3251 // If the user-defined conversion is specified by a
3252 // constructor (12.3.1), the initial standard conversion
3253 // sequence converts the source type to the type required by
3254 // the argument of the constructor.
3255 //
3256 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003257 if (isa<InitListExpr>(From)) {
3258 // Initializer lists don't have conversions as such.
3259 User.Before.setAsIdentityConversion();
3260 } else {
3261 if (Best->Conversions[0].isEllipsis())
3262 User.EllipsisConversion = true;
3263 else {
3264 User.Before = Best->Conversions[0].Standard;
3265 User.EllipsisConversion = false;
3266 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003267 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003268 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003269 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003270 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003271 User.After.setAsIdentityConversion();
3272 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3273 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003274 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003275 }
3276 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003277 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3278 // C++ [over.ics.user]p1:
3279 //
3280 // [...] If the user-defined conversion is specified by a
3281 // conversion function (12.3.2), the initial standard
3282 // conversion sequence converts the source type to the
3283 // implicit object parameter of the conversion function.
3284 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003285 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003286 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003287 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003288 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003289
John McCall5c32be02010-08-24 20:38:10 +00003290 // C++ [over.ics.user]p2:
3291 // The second standard conversion sequence converts the
3292 // result of the user-defined conversion to the target type
3293 // for the sequence. Since an implicit conversion sequence
3294 // is an initialization, the special rules for
3295 // initialization by user-defined conversion apply when
3296 // selecting the best user-defined conversion for a
3297 // user-defined conversion sequence (see 13.3.3 and
3298 // 13.3.3.1).
3299 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003300 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003301 }
David Blaikie8a40f702012-01-17 06:56:22 +00003302 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003303
John McCall5c32be02010-08-24 20:38:10 +00003304 case OR_No_Viable_Function:
3305 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306
John McCall5c32be02010-08-24 20:38:10 +00003307 case OR_Ambiguous:
3308 return OR_Ambiguous;
3309 }
3310
David Blaikie8a40f702012-01-17 06:56:22 +00003311 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003312}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003314bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003315Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003316 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003317 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3318 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003320 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003321 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003322 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003323 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3324 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003325 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003326 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003327 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003328 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003329 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003330 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003331 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003332 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003335}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003336
Douglas Gregor2837aa22012-02-22 17:32:19 +00003337/// \brief Compare the user-defined conversion functions or constructors
3338/// of two user-defined conversion sequences to determine whether any ordering
3339/// is possible.
3340static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003341compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003342 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003343 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003344 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003345
Douglas Gregor2837aa22012-02-22 17:32:19 +00003346 // Objective-C++:
3347 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003348 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003349 // respectively, always prefer the conversion to a function pointer,
3350 // because the function pointer is more lightweight and is more likely
3351 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003352 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003353 if (!Conv1)
3354 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003355
Douglas Gregor2837aa22012-02-22 17:32:19 +00003356 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3357 if (!Conv2)
3358 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003359
Douglas Gregor2837aa22012-02-22 17:32:19 +00003360 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3361 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3362 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3363 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003364 return Block1 ? ImplicitConversionSequence::Worse
3365 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003366 }
3367
3368 return ImplicitConversionSequence::Indistinguishable;
3369}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003370
3371static bool hasDeprecatedStringLiteralToCharPtrConversion(
3372 const ImplicitConversionSequence &ICS) {
3373 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3374 (ICS.isUserDefined() &&
3375 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3376}
3377
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378/// CompareImplicitConversionSequences - Compare two implicit
3379/// conversion sequences to determine whether one is better than the
3380/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003381static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003382CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003383 const ImplicitConversionSequence& ICS1,
3384 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003385{
3386 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3387 // conversion sequences (as defined in 13.3.3.1)
3388 // -- a standard conversion sequence (13.3.3.1.1) is a better
3389 // conversion sequence than a user-defined conversion sequence or
3390 // an ellipsis conversion sequence, and
3391 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3392 // conversion sequence than an ellipsis conversion sequence
3393 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003394 //
John McCall0d1da222010-01-12 00:44:57 +00003395 // C++0x [over.best.ics]p10:
3396 // For the purpose of ranking implicit conversion sequences as
3397 // described in 13.3.3.2, the ambiguous conversion sequence is
3398 // treated as a user-defined sequence that is indistinguishable
3399 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003400
3401 // String literal to 'char *' conversion has been deprecated in C++03. It has
3402 // been removed from C++11. We still accept this conversion, if it happens at
3403 // the best viable function. Otherwise, this conversion is considered worse
3404 // than ellipsis conversion. Consider this as an extension; this is not in the
3405 // standard. For example:
3406 //
3407 // int &f(...); // #1
3408 // void f(char*); // #2
3409 // void g() { int &r = f("foo"); }
3410 //
3411 // In C++03, we pick #2 as the best viable function.
3412 // In C++11, we pick #1 as the best viable function, because ellipsis
3413 // conversion is better than string-literal to char* conversion (since there
3414 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3415 // convert arguments, #2 would be the best viable function in C++11.
3416 // If the best viable function has this conversion, a warning will be issued
3417 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3418
3419 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3420 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3421 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3422 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3423 ? ImplicitConversionSequence::Worse
3424 : ImplicitConversionSequence::Better;
3425
Douglas Gregor5ab11652010-04-17 22:01:05 +00003426 if (ICS1.getKindRank() < ICS2.getKindRank())
3427 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003428 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003429 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003430
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003431 // The following checks require both conversion sequences to be of
3432 // the same kind.
3433 if (ICS1.getKind() != ICS2.getKind())
3434 return ImplicitConversionSequence::Indistinguishable;
3435
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003436 ImplicitConversionSequence::CompareKind Result =
3437 ImplicitConversionSequence::Indistinguishable;
3438
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003439 // Two implicit conversion sequences of the same form are
3440 // indistinguishable conversion sequences unless one of the
3441 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003442
3443 // List-initialization sequence L1 is a better conversion sequence than
3444 // list-initialization sequence L2 if:
3445 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3446 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003447 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003448 // and N1 is smaller than N2.,
3449 // even if one of the other rules in this paragraph would otherwise apply.
3450 if (!ICS1.isBad()) {
3451 if (ICS1.isStdInitializerListElement() &&
3452 !ICS2.isStdInitializerListElement())
3453 return ImplicitConversionSequence::Better;
3454 if (!ICS1.isStdInitializerListElement() &&
3455 ICS2.isStdInitializerListElement())
3456 return ImplicitConversionSequence::Worse;
3457 }
3458
John McCall0d1da222010-01-12 00:44:57 +00003459 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003460 // Standard conversion sequence S1 is a better conversion sequence than
3461 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003462 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003463 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003464 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003465 // User-defined conversion sequence U1 is a better conversion
3466 // sequence than another user-defined conversion sequence U2 if
3467 // they contain the same user-defined conversion function or
3468 // constructor and if the second standard conversion sequence of
3469 // U1 is better than the second standard conversion sequence of
3470 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003471 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003472 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003473 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003474 ICS1.UserDefined.After,
3475 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003476 else
3477 Result = compareConversionFunctions(S,
3478 ICS1.UserDefined.ConversionFunction,
3479 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480 }
3481
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003482 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003483}
3484
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003485static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3486 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3487 Qualifiers Quals;
3488 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003492 return Context.hasSameUnqualifiedType(T1, T2);
3493}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003495// Per 13.3.3.2p3, compare the given standard conversion sequences to
3496// determine if one is a proper subset of the other.
3497static ImplicitConversionSequence::CompareKind
3498compareStandardConversionSubsets(ASTContext &Context,
3499 const StandardConversionSequence& SCS1,
3500 const StandardConversionSequence& SCS2) {
3501 ImplicitConversionSequence::CompareKind Result
3502 = ImplicitConversionSequence::Indistinguishable;
3503
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003505 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003506 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3507 return ImplicitConversionSequence::Better;
3508 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3509 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003511 if (SCS1.Second != SCS2.Second) {
3512 if (SCS1.Second == ICK_Identity)
3513 Result = ImplicitConversionSequence::Better;
3514 else if (SCS2.Second == ICK_Identity)
3515 Result = ImplicitConversionSequence::Worse;
3516 else
3517 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003518 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003519 return ImplicitConversionSequence::Indistinguishable;
3520
3521 if (SCS1.Third == SCS2.Third) {
3522 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3523 : ImplicitConversionSequence::Indistinguishable;
3524 }
3525
3526 if (SCS1.Third == ICK_Identity)
3527 return Result == ImplicitConversionSequence::Worse
3528 ? ImplicitConversionSequence::Indistinguishable
3529 : ImplicitConversionSequence::Better;
3530
3531 if (SCS2.Third == ICK_Identity)
3532 return Result == ImplicitConversionSequence::Better
3533 ? ImplicitConversionSequence::Indistinguishable
3534 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003536 return ImplicitConversionSequence::Indistinguishable;
3537}
3538
Douglas Gregore696ebb2011-01-26 14:52:12 +00003539/// \brief Determine whether one of the given reference bindings is better
3540/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003541static bool
3542isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3543 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003544 // C++0x [over.ics.rank]p3b4:
3545 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3546 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003548 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003550 // reference*.
3551 //
3552 // FIXME: Rvalue references. We're going rogue with the above edits,
3553 // because the semantics in the current C++0x working paper (N3225 at the
3554 // time of this writing) break the standard definition of std::forward
3555 // and std::reference_wrapper when dealing with references to functions.
3556 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003557 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3558 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3559 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560
Douglas Gregore696ebb2011-01-26 14:52:12 +00003561 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3562 SCS2.IsLvalueReference) ||
3563 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003564 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003565}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003567/// CompareStandardConversionSequences - Compare two standard
3568/// conversion sequences to determine whether one is better than the
3569/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003570static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003571CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003572 const StandardConversionSequence& SCS1,
3573 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003574{
3575 // Standard conversion sequence S1 is a better conversion sequence
3576 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3577
3578 // -- S1 is a proper subsequence of S2 (comparing the conversion
3579 // sequences in the canonical form defined by 13.3.3.1.1,
3580 // excluding any Lvalue Transformation; the identity conversion
3581 // sequence is considered to be a subsequence of any
3582 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003583 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003584 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003585 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003586
3587 // -- the rank of S1 is better than the rank of S2 (by the rules
3588 // defined below), or, if not that,
3589 ImplicitConversionRank Rank1 = SCS1.getRank();
3590 ImplicitConversionRank Rank2 = SCS2.getRank();
3591 if (Rank1 < Rank2)
3592 return ImplicitConversionSequence::Better;
3593 else if (Rank2 < Rank1)
3594 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003595
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003596 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3597 // are indistinguishable unless one of the following rules
3598 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003599
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003600 // A conversion that is not a conversion of a pointer, or
3601 // pointer to member, to bool is better than another conversion
3602 // that is such a conversion.
3603 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3604 return SCS2.isPointerConversionToBool()
3605 ? ImplicitConversionSequence::Better
3606 : ImplicitConversionSequence::Worse;
3607
Douglas Gregor5c407d92008-10-23 00:40:37 +00003608 // C++ [over.ics.rank]p4b2:
3609 //
3610 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003611 // conversion of B* to A* is better than conversion of B* to
3612 // void*, and conversion of A* to void* is better than conversion
3613 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003614 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003615 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003616 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003617 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003618 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3619 // Exactly one of the conversion sequences is a conversion to
3620 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003621 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3622 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003623 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3624 // Neither conversion sequence converts to a void pointer; compare
3625 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003626 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003627 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003628 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003629 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3630 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003631 // Both conversion sequences are conversions to void
3632 // pointers. Compare the source types to determine if there's an
3633 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003634 QualType FromType1 = SCS1.getFromType();
3635 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003636
3637 // Adjust the types we're converting from via the array-to-pointer
3638 // conversion, if we need to.
3639 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003640 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003641 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003642 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003643
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003644 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3645 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003646
Richard Smith0f59cb32015-12-18 21:45:41 +00003647 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003648 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003649 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003650 return ImplicitConversionSequence::Worse;
3651
3652 // Objective-C++: If one interface is more specific than the
3653 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003654 const ObjCObjectPointerType* FromObjCPtr1
3655 = FromType1->getAs<ObjCObjectPointerType>();
3656 const ObjCObjectPointerType* FromObjCPtr2
3657 = FromType2->getAs<ObjCObjectPointerType>();
3658 if (FromObjCPtr1 && FromObjCPtr2) {
3659 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3660 FromObjCPtr2);
3661 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3662 FromObjCPtr1);
3663 if (AssignLeft != AssignRight) {
3664 return AssignLeft? ImplicitConversionSequence::Better
3665 : ImplicitConversionSequence::Worse;
3666 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003667 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003668 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003669
3670 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3671 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003672 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003673 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003674 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003675
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003676 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003677 // Check for a better reference binding based on the kind of bindings.
3678 if (isBetterReferenceBindingKind(SCS1, SCS2))
3679 return ImplicitConversionSequence::Better;
3680 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3681 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Sebastian Redlb28b4072009-03-22 23:49:27 +00003683 // C++ [over.ics.rank]p3b4:
3684 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3685 // which the references refer are the same type except for
3686 // top-level cv-qualifiers, and the type to which the reference
3687 // initialized by S2 refers is more cv-qualified than the type
3688 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003689 QualType T1 = SCS1.getToType(2);
3690 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003691 T1 = S.Context.getCanonicalType(T1);
3692 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003694 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3695 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003696 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003697 // Objective-C++ ARC: If the references refer to objects with different
3698 // lifetimes, prefer bindings that don't change lifetime.
3699 if (SCS1.ObjCLifetimeConversionBinding !=
3700 SCS2.ObjCLifetimeConversionBinding) {
3701 return SCS1.ObjCLifetimeConversionBinding
3702 ? ImplicitConversionSequence::Worse
3703 : ImplicitConversionSequence::Better;
3704 }
3705
Chandler Carruth8e543b32010-12-12 08:17:55 +00003706 // If the type is an array type, promote the element qualifiers to the
3707 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003708 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003709 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003710 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003711 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003712 if (T2.isMoreQualifiedThan(T1))
3713 return ImplicitConversionSequence::Better;
3714 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003715 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003716 }
3717 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003718
Francois Pichet08d2fa02011-09-18 21:37:37 +00003719 // In Microsoft mode, prefer an integral conversion to a
3720 // floating-to-integral conversion if the integral conversion
3721 // is between types of the same size.
3722 // For example:
3723 // void f(float);
3724 // void f(int);
3725 // int main {
3726 // long a;
3727 // f(a);
3728 // }
3729 // Here, MSVC will call f(int) instead of generating a compile error
3730 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003731 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3732 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003733 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003734 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003735 return ImplicitConversionSequence::Better;
3736
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003737 return ImplicitConversionSequence::Indistinguishable;
3738}
3739
3740/// CompareQualificationConversions - Compares two standard conversion
3741/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003742/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003743static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003744CompareQualificationConversions(Sema &S,
3745 const StandardConversionSequence& SCS1,
3746 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003747 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003748 // -- S1 and S2 differ only in their qualification conversion and
3749 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3750 // cv-qualification signature of type T1 is a proper subset of
3751 // the cv-qualification signature of type T2, and S1 is not the
3752 // deprecated string literal array-to-pointer conversion (4.2).
3753 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3754 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3755 return ImplicitConversionSequence::Indistinguishable;
3756
3757 // FIXME: the example in the standard doesn't use a qualification
3758 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003759 QualType T1 = SCS1.getToType(2);
3760 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003761 T1 = S.Context.getCanonicalType(T1);
3762 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003763 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003764 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3765 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003766
3767 // If the types are the same, we won't learn anything by unwrapped
3768 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003769 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003770 return ImplicitConversionSequence::Indistinguishable;
3771
Chandler Carruth607f38e2009-12-29 07:16:59 +00003772 // If the type is an array type, promote the element qualifiers to the type
3773 // for comparison.
3774 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003775 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003776 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003777 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003778
Mike Stump11289f42009-09-09 15:08:12 +00003779 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003780 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003781
3782 // Objective-C++ ARC:
3783 // Prefer qualification conversions not involving a change in lifetime
3784 // to qualification conversions that do not change lifetime.
3785 if (SCS1.QualificationIncludesObjCLifetime !=
3786 SCS2.QualificationIncludesObjCLifetime) {
3787 Result = SCS1.QualificationIncludesObjCLifetime
3788 ? ImplicitConversionSequence::Worse
3789 : ImplicitConversionSequence::Better;
3790 }
3791
John McCall5c32be02010-08-24 20:38:10 +00003792 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003793 // Within each iteration of the loop, we check the qualifiers to
3794 // determine if this still looks like a qualification
3795 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003796 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003797 // until there are no more pointers or pointers-to-members left
3798 // to unwrap. This essentially mimics what
3799 // IsQualificationConversion does, but here we're checking for a
3800 // strict subset of qualifiers.
3801 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3802 // The qualifiers are the same, so this doesn't tell us anything
3803 // about how the sequences rank.
3804 ;
3805 else if (T2.isMoreQualifiedThan(T1)) {
3806 // T1 has fewer qualifiers, so it could be the better sequence.
3807 if (Result == ImplicitConversionSequence::Worse)
3808 // Neither has qualifiers that are a subset of the other's
3809 // qualifiers.
3810 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003811
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003812 Result = ImplicitConversionSequence::Better;
3813 } else if (T1.isMoreQualifiedThan(T2)) {
3814 // T2 has fewer qualifiers, so it could be the better sequence.
3815 if (Result == ImplicitConversionSequence::Better)
3816 // Neither has qualifiers that are a subset of the other's
3817 // qualifiers.
3818 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003819
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003820 Result = ImplicitConversionSequence::Worse;
3821 } else {
3822 // Qualifiers are disjoint.
3823 return ImplicitConversionSequence::Indistinguishable;
3824 }
3825
3826 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003827 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003828 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003829 }
3830
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003831 // Check that the winning standard conversion sequence isn't using
3832 // the deprecated string literal array to pointer conversion.
3833 switch (Result) {
3834 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003835 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003836 Result = ImplicitConversionSequence::Indistinguishable;
3837 break;
3838
3839 case ImplicitConversionSequence::Indistinguishable:
3840 break;
3841
3842 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003843 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003844 Result = ImplicitConversionSequence::Indistinguishable;
3845 break;
3846 }
3847
3848 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003849}
3850
Douglas Gregor5c407d92008-10-23 00:40:37 +00003851/// CompareDerivedToBaseConversions - Compares two standard conversion
3852/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003853/// various kinds of derived-to-base conversions (C++
3854/// [over.ics.rank]p4b3). As part of these checks, we also look at
3855/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003856static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003857CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003858 const StandardConversionSequence& SCS1,
3859 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003860 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003861 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003862 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003863 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003864
3865 // Adjust the types we're converting from via the array-to-pointer
3866 // conversion, if we need to.
3867 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003868 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003869 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003870 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003871
3872 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003873 FromType1 = S.Context.getCanonicalType(FromType1);
3874 ToType1 = S.Context.getCanonicalType(ToType1);
3875 FromType2 = S.Context.getCanonicalType(FromType2);
3876 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003877
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003878 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003879 //
3880 // If class B is derived directly or indirectly from class A and
3881 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003882 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003883 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003884 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003885 SCS2.Second == ICK_Pointer_Conversion &&
3886 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3887 FromType1->isPointerType() && FromType2->isPointerType() &&
3888 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003889 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003890 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003891 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003892 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003893 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003894 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003895 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003896 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003897
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003898 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003899 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003900 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003901 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003902 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003903 return ImplicitConversionSequence::Worse;
3904 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003905
3906 // -- conversion of B* to A* is better than conversion of C* to A*,
3907 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003908 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003909 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003910 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003911 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003912 }
3913 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3914 SCS2.Second == ICK_Pointer_Conversion) {
3915 const ObjCObjectPointerType *FromPtr1
3916 = FromType1->getAs<ObjCObjectPointerType>();
3917 const ObjCObjectPointerType *FromPtr2
3918 = FromType2->getAs<ObjCObjectPointerType>();
3919 const ObjCObjectPointerType *ToPtr1
3920 = ToType1->getAs<ObjCObjectPointerType>();
3921 const ObjCObjectPointerType *ToPtr2
3922 = ToType2->getAs<ObjCObjectPointerType>();
3923
3924 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3925 // Apply the same conversion ranking rules for Objective-C pointer types
3926 // that we do for C++ pointers to class types. However, we employ the
3927 // Objective-C pseudo-subtyping relationship used for assignment of
3928 // Objective-C pointer types.
3929 bool FromAssignLeft
3930 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3931 bool FromAssignRight
3932 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3933 bool ToAssignLeft
3934 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3935 bool ToAssignRight
3936 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3937
3938 // A conversion to an a non-id object pointer type or qualified 'id'
3939 // type is better than a conversion to 'id'.
3940 if (ToPtr1->isObjCIdType() &&
3941 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3942 return ImplicitConversionSequence::Worse;
3943 if (ToPtr2->isObjCIdType() &&
3944 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3945 return ImplicitConversionSequence::Better;
3946
3947 // A conversion to a non-id object pointer type is better than a
3948 // conversion to a qualified 'id' type
3949 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3950 return ImplicitConversionSequence::Worse;
3951 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3952 return ImplicitConversionSequence::Better;
3953
3954 // A conversion to an a non-Class object pointer type or qualified 'Class'
3955 // type is better than a conversion to 'Class'.
3956 if (ToPtr1->isObjCClassType() &&
3957 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3958 return ImplicitConversionSequence::Worse;
3959 if (ToPtr2->isObjCClassType() &&
3960 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3961 return ImplicitConversionSequence::Better;
3962
3963 // A conversion to a non-Class object pointer type is better than a
3964 // conversion to a qualified 'Class' type.
3965 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3966 return ImplicitConversionSequence::Worse;
3967 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3968 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003969
Douglas Gregor058d3de2011-01-31 18:51:41 +00003970 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3971 if (S.Context.hasSameType(FromType1, FromType2) &&
3972 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3973 (ToAssignLeft != ToAssignRight))
3974 return ToAssignLeft? ImplicitConversionSequence::Worse
3975 : ImplicitConversionSequence::Better;
3976
3977 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3978 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3979 (FromAssignLeft != FromAssignRight))
3980 return FromAssignLeft? ImplicitConversionSequence::Better
3981 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003982 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003983 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003984
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003985 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003986 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3987 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3988 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003990 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003992 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003994 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003996 ToType2->getAs<MemberPointerType>();
3997 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3998 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3999 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4000 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4001 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4002 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4003 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4004 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004005 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004006 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004007 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004008 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004009 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004010 return ImplicitConversionSequence::Better;
4011 }
4012 // conversion of B::* to C::* is better than conversion of A::* to C::*
4013 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004014 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004015 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004016 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004017 return ImplicitConversionSequence::Worse;
4018 }
4019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
Douglas Gregor5ab11652010-04-17 22:01:05 +00004021 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004022 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004023 // -- binding of an expression of type C to a reference of type
4024 // B& is better than binding an expression of type C to a
4025 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004026 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4027 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004028 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004029 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004030 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004031 return ImplicitConversionSequence::Worse;
4032 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004033
Douglas Gregor2fe98832008-11-03 19:09:14 +00004034 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004035 // -- binding of an expression of type B to a reference of type
4036 // A& is better than binding an expression of type C to a
4037 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004038 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4039 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004040 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004041 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004042 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004043 return ImplicitConversionSequence::Worse;
4044 }
4045 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004046
Douglas Gregor5c407d92008-10-23 00:40:37 +00004047 return ImplicitConversionSequence::Indistinguishable;
4048}
4049
Douglas Gregor45bb4832013-03-26 23:36:30 +00004050/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4051/// C++ class.
4052static bool isTypeValid(QualType T) {
4053 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4054 return !Record->isInvalidDecl();
4055
4056 return true;
4057}
4058
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004059/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4060/// determine whether they are reference-related,
4061/// reference-compatible, reference-compatible with added
4062/// qualification, or incompatible, for use in C++ initialization by
4063/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4064/// type, and the first type (T1) is the pointee type of the reference
4065/// type being initialized.
4066Sema::ReferenceCompareResult
4067Sema::CompareReferenceRelationship(SourceLocation Loc,
4068 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004069 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004070 bool &ObjCConversion,
4071 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004072 assert(!OrigT1->isReferenceType() &&
4073 "T1 must be the pointee type of the reference type");
4074 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4075
4076 QualType T1 = Context.getCanonicalType(OrigT1);
4077 QualType T2 = Context.getCanonicalType(OrigT2);
4078 Qualifiers T1Quals, T2Quals;
4079 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4080 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4081
4082 // C++ [dcl.init.ref]p4:
4083 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4084 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4085 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004086 DerivedToBase = false;
4087 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004088 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004089 if (UnqualT1 == UnqualT2) {
4090 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004091 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004092 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004093 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004094 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004095 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4096 UnqualT2->isObjCObjectOrInterfaceType() &&
4097 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4098 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099 else
4100 return Ref_Incompatible;
4101
4102 // At this point, we know that T1 and T2 are reference-related (at
4103 // least).
4104
4105 // If the type is an array type, promote the element qualifiers to the type
4106 // for comparison.
4107 if (isa<ArrayType>(T1) && T1Quals)
4108 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4109 if (isa<ArrayType>(T2) && T2Quals)
4110 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4111
4112 // C++ [dcl.init.ref]p4:
4113 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4114 // reference-related to T2 and cv1 is the same cv-qualification
4115 // as, or greater cv-qualification than, cv2. For purposes of
4116 // overload resolution, cases for which cv1 is greater
4117 // cv-qualification than cv2 are identified as
4118 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004119 //
4120 // Note that we also require equivalence of Objective-C GC and address-space
4121 // qualifiers when performing these computations, so that e.g., an int in
4122 // address space 1 is not reference-compatible with an int in address
4123 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004124 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4125 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004126 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4127 ObjCLifetimeConversion = true;
4128
John McCall31168b02011-06-15 23:02:42 +00004129 T1Quals.removeObjCLifetime();
4130 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004131 }
4132
Douglas Gregord517d552011-04-28 17:56:11 +00004133 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004134 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004135 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004136 return Ref_Compatible_With_Added_Qualification;
4137 else
4138 return Ref_Related;
4139}
4140
Douglas Gregor836a7e82010-08-11 02:15:33 +00004141/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004142/// with DeclType. Return true if something definite is found.
4143static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004144FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4145 QualType DeclType, SourceLocation DeclLoc,
4146 Expr *Init, QualType T2, bool AllowRvalues,
4147 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004148 assert(T2->isRecordType() && "Can only find conversions of record types.");
4149 CXXRecordDecl *T2RecordDecl
4150 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4151
Richard Smith100b24a2014-04-17 01:52:14 +00004152 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004153 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4154 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004155 NamedDecl *D = *I;
4156 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4157 if (isa<UsingShadowDecl>(D))
4158 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4159
4160 FunctionTemplateDecl *ConvTemplate
4161 = dyn_cast<FunctionTemplateDecl>(D);
4162 CXXConversionDecl *Conv;
4163 if (ConvTemplate)
4164 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4165 else
4166 Conv = cast<CXXConversionDecl>(D);
4167
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004169 // explicit conversions, skip it.
4170 if (!AllowExplicit && Conv->isExplicit())
4171 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregor836a7e82010-08-11 02:15:33 +00004173 if (AllowRvalues) {
4174 bool DerivedToBase = false;
4175 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004176 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004177
4178 // If we are initializing an rvalue reference, don't permit conversion
4179 // functions that return lvalues.
4180 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4181 const ReferenceType *RefType
4182 = Conv->getConversionType()->getAs<LValueReferenceType>();
4183 if (RefType && !RefType->getPointeeType()->isFunctionType())
4184 continue;
4185 }
4186
Douglas Gregor836a7e82010-08-11 02:15:33 +00004187 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004188 S.CompareReferenceRelationship(
4189 DeclLoc,
4190 Conv->getConversionType().getNonReferenceType()
4191 .getUnqualifiedType(),
4192 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004193 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004194 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004195 continue;
4196 } else {
4197 // If the conversion function doesn't return a reference type,
4198 // it can't be considered for this conversion. An rvalue reference
4199 // is only acceptable if its referencee is a function type.
4200
4201 const ReferenceType *RefType =
4202 Conv->getConversionType()->getAs<ReferenceType>();
4203 if (!RefType ||
4204 (!RefType->isLValueReferenceType() &&
4205 !RefType->getPointeeType()->isFunctionType()))
4206 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregor836a7e82010-08-11 02:15:33 +00004209 if (ConvTemplate)
4210 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004211 Init, DeclType, CandidateSet,
4212 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004213 else
4214 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004215 DeclType, CandidateSet,
4216 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004217 }
4218
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004219 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4220
Sebastian Redld92badf2010-06-30 18:13:39 +00004221 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004222 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004223 case OR_Success:
4224 // C++ [over.ics.ref]p1:
4225 //
4226 // [...] If the parameter binds directly to the result of
4227 // applying a conversion function to the argument
4228 // expression, the implicit conversion sequence is a
4229 // user-defined conversion sequence (13.3.3.1.2), with the
4230 // second standard conversion sequence either an identity
4231 // conversion or, if the conversion function returns an
4232 // entity of a type that is a derived class of the parameter
4233 // type, a derived-to-base Conversion.
4234 if (!Best->FinalConversion.DirectBinding)
4235 return false;
4236
4237 ICS.setUserDefined();
4238 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4239 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004240 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004241 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004242 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004243 ICS.UserDefined.EllipsisConversion = false;
4244 assert(ICS.UserDefined.After.ReferenceBinding &&
4245 ICS.UserDefined.After.DirectBinding &&
4246 "Expected a direct reference binding!");
4247 return true;
4248
4249 case OR_Ambiguous:
4250 ICS.setAmbiguous();
4251 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4252 Cand != CandidateSet.end(); ++Cand)
4253 if (Cand->Viable)
4254 ICS.Ambiguous.addConversion(Cand->Function);
4255 return true;
4256
4257 case OR_No_Viable_Function:
4258 case OR_Deleted:
4259 // There was no suitable conversion, or we found a deleted
4260 // conversion; continue with other checks.
4261 return false;
4262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
David Blaikie8a40f702012-01-17 06:56:22 +00004264 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004265}
4266
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004267/// \brief Compute an implicit conversion sequence for reference
4268/// initialization.
4269static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004270TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004271 SourceLocation DeclLoc,
4272 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004273 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004274 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4275
4276 // Most paths end in a failed conversion.
4277 ImplicitConversionSequence ICS;
4278 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4279
4280 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4281 QualType T2 = Init->getType();
4282
4283 // If the initializer is the address of an overloaded function, try
4284 // to resolve the overloaded function. If all goes well, T2 is the
4285 // type of the resulting function.
4286 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4287 DeclAccessPair Found;
4288 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4289 false, Found))
4290 T2 = Fn->getType();
4291 }
4292
4293 // Compute some basic properties of the types and the initializer.
4294 bool isRValRef = DeclType->isRValueReferenceType();
4295 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004296 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004297 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004298 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004299 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004300 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004301 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004302
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004303
Sebastian Redld92badf2010-06-30 18:13:39 +00004304 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004305 // A reference to type "cv1 T1" is initialized by an expression
4306 // of type "cv2 T2" as follows:
4307
Sebastian Redld92badf2010-06-30 18:13:39 +00004308 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004309 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004310 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4311 // reference-compatible with "cv2 T2," or
4312 //
4313 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4314 if (InitCategory.isLValue() &&
4315 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004316 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004317 // When a parameter of reference type binds directly (8.5.3)
4318 // to an argument expression, the implicit conversion sequence
4319 // is the identity conversion, unless the argument expression
4320 // has a type that is a derived class of the parameter type,
4321 // in which case the implicit conversion sequence is a
4322 // derived-to-base Conversion (13.3.3.1).
4323 ICS.setStandard();
4324 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004325 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4326 : ObjCConversion? ICK_Compatible_Conversion
4327 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004328 ICS.Standard.Third = ICK_Identity;
4329 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4330 ICS.Standard.setToType(0, T2);
4331 ICS.Standard.setToType(1, T1);
4332 ICS.Standard.setToType(2, T1);
4333 ICS.Standard.ReferenceBinding = true;
4334 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004335 ICS.Standard.IsLvalueReference = !isRValRef;
4336 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4337 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004338 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004339 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004340 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004341 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004342
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 // Nothing more to do: the inaccessibility/ambiguity check for
4344 // derived-to-base conversions is suppressed when we're
4345 // computing the implicit conversion sequence (C++
4346 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004347 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004349
Sebastian Redld92badf2010-06-30 18:13:39 +00004350 // -- has a class type (i.e., T2 is a class type), where T1 is
4351 // not reference-related to T2, and can be implicitly
4352 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4353 // is reference-compatible with "cv3 T3" 92) (this
4354 // conversion is selected by enumerating the applicable
4355 // conversion functions (13.3.1.6) and choosing the best
4356 // one through overload resolution (13.3)),
4357 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004358 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004359 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004360 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4361 Init, T2, /*AllowRvalues=*/false,
4362 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004363 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004364 }
4365 }
4366
Sebastian Redld92badf2010-06-30 18:13:39 +00004367 // -- Otherwise, the reference shall be an lvalue reference to a
4368 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004369 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004370 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004371 return ICS;
4372
Douglas Gregorf143cd52011-01-24 16:14:37 +00004373 // -- If the initializer expression
4374 //
4375 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004376 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004377 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4378 (InitCategory.isXValue() ||
4379 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4380 (InitCategory.isLValue() && T2->isFunctionType()))) {
4381 ICS.setStandard();
4382 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004384 : ObjCConversion? ICK_Compatible_Conversion
4385 : ICK_Identity;
4386 ICS.Standard.Third = ICK_Identity;
4387 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4388 ICS.Standard.setToType(0, T2);
4389 ICS.Standard.setToType(1, T1);
4390 ICS.Standard.setToType(2, T1);
4391 ICS.Standard.ReferenceBinding = true;
4392 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4393 // binding unless we're binding to a class prvalue.
4394 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4395 // allow the use of rvalue references in C++98/03 for the benefit of
4396 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004398 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004399 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004400 ICS.Standard.IsLvalueReference = !isRValRef;
4401 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004403 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004404 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004405 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004406 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregorf143cd52011-01-24 16:14:37 +00004410 // -- has a class type (i.e., T2 is a class type), where T1 is not
4411 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412 // an xvalue, class prvalue, or function lvalue of type
4413 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004414 // "cv3 T3",
4415 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004417 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004419 // class subobject).
4420 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004421 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004422 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4423 Init, T2, /*AllowRvalues=*/true,
4424 AllowExplicit)) {
4425 // In the second case, if the reference is an rvalue reference
4426 // and the second standard conversion sequence of the
4427 // user-defined conversion sequence includes an lvalue-to-rvalue
4428 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004430 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4431 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4432
Douglas Gregor95273c32011-01-21 16:36:05 +00004433 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435
Richard Smith19172c42014-07-14 02:28:44 +00004436 // A temporary of function type cannot be created; don't even try.
4437 if (T1->isFunctionType())
4438 return ICS;
4439
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004440 // -- Otherwise, a temporary of type "cv1 T1" is created and
4441 // initialized from the initializer expression using the
4442 // rules for a non-reference copy initialization (8.5). The
4443 // reference is then bound to the temporary. If T1 is
4444 // reference-related to T2, cv1 must be the same
4445 // cv-qualification as, or greater cv-qualification than,
4446 // cv2; otherwise, the program is ill-formed.
4447 if (RefRelationship == Sema::Ref_Related) {
4448 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4449 // we would be reference-compatible or reference-compatible with
4450 // added qualification. But that wasn't the case, so the reference
4451 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004452 //
4453 // Note that we only want to check address spaces and cvr-qualifiers here.
4454 // ObjC GC and lifetime qualifiers aren't important.
4455 Qualifiers T1Quals = T1.getQualifiers();
4456 Qualifiers T2Quals = T2.getQualifiers();
4457 T1Quals.removeObjCGCAttr();
4458 T1Quals.removeObjCLifetime();
4459 T2Quals.removeObjCGCAttr();
4460 T2Quals.removeObjCLifetime();
4461 if (!T1Quals.compatiblyIncludes(T2Quals))
4462 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 }
4464
4465 // If at least one of the types is a class type, the types are not
4466 // related, and we aren't allowed any user conversions, the
4467 // reference binding fails. This case is important for breaking
4468 // recursion, since TryImplicitConversion below will attempt to
4469 // create a temporary through the use of a copy constructor.
4470 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4471 (T1->isRecordType() || T2->isRecordType()))
4472 return ICS;
4473
Douglas Gregorcba72b12011-01-21 05:18:22 +00004474 // If T1 is reference-related to T2 and the reference is an rvalue
4475 // reference, the initializer expression shall not be an lvalue.
4476 if (RefRelationship >= Sema::Ref_Related &&
4477 isRValRef && Init->Classify(S.Context).isLValue())
4478 return ICS;
4479
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004481 // When a parameter of reference type is not bound directly to
4482 // an argument expression, the conversion sequence is the one
4483 // required to convert the argument expression to the
4484 // underlying type of the reference according to
4485 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4486 // to copy-initializing a temporary of the underlying type with
4487 // the argument expression. Any difference in top-level
4488 // cv-qualification is subsumed by the initialization itself
4489 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004490 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4491 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004492 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004493 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004494 /*AllowObjCWritebackConversion=*/false,
4495 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496
4497 // Of course, that's still a reference binding.
4498 if (ICS.isStandard()) {
4499 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004500 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004501 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004502 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004503 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004504 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004505 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004506 const ReferenceType *LValRefType =
4507 ICS.UserDefined.ConversionFunction->getReturnType()
4508 ->getAs<LValueReferenceType>();
4509
4510 // C++ [over.ics.ref]p3:
4511 // Except for an implicit object parameter, for which see 13.3.1, a
4512 // standard conversion sequence cannot be formed if it requires [...]
4513 // binding an rvalue reference to an lvalue other than a function
4514 // lvalue.
4515 // Note that the function case is not possible here.
4516 if (DeclType->isRValueReferenceType() && LValRefType) {
4517 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4518 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4519 // reference to an rvalue!
4520 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4521 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004522 }
Richard Smith19172c42014-07-14 02:28:44 +00004523
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004524 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004525 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004526 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004527 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4528 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004529 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4530 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004531 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004532
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004533 return ICS;
4534}
4535
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004536static ImplicitConversionSequence
4537TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4538 bool SuppressUserConversions,
4539 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004540 bool AllowObjCWritebackConversion,
4541 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004542
4543/// TryListConversion - Try to copy-initialize a value of type ToType from the
4544/// initializer list From.
4545static ImplicitConversionSequence
4546TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4547 bool SuppressUserConversions,
4548 bool InOverloadResolution,
4549 bool AllowObjCWritebackConversion) {
4550 // C++11 [over.ics.list]p1:
4551 // When an argument is an initializer list, it is not an expression and
4552 // special rules apply for converting it to a parameter type.
4553
4554 ImplicitConversionSequence Result;
4555 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4556
Sebastian Redl09edce02012-01-23 22:09:39 +00004557 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004558 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004559 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004560 return Result;
4561
Larisse Voufo19d08672015-01-27 18:47:05 +00004562 // Per DR1467:
4563 // If the parameter type is a class X and the initializer list has a single
4564 // element of type cv U, where U is X or a class derived from X, the
4565 // implicit conversion sequence is the one required to convert the element
4566 // to the parameter type.
4567 //
4568 // Otherwise, if the parameter type is a character array [... ]
4569 // and the initializer list has a single element that is an
4570 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4571 // implicit conversion sequence is the identity conversion.
4572 if (From->getNumInits() == 1) {
4573 if (ToType->isRecordType()) {
4574 QualType InitType = From->getInit(0)->getType();
4575 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004576 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004577 return TryCopyInitialization(S, From->getInit(0), ToType,
4578 SuppressUserConversions,
4579 InOverloadResolution,
4580 AllowObjCWritebackConversion);
4581 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004582 // FIXME: Check the other conditions here: array of character type,
4583 // initializer is a string literal.
4584 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004585 InitializedEntity Entity =
4586 InitializedEntity::InitializeParameter(S.Context, ToType,
4587 /*Consumed=*/false);
4588 if (S.CanPerformCopyInitialization(Entity, From)) {
4589 Result.setStandard();
4590 Result.Standard.setAsIdentityConversion();
4591 Result.Standard.setFromType(ToType);
4592 Result.Standard.setAllToTypes(ToType);
4593 return Result;
4594 }
4595 }
4596 }
4597
4598 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004599 // C++11 [over.ics.list]p2:
4600 // If the parameter type is std::initializer_list<X> or "array of X" and
4601 // all the elements can be implicitly converted to X, the implicit
4602 // conversion sequence is the worst conversion necessary to convert an
4603 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004604 //
4605 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004606 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004607 // list has exactly N elements or if it has fewer than N elements and X is
4608 // default-constructible, and if all the elements of the initializer list
4609 // can be implicitly converted to X, the implicit conversion sequence is
4610 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004611 //
4612 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004613 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004614 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004615 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004616 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004617 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004618 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004619 if (!X.isNull()) {
4620 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4621 Expr *Init = From->getInit(i);
4622 ImplicitConversionSequence ICS =
4623 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4624 InOverloadResolution,
4625 AllowObjCWritebackConversion);
4626 // If a single element isn't convertible, fail.
4627 if (ICS.isBad()) {
4628 Result = ICS;
4629 break;
4630 }
4631 // Otherwise, look for the worst conversion.
4632 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004633 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4634 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004635 ImplicitConversionSequence::Worse)
4636 Result = ICS;
4637 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004638
4639 // For an empty list, we won't have computed any conversion sequence.
4640 // Introduce the identity conversion sequence.
4641 if (From->getNumInits() == 0) {
4642 Result.setStandard();
4643 Result.Standard.setAsIdentityConversion();
4644 Result.Standard.setFromType(ToType);
4645 Result.Standard.setAllToTypes(ToType);
4646 }
4647
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004648 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004649 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004650 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004651
Larisse Voufo19d08672015-01-27 18:47:05 +00004652 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004653 // C++11 [over.ics.list]p3:
4654 // Otherwise, if the parameter is a non-aggregate class X and overload
4655 // resolution chooses a single best constructor [...] the implicit
4656 // conversion sequence is a user-defined conversion sequence. If multiple
4657 // constructors are viable but none is better than the others, the
4658 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004659 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4660 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004661 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4662 /*AllowExplicit=*/false,
4663 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004664 AllowObjCWritebackConversion,
4665 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004666 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004667
Larisse Voufo19d08672015-01-27 18:47:05 +00004668 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004669 // C++11 [over.ics.list]p4:
4670 // Otherwise, if the parameter has an aggregate type which can be
4671 // initialized from the initializer list [...] the implicit conversion
4672 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004673 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004674 // Type is an aggregate, argument is an init list. At this point it comes
4675 // down to checking whether the initialization works.
4676 // FIXME: Find out whether this parameter is consumed or not.
4677 InitializedEntity Entity =
4678 InitializedEntity::InitializeParameter(S.Context, ToType,
4679 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004680 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004681 Result.setUserDefined();
4682 Result.UserDefined.Before.setAsIdentityConversion();
4683 // Initializer lists don't have a type.
4684 Result.UserDefined.Before.setFromType(QualType());
4685 Result.UserDefined.Before.setAllToTypes(QualType());
4686
4687 Result.UserDefined.After.setAsIdentityConversion();
4688 Result.UserDefined.After.setFromType(ToType);
4689 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004690 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004691 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004692 return Result;
4693 }
4694
Larisse Voufo19d08672015-01-27 18:47:05 +00004695 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004696 // C++11 [over.ics.list]p5:
4697 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004698 if (ToType->isReferenceType()) {
4699 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4700 // mention initializer lists in any way. So we go by what list-
4701 // initialization would do and try to extrapolate from that.
4702
4703 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4704
4705 // If the initializer list has a single element that is reference-related
4706 // to the parameter type, we initialize the reference from that.
4707 if (From->getNumInits() == 1) {
4708 Expr *Init = From->getInit(0);
4709
4710 QualType T2 = Init->getType();
4711
4712 // If the initializer is the address of an overloaded function, try
4713 // to resolve the overloaded function. If all goes well, T2 is the
4714 // type of the resulting function.
4715 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4716 DeclAccessPair Found;
4717 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4718 Init, ToType, false, Found))
4719 T2 = Fn->getType();
4720 }
4721
4722 // Compute some basic properties of the types and the initializer.
4723 bool dummy1 = false;
4724 bool dummy2 = false;
4725 bool dummy3 = false;
4726 Sema::ReferenceCompareResult RefRelationship
4727 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4728 dummy2, dummy3);
4729
Richard Smith4d2bbd72013-09-06 01:22:42 +00004730 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004731 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4732 SuppressUserConversions,
4733 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004734 }
Sebastian Redldf888642011-12-03 14:54:30 +00004735 }
4736
4737 // Otherwise, we bind the reference to a temporary created from the
4738 // initializer list.
4739 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4740 InOverloadResolution,
4741 AllowObjCWritebackConversion);
4742 if (Result.isFailure())
4743 return Result;
4744 assert(!Result.isEllipsis() &&
4745 "Sub-initialization cannot result in ellipsis conversion.");
4746
4747 // Can we even bind to a temporary?
4748 if (ToType->isRValueReferenceType() ||
4749 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4750 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4751 Result.UserDefined.After;
4752 SCS.ReferenceBinding = true;
4753 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4754 SCS.BindsToRvalue = true;
4755 SCS.BindsToFunctionLvalue = false;
4756 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4757 SCS.ObjCLifetimeConversionBinding = false;
4758 } else
4759 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4760 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004761 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004762 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004763
Larisse Voufo19d08672015-01-27 18:47:05 +00004764 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004765 // C++11 [over.ics.list]p6:
4766 // Otherwise, if the parameter type is not a class:
4767 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004768 // - if the initializer list has one element that is not itself an
4769 // initializer list, the implicit conversion sequence is the one
4770 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004771 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004772 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004773 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4774 SuppressUserConversions,
4775 InOverloadResolution,
4776 AllowObjCWritebackConversion);
4777 // - if the initializer list has no elements, the implicit conversion
4778 // sequence is the identity conversion.
4779 else if (NumInits == 0) {
4780 Result.setStandard();
4781 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004782 Result.Standard.setFromType(ToType);
4783 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004784 }
4785 return Result;
4786 }
4787
Larisse Voufo19d08672015-01-27 18:47:05 +00004788 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004789 // C++11 [over.ics.list]p7:
4790 // In all cases other than those enumerated above, no conversion is possible
4791 return Result;
4792}
4793
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004794/// TryCopyInitialization - Try to copy-initialize a value of type
4795/// ToType from the expression From. Return the implicit conversion
4796/// sequence required to pass this argument, which may be a bad
4797/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004798/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004799/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004800static ImplicitConversionSequence
4801TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004803 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004804 bool AllowObjCWritebackConversion,
4805 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004806 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4807 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4808 InOverloadResolution,AllowObjCWritebackConversion);
4809
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004810 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004811 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004812 /*FIXME:*/From->getLocStart(),
4813 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004814 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004815
John McCall5c32be02010-08-24 20:38:10 +00004816 return TryImplicitConversion(S, From, ToType,
4817 SuppressUserConversions,
4818 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004819 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004820 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004821 AllowObjCWritebackConversion,
4822 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004823}
4824
Anna Zaks1b068122011-07-28 19:46:48 +00004825static bool TryCopyInitialization(const CanQualType FromQTy,
4826 const CanQualType ToQTy,
4827 Sema &S,
4828 SourceLocation Loc,
4829 ExprValueKind FromVK) {
4830 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4831 ImplicitConversionSequence ICS =
4832 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4833
4834 return !ICS.isBad();
4835}
4836
Douglas Gregor436424c2008-11-18 23:14:02 +00004837/// TryObjectArgumentInitialization - Try to initialize the object
4838/// parameter of the given member function (@c Method) from the
4839/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004840static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004841TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004842 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004843 CXXMethodDecl *Method,
4844 CXXRecordDecl *ActingContext) {
4845 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004846 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4847 // const volatile object.
4848 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4849 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004850 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004851
4852 // Set up the conversion sequence as a "bad" conversion, to allow us
4853 // to exit early.
4854 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004855
4856 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004857 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004858 FromType = PT->getPointeeType();
4859
Douglas Gregor02824322011-01-26 19:30:28 +00004860 // When we had a pointer, it's implicitly dereferenced, so we
4861 // better have an lvalue.
4862 assert(FromClassification.isLValue());
4863 }
4864
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004865 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004866
Douglas Gregor02824322011-01-26 19:30:28 +00004867 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004869 // parameter is
4870 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004871 // - "lvalue reference to cv X" for functions declared without a
4872 // ref-qualifier or with the & ref-qualifier
4873 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004874 // ref-qualifier
4875 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004877 // cv-qualification on the member function declaration.
4878 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004880 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004881 // (C++ [over.match.funcs]p5). We perform a simplified version of
4882 // reference binding here, that allows class rvalues to bind to
4883 // non-constant references.
4884
Douglas Gregor02824322011-01-26 19:30:28 +00004885 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004886 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004888 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004889 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004890 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004891 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004892 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004893 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004894
4895 // Check that we have either the same type or a derived type. It
4896 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004897 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004898 ImplicitConversionKind SecondKind;
4899 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4900 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004901 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004902 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004903 else {
John McCall65eb8792010-02-25 01:37:24 +00004904 ICS.setBad(BadConversionSequence::unrelated_class,
4905 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004906 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004907 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004908
Douglas Gregor02824322011-01-26 19:30:28 +00004909 // Check the ref-qualifier.
4910 switch (Method->getRefQualifier()) {
4911 case RQ_None:
4912 // Do nothing; we don't care about lvalueness or rvalueness.
4913 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
Douglas Gregor02824322011-01-26 19:30:28 +00004915 case RQ_LValue:
4916 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4917 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004919 ImplicitParamType);
4920 return ICS;
4921 }
4922 break;
4923
4924 case RQ_RValue:
4925 if (!FromClassification.isRValue()) {
4926 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004928 ImplicitParamType);
4929 return ICS;
4930 }
4931 break;
4932 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933
Douglas Gregor436424c2008-11-18 23:14:02 +00004934 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004935 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004936 ICS.Standard.setAsIdentityConversion();
4937 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004938 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004939 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004940 ICS.Standard.ReferenceBinding = true;
4941 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004943 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004944 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4945 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4946 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004947 return ICS;
4948}
4949
4950/// PerformObjectArgumentInitialization - Perform initialization of
4951/// the implicit object parameter for the given Method with the given
4952/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004953ExprResult
4954Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004956 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004957 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004958 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004959 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004960 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004961
Douglas Gregor02824322011-01-26 19:30:28 +00004962 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004963 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004964 FromRecordType = PT->getPointeeType();
4965 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004966 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004967 } else {
4968 FromRecordType = From->getType();
4969 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004970 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004971 }
4972
John McCall6e9f8f62009-12-03 04:06:58 +00004973 // Note that we always use the true parent context when performing
4974 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004975 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004976 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4977 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004978 if (ICS.isBad()) {
4979 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4980 Qualifiers FromQs = FromRecordType.getQualifiers();
4981 Qualifiers ToQs = DestType.getQualifiers();
4982 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4983 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004984 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004985 diag::err_member_function_call_bad_cvr)
4986 << Method->getDeclName() << FromRecordType << (CVR - 1)
4987 << From->getSourceRange();
4988 Diag(Method->getLocation(), diag::note_previous_decl)
4989 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004990 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004991 }
4992 }
4993
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004994 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004995 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004996 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004997 }
Mike Stump11289f42009-09-09 15:08:12 +00004998
John Wiegley01296292011-04-08 18:41:53 +00004999 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5000 ExprResult FromRes =
5001 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5002 if (FromRes.isInvalid())
5003 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005004 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005005 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005006
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005007 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005008 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005009 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005010 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005011}
5012
Douglas Gregor5fb53972009-01-14 15:45:31 +00005013/// TryContextuallyConvertToBool - Attempt to contextually convert the
5014/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005015static ImplicitConversionSequence
5016TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005017 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005018 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005019 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005020 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005021 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005022 /*AllowObjCWritebackConversion=*/false,
5023 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005024}
5025
5026/// PerformContextuallyConvertToBool - Perform a contextual conversion
5027/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005028ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005029 if (checkPlaceholderForOverload(*this, From))
5030 return ExprError();
5031
John McCall5c32be02010-08-24 20:38:10 +00005032 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005033 if (!ICS.isBad())
5034 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Fariborz Jahanian76197412009-11-18 18:26:29 +00005036 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005037 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005038 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005039 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005040 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005041}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042
Richard Smithf8379a02012-01-18 23:55:52 +00005043/// Check that the specified conversion is permitted in a converted constant
5044/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5045/// is acceptable.
5046static bool CheckConvertedConstantConversions(Sema &S,
5047 StandardConversionSequence &SCS) {
5048 // Since we know that the target type is an integral or unscoped enumeration
5049 // type, most conversion kinds are impossible. All possible First and Third
5050 // conversions are fine.
5051 switch (SCS.Second) {
5052 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005053 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005054 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005055 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005056 return true;
5057
5058 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005059 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005060 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5061 // conversion, so we allow it in a converted constant expression.
5062 //
5063 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5064 // a lot of popular code. We should at least add a warning for this
5065 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005066 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5067 SCS.getToType(2)->isBooleanType();
5068
Richard Smith410cc892014-11-26 03:26:53 +00005069 case ICK_Pointer_Conversion:
5070 case ICK_Pointer_Member:
5071 // C++1z: null pointer conversions and null member pointer conversions are
5072 // only permitted if the source type is std::nullptr_t.
5073 return SCS.getFromType()->isNullPtrType();
5074
5075 case ICK_Floating_Promotion:
5076 case ICK_Complex_Promotion:
5077 case ICK_Floating_Conversion:
5078 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005079 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005080 case ICK_Compatible_Conversion:
5081 case ICK_Derived_To_Base:
5082 case ICK_Vector_Conversion:
5083 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005084 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005085 case ICK_Block_Pointer_Conversion:
5086 case ICK_TransparentUnionConversion:
5087 case ICK_Writeback_Conversion:
5088 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005089 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005090 return false;
5091
5092 case ICK_Lvalue_To_Rvalue:
5093 case ICK_Array_To_Pointer:
5094 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005095 llvm_unreachable("found a first conversion kind in Second");
5096
Richard Smithf8379a02012-01-18 23:55:52 +00005097 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005098 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005099
5100 case ICK_Num_Conversion_Kinds:
5101 break;
5102 }
5103
5104 llvm_unreachable("unknown conversion kind");
5105}
5106
5107/// CheckConvertedConstantExpression - Check that the expression From is a
5108/// converted constant expression of type T, perform the conversion and produce
5109/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005110static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5111 QualType T, APValue &Value,
5112 Sema::CCEKind CCE,
5113 bool RequireInt) {
5114 assert(S.getLangOpts().CPlusPlus11 &&
5115 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005116
Richard Smith410cc892014-11-26 03:26:53 +00005117 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005118 return ExprError();
5119
Richard Smith410cc892014-11-26 03:26:53 +00005120 // C++1z [expr.const]p3:
5121 // A converted constant expression of type T is an expression,
5122 // implicitly converted to type T, where the converted
5123 // expression is a constant expression and the implicit conversion
5124 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005125 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005126 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005127 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005128 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005129 /*AllowObjcWritebackConversion=*/false,
5130 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005131 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005132 switch (ICS.getKind()) {
5133 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005134 SCS = &ICS.Standard;
5135 break;
5136 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005137 // We are converting to a non-class type, so the Before sequence
5138 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005139 SCS = &ICS.UserDefined.After;
5140 break;
5141 case ImplicitConversionSequence::AmbiguousConversion:
5142 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005143 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5144 return S.Diag(From->getLocStart(),
5145 diag::err_typecheck_converted_constant_expression)
5146 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005147 return ExprError();
5148
5149 case ImplicitConversionSequence::EllipsisConversion:
5150 llvm_unreachable("ellipsis conversion in converted constant expression");
5151 }
5152
Richard Smith410cc892014-11-26 03:26:53 +00005153 // Check that we would only use permitted conversions.
5154 if (!CheckConvertedConstantConversions(S, *SCS)) {
5155 return S.Diag(From->getLocStart(),
5156 diag::err_typecheck_converted_constant_expression_disallowed)
5157 << From->getType() << From->getSourceRange() << T;
5158 }
5159 // [...] and where the reference binding (if any) binds directly.
5160 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5161 return S.Diag(From->getLocStart(),
5162 diag::err_typecheck_converted_constant_expression_indirect)
5163 << From->getType() << From->getSourceRange() << T;
5164 }
5165
5166 ExprResult Result =
5167 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005168 if (Result.isInvalid())
5169 return Result;
5170
5171 // Check for a narrowing implicit conversion.
5172 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005173 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005174 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005175 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005176 case NK_Variable_Narrowing:
5177 // Implicit conversion to a narrower type, and the value is not a constant
5178 // expression. We'll diagnose this in a moment.
5179 case NK_Not_Narrowing:
5180 break;
5181
5182 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005183 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005184 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005185 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005186 break;
5187
5188 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005189 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005190 << CCE << /*Constant*/0 << From->getType() << T;
5191 break;
5192 }
5193
5194 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005195 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005196 Expr::EvalResult Eval;
5197 Eval.Diag = &Notes;
5198
Richard Smith410cc892014-11-26 03:26:53 +00005199 if ((T->isReferenceType()
5200 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5201 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5202 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005203 // The expression can't be folded, so we can't keep it at this position in
5204 // the AST.
5205 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005206 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005207 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005208
5209 if (Notes.empty()) {
5210 // It's a constant expression.
5211 return Result;
5212 }
Richard Smithf8379a02012-01-18 23:55:52 +00005213 }
5214
5215 // It's not a constant expression. Produce an appropriate diagnostic.
5216 if (Notes.size() == 1 &&
5217 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005218 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005219 else {
Richard Smith410cc892014-11-26 03:26:53 +00005220 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005221 << CCE << From->getSourceRange();
5222 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005223 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005224 }
Richard Smith410cc892014-11-26 03:26:53 +00005225 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005226}
5227
Richard Smith410cc892014-11-26 03:26:53 +00005228ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5229 APValue &Value, CCEKind CCE) {
5230 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5231}
5232
5233ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5234 llvm::APSInt &Value,
5235 CCEKind CCE) {
5236 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5237
5238 APValue V;
5239 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5240 if (!R.isInvalid())
5241 Value = V.getInt();
5242 return R;
5243}
5244
5245
John McCallfec112d2011-09-09 06:11:02 +00005246/// dropPointerConversions - If the given standard conversion sequence
5247/// involves any pointer conversions, remove them. This may change
5248/// the result type of the conversion sequence.
5249static void dropPointerConversion(StandardConversionSequence &SCS) {
5250 if (SCS.Second == ICK_Pointer_Conversion) {
5251 SCS.Second = ICK_Identity;
5252 SCS.Third = ICK_Identity;
5253 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5254 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005255}
John McCall5c32be02010-08-24 20:38:10 +00005256
John McCallfec112d2011-09-09 06:11:02 +00005257/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5258/// convert the expression From to an Objective-C pointer type.
5259static ImplicitConversionSequence
5260TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5261 // Do an implicit conversion to 'id'.
5262 QualType Ty = S.Context.getObjCIdType();
5263 ImplicitConversionSequence ICS
5264 = TryImplicitConversion(S, From, Ty,
5265 // FIXME: Are these flags correct?
5266 /*SuppressUserConversions=*/false,
5267 /*AllowExplicit=*/true,
5268 /*InOverloadResolution=*/false,
5269 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005270 /*AllowObjCWritebackConversion=*/false,
5271 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005272
5273 // Strip off any final conversions to 'id'.
5274 switch (ICS.getKind()) {
5275 case ImplicitConversionSequence::BadConversion:
5276 case ImplicitConversionSequence::AmbiguousConversion:
5277 case ImplicitConversionSequence::EllipsisConversion:
5278 break;
5279
5280 case ImplicitConversionSequence::UserDefinedConversion:
5281 dropPointerConversion(ICS.UserDefined.After);
5282 break;
5283
5284 case ImplicitConversionSequence::StandardConversion:
5285 dropPointerConversion(ICS.Standard);
5286 break;
5287 }
5288
5289 return ICS;
5290}
5291
5292/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5293/// conversion of the expression From to an Objective-C pointer type.
5294ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005295 if (checkPlaceholderForOverload(*this, From))
5296 return ExprError();
5297
John McCall8b07ec22010-05-15 11:32:37 +00005298 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005299 ImplicitConversionSequence ICS =
5300 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005301 if (!ICS.isBad())
5302 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005303 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005304}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005305
Richard Smith8dd34252012-02-04 07:07:42 +00005306/// Determine whether the provided type is an integral type, or an enumeration
5307/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005308bool Sema::ICEConvertDiagnoser::match(QualType T) {
5309 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5310 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005311}
5312
Larisse Voufo236bec22013-06-10 06:50:24 +00005313static ExprResult
5314diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5315 Sema::ContextualImplicitConverter &Converter,
5316 QualType T, UnresolvedSetImpl &ViableConversions) {
5317
5318 if (Converter.Suppress)
5319 return ExprError();
5320
5321 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5322 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5323 CXXConversionDecl *Conv =
5324 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5325 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5326 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5327 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005328 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005329}
5330
5331static bool
5332diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5333 Sema::ContextualImplicitConverter &Converter,
5334 QualType T, bool HadMultipleCandidates,
5335 UnresolvedSetImpl &ExplicitConversions) {
5336 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5337 DeclAccessPair Found = ExplicitConversions[0];
5338 CXXConversionDecl *Conversion =
5339 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5340
5341 // The user probably meant to invoke the given explicit
5342 // conversion; use it.
5343 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5344 std::string TypeStr;
5345 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5346
5347 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5348 << FixItHint::CreateInsertion(From->getLocStart(),
5349 "static_cast<" + TypeStr + ">(")
5350 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005351 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005352 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5353
5354 // If we aren't in a SFINAE context, build a call to the
5355 // explicit conversion function.
5356 if (SemaRef.isSFINAEContext())
5357 return true;
5358
Craig Topperc3ec1492014-05-26 06:22:03 +00005359 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005360 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5361 HadMultipleCandidates);
5362 if (Result.isInvalid())
5363 return true;
5364 // Record usage of conversion in an implicit cast.
5365 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005366 CK_UserDefinedConversion, Result.get(),
5367 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005368 }
5369 return false;
5370}
5371
5372static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5373 Sema::ContextualImplicitConverter &Converter,
5374 QualType T, bool HadMultipleCandidates,
5375 DeclAccessPair &Found) {
5376 CXXConversionDecl *Conversion =
5377 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005378 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005379
5380 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5381 if (!Converter.SuppressConversion) {
5382 if (SemaRef.isSFINAEContext())
5383 return true;
5384
5385 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5386 << From->getSourceRange();
5387 }
5388
5389 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5390 HadMultipleCandidates);
5391 if (Result.isInvalid())
5392 return true;
5393 // Record usage of conversion in an implicit cast.
5394 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005395 CK_UserDefinedConversion, Result.get(),
5396 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005397 return false;
5398}
5399
5400static ExprResult finishContextualImplicitConversion(
5401 Sema &SemaRef, SourceLocation Loc, Expr *From,
5402 Sema::ContextualImplicitConverter &Converter) {
5403 if (!Converter.match(From->getType()) && !Converter.Suppress)
5404 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5405 << From->getSourceRange();
5406
5407 return SemaRef.DefaultLvalueConversion(From);
5408}
5409
5410static void
5411collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5412 UnresolvedSetImpl &ViableConversions,
5413 OverloadCandidateSet &CandidateSet) {
5414 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5415 DeclAccessPair FoundDecl = ViableConversions[I];
5416 NamedDecl *D = FoundDecl.getDecl();
5417 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5418 if (isa<UsingShadowDecl>(D))
5419 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5420
5421 CXXConversionDecl *Conv;
5422 FunctionTemplateDecl *ConvTemplate;
5423 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5424 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5425 else
5426 Conv = cast<CXXConversionDecl>(D);
5427
5428 if (ConvTemplate)
5429 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005430 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5431 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005432 else
5433 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005434 ToType, CandidateSet,
5435 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005436 }
5437}
5438
Richard Smithccc11812013-05-21 19:05:48 +00005439/// \brief Attempt to convert the given expression to a type which is accepted
5440/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005441///
Richard Smithccc11812013-05-21 19:05:48 +00005442/// This routine will attempt to convert an expression of class type to a
5443/// type accepted by the specified converter. In C++11 and before, the class
5444/// must have a single non-explicit conversion function converting to a matching
5445/// type. In C++1y, there can be multiple such conversion functions, but only
5446/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005447///
Douglas Gregor4799d032010-06-30 00:20:43 +00005448/// \param Loc The source location of the construct that requires the
5449/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005450///
James Dennett18348b62012-06-22 08:52:37 +00005451/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005452///
Richard Smithccc11812013-05-21 19:05:48 +00005453/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005454///
Douglas Gregor4799d032010-06-30 00:20:43 +00005455/// \returns The expression, converted to an integral or enumeration type if
5456/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005457ExprResult Sema::PerformContextualImplicitConversion(
5458 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005459 // We can't perform any more checking for type-dependent expressions.
5460 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005461 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Eli Friedman1da70392012-01-26 00:26:18 +00005463 // Process placeholders immediately.
5464 if (From->hasPlaceholderType()) {
5465 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005466 if (result.isInvalid())
5467 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005468 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005469 }
5470
Richard Smithccc11812013-05-21 19:05:48 +00005471 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005472 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005473 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005474 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005475
5476 // FIXME: Check for missing '()' if T is a function type?
5477
Richard Smithccc11812013-05-21 19:05:48 +00005478 // We can only perform contextual implicit conversions on objects of class
5479 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005480 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005481 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005482 if (!Converter.Suppress)
5483 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005484 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005487 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005488 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005489 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005490 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005491
5492 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005493 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005494
Craig Toppere14c0f82014-03-12 04:55:44 +00005495 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005496 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005497 }
Richard Smithccc11812013-05-21 19:05:48 +00005498 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005499
Richard Smithdb0ac552015-12-18 22:40:25 +00005500 if (Converter.Suppress ? !isCompleteType(Loc, T)
5501 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005502 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005504 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005505 UnresolvedSet<4>
5506 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005507 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005508 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005509 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Larisse Voufo236bec22013-06-10 06:50:24 +00005511 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005512 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005513
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 // To check that there is only one target type, in C++1y:
5515 QualType ToType;
5516 bool HasUniqueTargetType = true;
5517
5518 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005519 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005520 NamedDecl *D = (*I)->getUnderlyingDecl();
5521 CXXConversionDecl *Conversion;
5522 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5523 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005524 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005525 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5526 else
5527 continue; // C++11 does not consider conversion operator templates(?).
5528 } else
5529 Conversion = cast<CXXConversionDecl>(D);
5530
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005531 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005532 "Conversion operator templates are considered potentially "
5533 "viable in C++1y");
5534
5535 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5536 if (Converter.match(CurToType) || ConvTemplate) {
5537
5538 if (Conversion->isExplicit()) {
5539 // FIXME: For C++1y, do we need this restriction?
5540 // cf. diagnoseNoViableConversion()
5541 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005542 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005543 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005544 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005545 if (ToType.isNull())
5546 ToType = CurToType.getUnqualifiedType();
5547 else if (HasUniqueTargetType &&
5548 (CurToType.getUnqualifiedType() != ToType))
5549 HasUniqueTargetType = false;
5550 }
5551 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005552 }
Richard Smith8dd34252012-02-04 07:07:42 +00005553 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005556 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005557 // C++1y [conv]p6:
5558 // ... An expression e of class type E appearing in such a context
5559 // is said to be contextually implicitly converted to a specified
5560 // type T and is well-formed if and only if e can be implicitly
5561 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005562 // for conversion functions whose return type is cv T or reference to
5563 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005564 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005565
Larisse Voufo236bec22013-06-10 06:50:24 +00005566 // If no unique T is found:
5567 if (ToType.isNull()) {
5568 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5569 HadMultipleCandidates,
5570 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005571 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005574
Larisse Voufo236bec22013-06-10 06:50:24 +00005575 // If more than one unique Ts are found:
5576 if (!HasUniqueTargetType)
5577 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5578 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Larisse Voufo236bec22013-06-10 06:50:24 +00005580 // If one unique T is found:
5581 // First, build a candidate set from the previously recorded
5582 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005583 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005584 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5585 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005586
Larisse Voufo236bec22013-06-10 06:50:24 +00005587 // Then, perform overload resolution over the candidate set.
5588 OverloadCandidateSet::iterator Best;
5589 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5590 case OR_Success: {
5591 // Apply this conversion.
5592 DeclAccessPair Found =
5593 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5594 if (recordConversion(*this, Loc, From, Converter, T,
5595 HadMultipleCandidates, Found))
5596 return ExprError();
5597 break;
5598 }
5599 case OR_Ambiguous:
5600 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5601 ViableConversions);
5602 case OR_No_Viable_Function:
5603 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5604 HadMultipleCandidates,
5605 ExplicitConversions))
5606 return ExprError();
5607 // fall through 'OR_Deleted' case.
5608 case OR_Deleted:
5609 // We'll complain below about a non-integral condition type.
5610 break;
5611 }
5612 } else {
5613 switch (ViableConversions.size()) {
5614 case 0: {
5615 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5616 HadMultipleCandidates,
5617 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005618 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005619
Larisse Voufo236bec22013-06-10 06:50:24 +00005620 // We'll complain below about a non-integral condition type.
5621 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005622 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005623 case 1: {
5624 // Apply this conversion.
5625 DeclAccessPair Found = ViableConversions[0];
5626 if (recordConversion(*this, Loc, From, Converter, T,
5627 HadMultipleCandidates, Found))
5628 return ExprError();
5629 break;
5630 }
5631 default:
5632 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5633 ViableConversions);
5634 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636
Larisse Voufo236bec22013-06-10 06:50:24 +00005637 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005638}
5639
Richard Smith100b24a2014-04-17 01:52:14 +00005640/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5641/// an acceptable non-member overloaded operator for a call whose
5642/// arguments have types T1 (and, if non-empty, T2). This routine
5643/// implements the check in C++ [over.match.oper]p3b2 concerning
5644/// enumeration types.
5645static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5646 FunctionDecl *Fn,
5647 ArrayRef<Expr *> Args) {
5648 QualType T1 = Args[0]->getType();
5649 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5650
5651 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5652 return true;
5653
5654 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5655 return true;
5656
5657 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5658 if (Proto->getNumParams() < 1)
5659 return false;
5660
5661 if (T1->isEnumeralType()) {
5662 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5663 if (Context.hasSameUnqualifiedType(T1, ArgType))
5664 return true;
5665 }
5666
5667 if (Proto->getNumParams() < 2)
5668 return false;
5669
5670 if (!T2.isNull() && T2->isEnumeralType()) {
5671 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5672 if (Context.hasSameUnqualifiedType(T2, ArgType))
5673 return true;
5674 }
5675
5676 return false;
5677}
5678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005679/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005680/// candidate functions, using the given function call arguments. If
5681/// @p SuppressUserConversions, then don't allow user-defined
5682/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005683///
James Dennett2a4d13c2012-06-15 07:13:21 +00005684/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005685/// based on an incomplete set of function arguments. This feature is used by
5686/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005687void
5688Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005689 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005690 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005691 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005692 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005693 bool PartialOverloading,
5694 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005695 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005696 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005697 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005698 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005699 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005700
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005702 if (!isa<CXXConstructorDecl>(Method)) {
5703 // If we get here, it's because we're calling a member function
5704 // that is named without a member access expression (e.g.,
5705 // "this->f") that was either written explicitly or created
5706 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005707 // function, e.g., X::f(). We use an empty type for the implied
5708 // object argument (C++ [over.call.func]p3), and the acting context
5709 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005710 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005712 Args, CandidateSet, SuppressUserConversions,
5713 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005714 return;
5715 }
5716 // We treat a constructor like a non-member function, since its object
5717 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005718 }
5719
Douglas Gregorff7028a2009-11-13 23:59:09 +00005720 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005721 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005722
Richard Smith100b24a2014-04-17 01:52:14 +00005723 // C++ [over.match.oper]p3:
5724 // if no operand has a class type, only those non-member functions in the
5725 // lookup set that have a first parameter of type T1 or "reference to
5726 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5727 // is a right operand) a second parameter of type T2 or "reference to
5728 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5729 // candidate functions.
5730 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5731 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5732 return;
5733
Richard Smith8b86f2d2013-11-04 01:48:18 +00005734 // C++11 [class.copy]p11: [DR1402]
5735 // A defaulted move constructor that is defined as deleted is ignored by
5736 // overload resolution.
5737 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5738 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5739 Constructor->isMoveConstructor())
5740 return;
5741
Douglas Gregor27381f32009-11-23 12:27:39 +00005742 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005743 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005744
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005745 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005746 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005747 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005748 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005749 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005750 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005751 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005752 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
John McCall578a1f82014-12-14 01:46:53 +00005754 if (Constructor) {
5755 // C++ [class.copy]p3:
5756 // A member function template is never instantiated to perform the copy
5757 // of a class object to an object of its class type.
5758 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005759 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005760 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005761 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5762 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005763 Candidate.Viable = false;
5764 Candidate.FailureKind = ovl_fail_illegal_constructor;
5765 return;
5766 }
5767 }
5768
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005769 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005770
5771 // (C++ 13.3.2p2): A candidate function having fewer than m
5772 // parameters is viable only if it has an ellipsis in its parameter
5773 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005774 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005775 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005776 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005777 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005778 return;
5779 }
5780
5781 // (C++ 13.3.2p2): A candidate function having more than m parameters
5782 // is viable only if the (m+1)st parameter has a default argument
5783 // (8.3.6). For the purposes of overload resolution, the
5784 // parameter list is truncated on the right, so that there are
5785 // exactly m parameters.
5786 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005787 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005788 // Not enough arguments.
5789 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005790 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005791 return;
5792 }
5793
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005794 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005795 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005796 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005797 // Skip the check for callers that are implicit members, because in this
5798 // case we may not yet know what the member's target is; the target is
5799 // inferred for the member automatically, based on the bases and fields of
5800 // the class.
5801 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005802 Candidate.Viable = false;
5803 Candidate.FailureKind = ovl_fail_bad_target;
5804 return;
5805 }
5806
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005807 // Determine the implicit conversion sequences for each of the
5808 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005809 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005810 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005811 // (C++ 13.3.2p3): for F to be a viable function, there shall
5812 // exist for each argument an implicit conversion sequence
5813 // (13.3.3.1) that converts that argument to the corresponding
5814 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005815 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005816 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005817 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005819 /*InOverloadResolution=*/true,
5820 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005821 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005822 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005823 if (Candidate.Conversions[ArgIdx].isBad()) {
5824 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005825 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005826 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005827 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005828 } else {
5829 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5830 // argument for which there is no corresponding parameter is
5831 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005832 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005833 }
5834 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005835
5836 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5837 Candidate.Viable = false;
5838 Candidate.FailureKind = ovl_fail_enable_if;
5839 Candidate.DeductionFailure.Data = FailedAttr;
5840 return;
5841 }
5842}
5843
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005844ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005845 bool IsInstance) {
5846 SmallVector<ObjCMethodDecl*, 4> Methods;
5847 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5848 return nullptr;
5849
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005850 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5851 bool Match = true;
5852 ObjCMethodDecl *Method = Methods[b];
5853 unsigned NumNamedArgs = Sel.getNumArgs();
5854 // Method might have more arguments than selector indicates. This is due
5855 // to addition of c-style arguments in method.
5856 if (Method->param_size() > NumNamedArgs)
5857 NumNamedArgs = Method->param_size();
5858 if (Args.size() < NumNamedArgs)
5859 continue;
5860
5861 for (unsigned i = 0; i < NumNamedArgs; i++) {
5862 // We can't do any type-checking on a type-dependent argument.
5863 if (Args[i]->isTypeDependent()) {
5864 Match = false;
5865 break;
5866 }
5867
5868 ParmVarDecl *param = Method->parameters()[i];
5869 Expr *argExpr = Args[i];
5870 assert(argExpr && "SelectBestMethod(): missing expression");
5871
5872 // Strip the unbridged-cast placeholder expression off unless it's
5873 // a consumed argument.
5874 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5875 !param->hasAttr<CFConsumedAttr>())
5876 argExpr = stripARCUnbridgedCast(argExpr);
5877
5878 // If the parameter is __unknown_anytype, move on to the next method.
5879 if (param->getType() == Context.UnknownAnyTy) {
5880 Match = false;
5881 break;
5882 }
George Burgess IV45461812015-10-11 20:13:20 +00005883
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005884 ImplicitConversionSequence ConversionState
5885 = TryCopyInitialization(*this, argExpr, param->getType(),
5886 /*SuppressUserConversions*/false,
5887 /*InOverloadResolution=*/true,
5888 /*AllowObjCWritebackConversion=*/
5889 getLangOpts().ObjCAutoRefCount,
5890 /*AllowExplicit*/false);
5891 if (ConversionState.isBad()) {
5892 Match = false;
5893 break;
5894 }
5895 }
5896 // Promote additional arguments to variadic methods.
5897 if (Match && Method->isVariadic()) {
5898 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5899 if (Args[i]->isTypeDependent()) {
5900 Match = false;
5901 break;
5902 }
5903 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5904 nullptr);
5905 if (Arg.isInvalid()) {
5906 Match = false;
5907 break;
5908 }
5909 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005910 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005911 // Check for extra arguments to non-variadic methods.
5912 if (Args.size() != NumNamedArgs)
5913 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005914 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5915 // Special case when selectors have no argument. In this case, select
5916 // one with the most general result type of 'id'.
5917 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5918 QualType ReturnT = Methods[b]->getReturnType();
5919 if (ReturnT->isObjCIdType())
5920 return Methods[b];
5921 }
5922 }
5923 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005924
5925 if (Match)
5926 return Method;
5927 }
5928 return nullptr;
5929}
5930
George Burgess IV2a6150d2015-10-16 01:17:38 +00005931// specific_attr_iterator iterates over enable_if attributes in reverse, and
5932// enable_if is order-sensitive. As a result, we need to reverse things
5933// sometimes. Size of 4 elements is arbitrary.
5934static SmallVector<EnableIfAttr *, 4>
5935getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5936 SmallVector<EnableIfAttr *, 4> Result;
5937 if (!Function->hasAttrs())
5938 return Result;
5939
5940 const auto &FuncAttrs = Function->getAttrs();
5941 for (Attr *Attr : FuncAttrs)
5942 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5943 Result.push_back(EnableIf);
5944
5945 std::reverse(Result.begin(), Result.end());
5946 return Result;
5947}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005948
5949EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5950 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005951 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5952 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005953 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005954
5955 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005956 SmallVector<Expr *, 16> ConvertedArgs;
5957 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005958 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005959
5960 // Convert the arguments.
George Burgess IVe96abf72016-02-24 22:31:14 +00005961 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5962 ExprResult R;
5963 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005964 !cast<CXXMethodDecl>(Function)->isStatic() &&
5965 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005966 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00005967 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5968 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005969 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00005970 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5971 Context, Function->getParamDecl(I)),
5972 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005973 }
George Burgess IVe96abf72016-02-24 22:31:14 +00005974
5975 if (R.isInvalid()) {
5976 InitializationFailed = true;
5977 break;
5978 }
5979
5980 ContainsValueDependentExpr |= R.get()->isValueDependent();
5981 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005982 }
5983
5984 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005985 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005986
Nick Lewyckye283c552015-08-25 22:33:16 +00005987 // Push default arguments if needed.
5988 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5989 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5990 ParmVarDecl *P = Function->getParamDecl(i);
5991 ExprResult R = PerformCopyInitialization(
5992 InitializedEntity::InitializeParameter(Context,
5993 Function->getParamDecl(i)),
5994 SourceLocation(),
5995 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5996 : P->getDefaultArg());
5997 if (R.isInvalid()) {
5998 InitializationFailed = true;
5999 break;
6000 }
6001 ContainsValueDependentExpr |= R.get()->isValueDependent();
6002 ConvertedArgs.push_back(R.get());
6003 }
6004
6005 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006006 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006007 }
6008
George Burgess IV2a6150d2015-10-16 01:17:38 +00006009 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006010 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006011 if (EIA->getCond()->isValueDependent()) {
6012 // Don't even try now, we'll examine it after instantiation.
6013 continue;
6014 }
6015
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006016 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006017 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6018 if (!ContainsValueDependentExpr)
6019 return EIA;
6020 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006021 return EIA;
6022 }
6023 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006024 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006025}
6026
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006027/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006028/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006029void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006030 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006031 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006032 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006033 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006034 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006035 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006036 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006038 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006039 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006040 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006041 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006042 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006043 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006044 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006045 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006046 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006047 } else {
John McCalla0296f72010-03-19 07:35:19 +00006048 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006049 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6050 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006051 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006052 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006053 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006054 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006055 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006056 CandidateSet, SuppressUserConversions,
6057 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006058 else
John McCalla0296f72010-03-19 07:35:19 +00006059 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006060 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006061 CandidateSet, SuppressUserConversions,
6062 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006063 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006064 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006065}
6066
John McCallf0f1cf02009-11-17 07:50:12 +00006067/// AddMethodCandidate - Adds a named decl (which is some kind of
6068/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006069void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006070 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006071 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006072 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006073 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006074 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006075 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006077
6078 if (isa<UsingShadowDecl>(Decl))
6079 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080
John McCallf0f1cf02009-11-17 07:50:12 +00006081 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6082 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6083 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006084 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006085 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006086 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006087 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006088 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006089 } else {
John McCalla0296f72010-03-19 07:35:19 +00006090 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006091 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006092 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006093 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006094 }
6095}
6096
Douglas Gregor436424c2008-11-18 23:14:02 +00006097/// AddMethodCandidate - Adds the given C++ member function to the set
6098/// of candidate functions, using the given function call arguments
6099/// and the object argument (@c Object). For example, in a call
6100/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6101/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6102/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006103/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006104void
John McCalla0296f72010-03-19 07:35:19 +00006105Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006106 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006107 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006108 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006109 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006110 bool SuppressUserConversions,
6111 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006112 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006113 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006114 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006115 assert(!isa<CXXConstructorDecl>(Method) &&
6116 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006117
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006118 if (!CandidateSet.isNewCandidate(Method))
6119 return;
6120
Richard Smith8b86f2d2013-11-04 01:48:18 +00006121 // C++11 [class.copy]p23: [DR1402]
6122 // A defaulted move assignment operator that is defined as deleted is
6123 // ignored by overload resolution.
6124 if (Method->isDefaulted() && Method->isDeleted() &&
6125 Method->isMoveAssignmentOperator())
6126 return;
6127
Douglas Gregor27381f32009-11-23 12:27:39 +00006128 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006129 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006130
Douglas Gregor436424c2008-11-18 23:14:02 +00006131 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006132 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006133 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006134 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006135 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006136 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006137 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006138
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006139 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006140
6141 // (C++ 13.3.2p2): A candidate function having fewer than m
6142 // parameters is viable only if it has an ellipsis in its parameter
6143 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006144 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6145 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006146 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006147 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006148 return;
6149 }
6150
6151 // (C++ 13.3.2p2): A candidate function having more than m parameters
6152 // is viable only if the (m+1)st parameter has a default argument
6153 // (8.3.6). For the purposes of overload resolution, the
6154 // parameter list is truncated on the right, so that there are
6155 // exactly m parameters.
6156 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006157 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006158 // Not enough arguments.
6159 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006160 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006161 return;
6162 }
6163
6164 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006165
John McCall6e9f8f62009-12-03 04:06:58 +00006166 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006167 // The implicit object argument is ignored.
6168 Candidate.IgnoreObjectArgument = true;
6169 else {
6170 // Determine the implicit conversion sequence for the object
6171 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006172 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6173 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6174 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006175 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006176 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006177 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006178 return;
6179 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006180 }
6181
Eli Bendersky291a57e2014-09-25 23:59:08 +00006182 // (CUDA B.1): Check for invalid calls between targets.
6183 if (getLangOpts().CUDA)
6184 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6185 if (CheckCUDATarget(Caller, Method)) {
6186 Candidate.Viable = false;
6187 Candidate.FailureKind = ovl_fail_bad_target;
6188 return;
6189 }
6190
Douglas Gregor436424c2008-11-18 23:14:02 +00006191 // Determine the implicit conversion sequences for each of the
6192 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006193 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006194 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006195 // (C++ 13.3.2p3): for F to be a viable function, there shall
6196 // exist for each argument an implicit conversion sequence
6197 // (13.3.3.1) that converts that argument to the corresponding
6198 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006199 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006200 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006201 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006203 /*InOverloadResolution=*/true,
6204 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006205 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006206 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006207 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006208 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006209 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006210 }
6211 } else {
6212 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6213 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006214 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006215 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006216 }
6217 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006218
6219 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6220 Candidate.Viable = false;
6221 Candidate.FailureKind = ovl_fail_enable_if;
6222 Candidate.DeductionFailure.Data = FailedAttr;
6223 return;
6224 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006225}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226
Douglas Gregor97628d62009-08-21 00:16:32 +00006227/// \brief Add a C++ member function template as a candidate to the candidate
6228/// set, using template argument deduction to produce an appropriate member
6229/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006230void
Douglas Gregor97628d62009-08-21 00:16:32 +00006231Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006232 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006233 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006234 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006235 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006236 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006237 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006238 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006239 bool SuppressUserConversions,
6240 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006241 if (!CandidateSet.isNewCandidate(MethodTmpl))
6242 return;
6243
Douglas Gregor97628d62009-08-21 00:16:32 +00006244 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006245 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006246 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006247 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006248 // candidate functions in the usual way.113) A given name can refer to one
6249 // or more function templates and also to a set of overloaded non-template
6250 // functions. In such a case, the candidate functions generated from each
6251 // function template are combined with the set of non-template candidate
6252 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006253 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006254 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006255 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006256 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006257 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006258 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006259 Candidate.FoundDecl = FoundDecl;
6260 Candidate.Function = MethodTmpl->getTemplatedDecl();
6261 Candidate.Viable = false;
6262 Candidate.FailureKind = ovl_fail_bad_deduction;
6263 Candidate.IsSurrogate = false;
6264 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006265 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006267 Info);
6268 return;
6269 }
Mike Stump11289f42009-09-09 15:08:12 +00006270
Douglas Gregor97628d62009-08-21 00:16:32 +00006271 // Add the function template specialization produced by template argument
6272 // deduction as a candidate.
6273 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006274 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006275 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006276 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006277 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006278 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006279}
6280
Douglas Gregor05155d82009-08-21 23:19:43 +00006281/// \brief Add a C++ function template specialization as a candidate
6282/// in the candidate set, using template argument deduction to produce
6283/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006284void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006285Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006286 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006287 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006288 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006289 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006290 bool SuppressUserConversions,
6291 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006292 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6293 return;
6294
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006295 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006296 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006297 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006298 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006299 // candidate functions in the usual way.113) A given name can refer to one
6300 // or more function templates and also to a set of overloaded non-template
6301 // functions. In such a case, the candidate functions generated from each
6302 // function template are combined with the set of non-template candidate
6303 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006304 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006305 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006306 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006307 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006308 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006309 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006310 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006311 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6312 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006313 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006314 Candidate.IsSurrogate = false;
6315 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006316 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006317 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006318 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006319 return;
6320 }
Mike Stump11289f42009-09-09 15:08:12 +00006321
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006322 // Add the function template specialization produced by template argument
6323 // deduction as a candidate.
6324 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006325 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006326 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006327}
Mike Stump11289f42009-09-09 15:08:12 +00006328
Douglas Gregor4b60a152013-11-07 22:34:54 +00006329/// Determine whether this is an allowable conversion from the result
6330/// of an explicit conversion operator to the expected type, per C++
6331/// [over.match.conv]p1 and [over.match.ref]p1.
6332///
6333/// \param ConvType The return type of the conversion function.
6334///
6335/// \param ToType The type we are converting to.
6336///
6337/// \param AllowObjCPointerConversion Allow a conversion from one
6338/// Objective-C pointer to another.
6339///
6340/// \returns true if the conversion is allowable, false otherwise.
6341static bool isAllowableExplicitConversion(Sema &S,
6342 QualType ConvType, QualType ToType,
6343 bool AllowObjCPointerConversion) {
6344 QualType ToNonRefType = ToType.getNonReferenceType();
6345
6346 // Easy case: the types are the same.
6347 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6348 return true;
6349
6350 // Allow qualification conversions.
6351 bool ObjCLifetimeConversion;
6352 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6353 ObjCLifetimeConversion))
6354 return true;
6355
6356 // If we're not allowed to consider Objective-C pointer conversions,
6357 // we're done.
6358 if (!AllowObjCPointerConversion)
6359 return false;
6360
6361 // Is this an Objective-C pointer conversion?
6362 bool IncompatibleObjC = false;
6363 QualType ConvertedType;
6364 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6365 IncompatibleObjC);
6366}
6367
Douglas Gregora1f013e2008-11-07 22:36:19 +00006368/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006369/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006370/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006371/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006372/// (which may or may not be the same type as the type that the
6373/// conversion function produces).
6374void
6375Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006376 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006377 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006378 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006379 OverloadCandidateSet& CandidateSet,
6380 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006381 assert(!Conversion->getDescribedFunctionTemplate() &&
6382 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006383 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006384 if (!CandidateSet.isNewCandidate(Conversion))
6385 return;
6386
Richard Smith2a7d4812013-05-04 07:00:32 +00006387 // If the conversion function has an undeduced return type, trigger its
6388 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006389 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006390 if (DeduceReturnType(Conversion, From->getExprLoc()))
6391 return;
6392 ConvType = Conversion->getConversionType().getNonReferenceType();
6393 }
6394
Richard Smith089c3162013-09-21 21:55:46 +00006395 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6396 // operator is only a candidate if its return type is the target type or
6397 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006398 if (Conversion->isExplicit() &&
6399 !isAllowableExplicitConversion(*this, ConvType, ToType,
6400 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006401 return;
6402
Douglas Gregor27381f32009-11-23 12:27:39 +00006403 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006404 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006405
Douglas Gregora1f013e2008-11-07 22:36:19 +00006406 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006407 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006408 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006409 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006410 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006411 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006412 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006413 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006414 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006415 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006416 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006417
Douglas Gregor6affc782010-08-19 15:37:02 +00006418 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419 // For conversion functions, the function is considered to be a member of
6420 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006421 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006422 //
6423 // Determine the implicit conversion sequence for the implicit
6424 // object parameter.
6425 QualType ImplicitParamType = From->getType();
6426 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6427 ImplicitParamType = FromPtrType->getPointeeType();
6428 CXXRecordDecl *ConversionContext
6429 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430
Richard Smith0f59cb32015-12-18 21:45:41 +00006431 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6432 *this, CandidateSet.getLocation(), From->getType(),
6433 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006434
John McCall0d1da222010-01-12 00:44:57 +00006435 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006436 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006437 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006438 return;
6439 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006440
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006441 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006442 // derived to base as such conversions are given Conversion Rank. They only
6443 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6444 QualType FromCanon
6445 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6446 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006447 if (FromCanon == ToCanon ||
6448 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006449 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006450 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006451 return;
6452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453
Douglas Gregora1f013e2008-11-07 22:36:19 +00006454 // To determine what the conversion from the result of calling the
6455 // conversion function to the type we're eventually trying to
6456 // convert to (ToType), we need to synthesize a call to the
6457 // conversion function and attempt copy initialization from it. This
6458 // makes sure that we get the right semantics with respect to
6459 // lvalues/rvalues and the type. Fortunately, we can allocate this
6460 // call on the stack and we don't need its arguments to be
6461 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006462 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006463 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006464 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6465 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006466 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006467 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006468
Richard Smith48d24642011-07-13 22:53:21 +00006469 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006470 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006471 Candidate.Viable = false;
6472 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6473 return;
6474 }
6475
Richard Smith48d24642011-07-13 22:53:21 +00006476 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006477
Mike Stump11289f42009-09-09 15:08:12 +00006478 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006479 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6480 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006481 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006482 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006483 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006484 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006485 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006486 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006487 /*InOverloadResolution=*/false,
6488 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006489
John McCall0d1da222010-01-12 00:44:57 +00006490 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006491 case ImplicitConversionSequence::StandardConversion:
6492 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006494 // C++ [over.ics.user]p3:
6495 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006497 // shall have exact match rank.
6498 if (Conversion->getPrimaryTemplate() &&
6499 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6500 Candidate.Viable = false;
6501 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006502 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006504
Douglas Gregorcba72b12011-01-21 05:18:22 +00006505 // C++0x [dcl.init.ref]p5:
6506 // In the second case, if the reference is an rvalue reference and
6507 // the second standard conversion sequence of the user-defined
6508 // conversion sequence includes an lvalue-to-rvalue conversion, the
6509 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006510 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006511 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6512 Candidate.Viable = false;
6513 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006514 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006515 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006516 break;
6517
6518 case ImplicitConversionSequence::BadConversion:
6519 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006520 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006521 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006522
6523 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006524 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006525 "Can only end up with a standard conversion sequence or failure");
6526 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006527
Craig Topper5fc8fc22014-08-27 06:28:36 +00006528 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006529 Candidate.Viable = false;
6530 Candidate.FailureKind = ovl_fail_enable_if;
6531 Candidate.DeductionFailure.Data = FailedAttr;
6532 return;
6533 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006534}
6535
Douglas Gregor05155d82009-08-21 23:19:43 +00006536/// \brief Adds a conversion function template specialization
6537/// candidate to the overload set, using template argument deduction
6538/// to deduce the template arguments of the conversion function
6539/// template from the type that we are converting to (C++
6540/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006541void
Douglas Gregor05155d82009-08-21 23:19:43 +00006542Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006543 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006544 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006545 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006546 OverloadCandidateSet &CandidateSet,
6547 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006548 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6549 "Only conversion function templates permitted here");
6550
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006551 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6552 return;
6553
Craig Toppere6706e42012-09-19 02:26:47 +00006554 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006555 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006556 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006557 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006558 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006559 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006560 Candidate.FoundDecl = FoundDecl;
6561 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6562 Candidate.Viable = false;
6563 Candidate.FailureKind = ovl_fail_bad_deduction;
6564 Candidate.IsSurrogate = false;
6565 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006566 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006567 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006568 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006569 return;
6570 }
Mike Stump11289f42009-09-09 15:08:12 +00006571
Douglas Gregor05155d82009-08-21 23:19:43 +00006572 // Add the conversion function template specialization produced by
6573 // template argument deduction as a candidate.
6574 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006575 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006576 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006577}
6578
Douglas Gregorab7897a2008-11-19 22:57:39 +00006579/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6580/// converts the given @c Object to a function pointer via the
6581/// conversion function @c Conversion, and then attempts to call it
6582/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6583/// the type of function that we'll eventually be calling.
6584void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006585 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006586 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006587 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006588 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006589 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006590 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006591 if (!CandidateSet.isNewCandidate(Conversion))
6592 return;
6593
Douglas Gregor27381f32009-11-23 12:27:39 +00006594 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006595 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006596
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006597 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006598 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006599 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006600 Candidate.Surrogate = Conversion;
6601 Candidate.Viable = true;
6602 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006603 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006604 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006605
6606 // Determine the implicit conversion sequence for the implicit
6607 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006608 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6609 *this, CandidateSet.getLocation(), Object->getType(),
6610 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006611 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006612 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006613 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006614 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006615 return;
6616 }
6617
6618 // The first conversion is actually a user-defined conversion whose
6619 // first conversion is ObjectInit's standard conversion (which is
6620 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006621 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006622 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006623 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006624 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006625 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006626 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006627 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006628 = Candidate.Conversions[0].UserDefined.Before;
6629 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6630
Mike Stump11289f42009-09-09 15:08:12 +00006631 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006632 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006633
6634 // (C++ 13.3.2p2): A candidate function having fewer than m
6635 // parameters is viable only if it has an ellipsis in its parameter
6636 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006637 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006638 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006639 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006640 return;
6641 }
6642
6643 // Function types don't have any default arguments, so just check if
6644 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006645 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006646 // Not enough arguments.
6647 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006648 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006649 return;
6650 }
6651
6652 // Determine the implicit conversion sequences for each of the
6653 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006654 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006655 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006656 // (C++ 13.3.2p3): for F to be a viable function, there shall
6657 // exist for each argument an implicit conversion sequence
6658 // (13.3.3.1) that converts that argument to the corresponding
6659 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006660 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006661 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006662 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006663 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006664 /*InOverloadResolution=*/false,
6665 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006666 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006667 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006668 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006669 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006670 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006671 }
6672 } else {
6673 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6674 // argument for which there is no corresponding parameter is
6675 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006676 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006677 }
6678 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006679
Craig Topper5fc8fc22014-08-27 06:28:36 +00006680 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006681 Candidate.Viable = false;
6682 Candidate.FailureKind = ovl_fail_enable_if;
6683 Candidate.DeductionFailure.Data = FailedAttr;
6684 return;
6685 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006686}
6687
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006688/// \brief Add overload candidates for overloaded operators that are
6689/// member functions.
6690///
6691/// Add the overloaded operator candidates that are member functions
6692/// for the operator Op that was used in an operator expression such
6693/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6694/// CandidateSet will store the added overload candidates. (C++
6695/// [over.match.oper]).
6696void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6697 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006698 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006699 OverloadCandidateSet& CandidateSet,
6700 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006701 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6702
6703 // C++ [over.match.oper]p3:
6704 // For a unary operator @ with an operand of a type whose
6705 // cv-unqualified version is T1, and for a binary operator @ with
6706 // a left operand of a type whose cv-unqualified version is T1 and
6707 // a right operand of a type whose cv-unqualified version is T2,
6708 // three sets of candidate functions, designated member
6709 // candidates, non-member candidates and built-in candidates, are
6710 // constructed as follows:
6711 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006712
Richard Smith0feaf0c2013-04-20 12:41:22 +00006713 // -- If T1 is a complete class type or a class currently being
6714 // defined, the set of member candidates is the result of the
6715 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6716 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006717 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006718 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006719 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006720 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006721 // If the type is neither complete nor being defined, bail out now.
6722 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006723 return;
Mike Stump11289f42009-09-09 15:08:12 +00006724
John McCall27b18f82009-11-17 02:14:36 +00006725 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6726 LookupQualifiedName(Operators, T1Rec->getDecl());
6727 Operators.suppressDiagnostics();
6728
Mike Stump11289f42009-09-09 15:08:12 +00006729 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006730 OperEnd = Operators.end();
6731 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006732 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006733 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006734 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006735 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006736 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006737 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006738 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006739}
6740
Douglas Gregora11693b2008-11-12 17:17:38 +00006741/// AddBuiltinCandidate - Add a candidate for a built-in
6742/// operator. ResultTy and ParamTys are the result and parameter types
6743/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006744/// arguments being passed to the candidate. IsAssignmentOperator
6745/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006746/// operator. NumContextualBoolArguments is the number of arguments
6747/// (at the beginning of the argument list) that will be contextually
6748/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006749void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006750 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006751 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006752 bool IsAssignmentOperator,
6753 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006754 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006755 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006756
Douglas Gregora11693b2008-11-12 17:17:38 +00006757 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006758 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006759 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6760 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006761 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006762 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006763 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006764 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006765 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6766
6767 // Determine the implicit conversion sequences for each of the
6768 // arguments.
6769 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006770 Candidate.ExplicitCallArguments = Args.size();
6771 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006772 // C++ [over.match.oper]p4:
6773 // For the built-in assignment operators, conversions of the
6774 // left operand are restricted as follows:
6775 // -- no temporaries are introduced to hold the left operand, and
6776 // -- no user-defined conversions are applied to the left
6777 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006778 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006779 //
6780 // We block these conversions by turning off user-defined
6781 // conversions, since that is the only way that initialization of
6782 // a reference to a non-class type can occur from something that
6783 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006784 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006785 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006786 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006787 Candidate.Conversions[ArgIdx]
6788 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006789 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006790 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006791 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006792 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006793 /*InOverloadResolution=*/false,
6794 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006795 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006796 }
John McCall0d1da222010-01-12 00:44:57 +00006797 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006798 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006799 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006800 break;
6801 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006802 }
6803}
6804
Craig Toppercd7b0332013-07-01 06:29:40 +00006805namespace {
6806
Douglas Gregora11693b2008-11-12 17:17:38 +00006807/// BuiltinCandidateTypeSet - A set of types that will be used for the
6808/// candidate operator functions for built-in operators (C++
6809/// [over.built]). The types are separated into pointer types and
6810/// enumeration types.
6811class BuiltinCandidateTypeSet {
6812 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006813 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006814
6815 /// PointerTypes - The set of pointer types that will be used in the
6816 /// built-in candidates.
6817 TypeSet PointerTypes;
6818
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006819 /// MemberPointerTypes - The set of member pointer types that will be
6820 /// used in the built-in candidates.
6821 TypeSet MemberPointerTypes;
6822
Douglas Gregora11693b2008-11-12 17:17:38 +00006823 /// EnumerationTypes - The set of enumeration types that will be
6824 /// used in the built-in candidates.
6825 TypeSet EnumerationTypes;
6826
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006828 /// candidates.
6829 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006830
6831 /// \brief A flag indicating non-record types are viable candidates
6832 bool HasNonRecordTypes;
6833
6834 /// \brief A flag indicating whether either arithmetic or enumeration types
6835 /// were present in the candidate set.
6836 bool HasArithmeticOrEnumeralTypes;
6837
Douglas Gregor80af3132011-05-21 23:15:46 +00006838 /// \brief A flag indicating whether the nullptr type was present in the
6839 /// candidate set.
6840 bool HasNullPtrType;
6841
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006842 /// Sema - The semantic analysis instance where we are building the
6843 /// candidate type set.
6844 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006845
Douglas Gregora11693b2008-11-12 17:17:38 +00006846 /// Context - The AST context in which we will build the type sets.
6847 ASTContext &Context;
6848
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006849 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6850 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006851 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006852
6853public:
6854 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006855 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006856
Mike Stump11289f42009-09-09 15:08:12 +00006857 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006858 : HasNonRecordTypes(false),
6859 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006860 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006861 SemaRef(SemaRef),
6862 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006863
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006865 SourceLocation Loc,
6866 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006867 bool AllowExplicitConversions,
6868 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006869
6870 /// pointer_begin - First pointer type found;
6871 iterator pointer_begin() { return PointerTypes.begin(); }
6872
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006873 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 iterator pointer_end() { return PointerTypes.end(); }
6875
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006876 /// member_pointer_begin - First member pointer type found;
6877 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6878
6879 /// member_pointer_end - Past the last member pointer type found;
6880 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6881
Douglas Gregora11693b2008-11-12 17:17:38 +00006882 /// enumeration_begin - First enumeration type found;
6883 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6884
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006885 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006886 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006888 iterator vector_begin() { return VectorTypes.begin(); }
6889 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006890
6891 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6892 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006893 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006894};
6895
Craig Toppercd7b0332013-07-01 06:29:40 +00006896} // end anonymous namespace
6897
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006898/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006899/// the set of pointer types along with any more-qualified variants of
6900/// that type. For example, if @p Ty is "int const *", this routine
6901/// will add "int const *", "int const volatile *", "int const
6902/// restrict *", and "int const volatile restrict *" to the set of
6903/// pointer types. Returns true if the add of @p Ty itself succeeded,
6904/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006905///
6906/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006907bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006908BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6909 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006910
Douglas Gregora11693b2008-11-12 17:17:38 +00006911 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006912 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006913 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006914
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006915 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006916 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006917 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006918 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006919 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6920 PointeeTy = PTy->getPointeeType();
6921 buildObjCPtr = true;
6922 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006923 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006924 }
6925
Sebastian Redl4990a632009-11-18 20:39:26 +00006926 // Don't add qualified variants of arrays. For one, they're not allowed
6927 // (the qualifier would sink to the element type), and for another, the
6928 // only overload situation where it matters is subscript or pointer +- int,
6929 // and those shouldn't have qualifier variants anyway.
6930 if (PointeeTy->isArrayType())
6931 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006932
John McCall8ccfcb52009-09-24 19:53:00 +00006933 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006934 bool hasVolatile = VisibleQuals.hasVolatile();
6935 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
John McCall8ccfcb52009-09-24 19:53:00 +00006937 // Iterate through all strict supersets of BaseCVR.
6938 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6939 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006940 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006941 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006942
6943 // Skip over restrict if no restrict found anywhere in the types, or if
6944 // the type cannot be restrict-qualified.
6945 if ((CVR & Qualifiers::Restrict) &&
6946 (!hasRestrict ||
6947 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6948 continue;
6949
6950 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006951 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006952
6953 // Build qualified pointer type.
6954 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006955 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006956 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006957 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006958 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6959
6960 // Insert qualified pointer type.
6961 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006962 }
6963
6964 return true;
6965}
6966
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006967/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6968/// to the set of pointer types along with any more-qualified variants of
6969/// that type. For example, if @p Ty is "int const *", this routine
6970/// will add "int const *", "int const volatile *", "int const
6971/// restrict *", and "int const volatile restrict *" to the set of
6972/// pointer types. Returns true if the add of @p Ty itself succeeded,
6973/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006974///
6975/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006976bool
6977BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6978 QualType Ty) {
6979 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006980 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006981 return false;
6982
John McCall8ccfcb52009-09-24 19:53:00 +00006983 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6984 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006985
John McCall8ccfcb52009-09-24 19:53:00 +00006986 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006987 // Don't add qualified variants of arrays. For one, they're not allowed
6988 // (the qualifier would sink to the element type), and for another, the
6989 // only overload situation where it matters is subscript or pointer +- int,
6990 // and those shouldn't have qualifier variants anyway.
6991 if (PointeeTy->isArrayType())
6992 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006993 const Type *ClassTy = PointerTy->getClass();
6994
6995 // Iterate through all strict supersets of the pointee type's CVR
6996 // qualifiers.
6997 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6998 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6999 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000
John McCall8ccfcb52009-09-24 19:53:00 +00007001 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007002 MemberPointerTypes.insert(
7003 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007004 }
7005
7006 return true;
7007}
7008
Douglas Gregora11693b2008-11-12 17:17:38 +00007009/// AddTypesConvertedFrom - Add each of the types to which the type @p
7010/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007011/// primarily interested in pointer types and enumeration types. We also
7012/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007013/// AllowUserConversions is true if we should look at the conversion
7014/// functions of a class type, and AllowExplicitConversions if we
7015/// should also include the explicit conversion functions of a class
7016/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007017void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007018BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007019 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007020 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007021 bool AllowExplicitConversions,
7022 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007023 // Only deal with canonical types.
7024 Ty = Context.getCanonicalType(Ty);
7025
7026 // Look through reference types; they aren't part of the type of an
7027 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007028 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007029 Ty = RefTy->getPointeeType();
7030
John McCall33ddac02011-01-19 10:06:00 +00007031 // If we're dealing with an array type, decay to the pointer.
7032 if (Ty->isArrayType())
7033 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7034
7035 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007036 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007037
Chandler Carruth00a38332010-12-13 01:44:01 +00007038 // Flag if we ever add a non-record type.
7039 const RecordType *TyRec = Ty->getAs<RecordType>();
7040 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7041
Chandler Carruth00a38332010-12-13 01:44:01 +00007042 // Flag if we encounter an arithmetic type.
7043 HasArithmeticOrEnumeralTypes =
7044 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7045
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007046 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7047 PointerTypes.insert(Ty);
7048 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007049 // Insert our type, and its more-qualified variants, into the set
7050 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007051 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007052 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007053 } else if (Ty->isMemberPointerType()) {
7054 // Member pointers are far easier, since the pointee can't be converted.
7055 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7056 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007057 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007058 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007059 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007060 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007061 // We treat vector types as arithmetic types in many contexts as an
7062 // extension.
7063 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007064 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007065 } else if (Ty->isNullPtrType()) {
7066 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007067 } else if (AllowUserConversions && TyRec) {
7068 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007069 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007070 return;
Mike Stump11289f42009-09-09 15:08:12 +00007071
Chandler Carruth00a38332010-12-13 01:44:01 +00007072 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007073 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007074 if (isa<UsingShadowDecl>(D))
7075 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007076
Chandler Carruth00a38332010-12-13 01:44:01 +00007077 // Skip conversion function templates; they don't tell us anything
7078 // about which builtin types we can convert to.
7079 if (isa<FunctionTemplateDecl>(D))
7080 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007081
Chandler Carruth00a38332010-12-13 01:44:01 +00007082 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7083 if (AllowExplicitConversions || !Conv->isExplicit()) {
7084 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7085 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007086 }
7087 }
7088 }
7089}
7090
Douglas Gregor84605ae2009-08-24 13:43:27 +00007091/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7092/// the volatile- and non-volatile-qualified assignment operators for the
7093/// given type to the candidate set.
7094static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7095 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007096 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007097 OverloadCandidateSet &CandidateSet) {
7098 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007099
Douglas Gregor84605ae2009-08-24 13:43:27 +00007100 // T& operator=(T&, T)
7101 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7102 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007104 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007105
Douglas Gregor84605ae2009-08-24 13:43:27 +00007106 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7107 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007108 ParamTypes[0]
7109 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007110 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007112 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007113 }
7114}
Mike Stump11289f42009-09-09 15:08:12 +00007115
Sebastian Redl1054fae2009-10-25 17:03:50 +00007116/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7117/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007118static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7119 Qualifiers VRQuals;
7120 const RecordType *TyRec;
7121 if (const MemberPointerType *RHSMPType =
7122 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007123 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007124 else
7125 TyRec = ArgExpr->getType()->getAs<RecordType>();
7126 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007127 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007128 VRQuals.addVolatile();
7129 VRQuals.addRestrict();
7130 return VRQuals;
7131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007134 if (!ClassDecl->hasDefinition())
7135 return VRQuals;
7136
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007137 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007138 if (isa<UsingShadowDecl>(D))
7139 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7140 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007141 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7142 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7143 CanTy = ResTypeRef->getPointeeType();
7144 // Need to go down the pointer/mempointer chain and add qualifiers
7145 // as see them.
7146 bool done = false;
7147 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007148 if (CanTy.isRestrictQualified())
7149 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007150 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7151 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007153 CanTy->getAs<MemberPointerType>())
7154 CanTy = ResTypeMPtr->getPointeeType();
7155 else
7156 done = true;
7157 if (CanTy.isVolatileQualified())
7158 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007159 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7160 return VRQuals;
7161 }
7162 }
7163 }
7164 return VRQuals;
7165}
John McCall52872982010-11-13 05:51:15 +00007166
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007167namespace {
John McCall52872982010-11-13 05:51:15 +00007168
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007169/// \brief Helper class to manage the addition of builtin operator overload
7170/// candidates. It provides shared state and utility methods used throughout
7171/// the process, as well as a helper method to add each group of builtin
7172/// operator overloads from the standard to a candidate set.
7173class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007174 // Common instance state available to all overload candidate addition methods.
7175 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007176 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007177 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007178 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007179 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007180 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007181
Chandler Carruthc6586e52010-12-12 10:35:00 +00007182 // Define some constants used to index and iterate over the arithemetic types
7183 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007184 // The "promoted arithmetic types" are the arithmetic
7185 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007186 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007187 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007188 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007189 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007190 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007191 LastPromotedArithmeticType = 11;
7192 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007193
Chandler Carruthc6586e52010-12-12 10:35:00 +00007194 /// \brief Get the canonical type for a given arithmetic type index.
7195 CanQualType getArithmeticType(unsigned index) {
7196 assert(index < NumArithmeticTypes);
7197 static CanQualType ASTContext::* const
7198 ArithmeticTypes[NumArithmeticTypes] = {
7199 // Start of promoted types.
7200 &ASTContext::FloatTy,
7201 &ASTContext::DoubleTy,
7202 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007203
Chandler Carruthc6586e52010-12-12 10:35:00 +00007204 // Start of integral types.
7205 &ASTContext::IntTy,
7206 &ASTContext::LongTy,
7207 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007208 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007209 &ASTContext::UnsignedIntTy,
7210 &ASTContext::UnsignedLongTy,
7211 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007212 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007213 // End of promoted types.
7214
7215 &ASTContext::BoolTy,
7216 &ASTContext::CharTy,
7217 &ASTContext::WCharTy,
7218 &ASTContext::Char16Ty,
7219 &ASTContext::Char32Ty,
7220 &ASTContext::SignedCharTy,
7221 &ASTContext::ShortTy,
7222 &ASTContext::UnsignedCharTy,
7223 &ASTContext::UnsignedShortTy,
7224 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007225 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007226 };
7227 return S.Context.*ArithmeticTypes[index];
7228 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007229
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007230 /// \brief Gets the canonical type resulting from the usual arithemetic
7231 /// converions for the given arithmetic types.
7232 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7233 // Accelerator table for performing the usual arithmetic conversions.
7234 // The rules are basically:
7235 // - if either is floating-point, use the wider floating-point
7236 // - if same signedness, use the higher rank
7237 // - if same size, use unsigned of the higher rank
7238 // - use the larger type
7239 // These rules, together with the axiom that higher ranks are
7240 // never smaller, are sufficient to precompute all of these results
7241 // *except* when dealing with signed types of higher rank.
7242 // (we could precompute SLL x UI for all known platforms, but it's
7243 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007244 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007245 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007246 Dep=-1,
7247 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007248 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007249 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007250 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007251/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7252/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7253/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7254/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7255/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7256/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7257/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7258/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7259/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7260/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7261/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007262 };
7263
7264 assert(L < LastPromotedArithmeticType);
7265 assert(R < LastPromotedArithmeticType);
7266 int Idx = ConversionsTable[L][R];
7267
7268 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007269 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007270
7271 // Slow path: we need to compare widths.
7272 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007273 CanQualType LT = getArithmeticType(L),
7274 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007275 unsigned LW = S.Context.getIntWidth(LT),
7276 RW = S.Context.getIntWidth(RT);
7277
7278 // If they're different widths, use the signed type.
7279 if (LW > RW) return LT;
7280 else if (LW < RW) return RT;
7281
7282 // Otherwise, use the unsigned type of the signed type's rank.
7283 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7284 assert(L == SLL || R == SLL);
7285 return S.Context.UnsignedLongLongTy;
7286 }
7287
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007288 /// \brief Helper method to factor out the common pattern of adding overloads
7289 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007290 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007291 bool HasVolatile,
7292 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007293 QualType ParamTypes[2] = {
7294 S.Context.getLValueReferenceType(CandidateTy),
7295 S.Context.IntTy
7296 };
7297
7298 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007299 if (Args.size() == 1)
7300 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007301 else
Richard Smithe54c3072013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007303
7304 // Use a heuristic to reduce number of builtin candidates in the set:
7305 // add volatile version only if there are conversions to a volatile type.
7306 if (HasVolatile) {
7307 ParamTypes[0] =
7308 S.Context.getLValueReferenceType(
7309 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007310 if (Args.size() == 1)
7311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007312 else
Richard Smithe54c3072013-05-05 15:51:06 +00007313 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007314 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007315
7316 // Add restrict version only if there are conversions to a restrict type
7317 // and our candidate type is a non-restrict-qualified pointer.
7318 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7319 !CandidateTy.isRestrictQualified()) {
7320 ParamTypes[0]
7321 = S.Context.getLValueReferenceType(
7322 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007323 if (Args.size() == 1)
7324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007325 else
Richard Smithe54c3072013-05-05 15:51:06 +00007326 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007327
7328 if (HasVolatile) {
7329 ParamTypes[0]
7330 = S.Context.getLValueReferenceType(
7331 S.Context.getCVRQualifiedType(CandidateTy,
7332 (Qualifiers::Volatile |
7333 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007334 if (Args.size() == 1)
7335 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007336 else
Richard Smithe54c3072013-05-05 15:51:06 +00007337 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007338 }
7339 }
7340
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007341 }
7342
7343public:
7344 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007345 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007346 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007347 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007348 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007349 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007350 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007352 HasArithmeticOrEnumeralCandidateType(
7353 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007354 CandidateTypes(CandidateTypes),
7355 CandidateSet(CandidateSet) {
7356 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007357 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007359 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007360 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007361 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007362 assert(getArithmeticType(FirstPromotedArithmeticType)
7363 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007365 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007366 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007367 "Invalid last promoted arithmetic type");
7368 }
7369
7370 // C++ [over.built]p3:
7371 //
7372 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7373 // is either volatile or empty, there exist candidate operator
7374 // functions of the form
7375 //
7376 // VQ T& operator++(VQ T&);
7377 // T operator++(VQ T&, int);
7378 //
7379 // C++ [over.built]p4:
7380 //
7381 // For every pair (T, VQ), where T is an arithmetic type other
7382 // than bool, and VQ is either volatile or empty, there exist
7383 // candidate operator functions of the form
7384 //
7385 // VQ T& operator--(VQ T&);
7386 // T operator--(VQ T&, int);
7387 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007388 if (!HasArithmeticOrEnumeralCandidateType)
7389 return;
7390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7392 Arith < NumArithmeticTypes; ++Arith) {
7393 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007394 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007395 VisibleTypeConversionsQuals.hasVolatile(),
7396 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007397 }
7398 }
7399
7400 // C++ [over.built]p5:
7401 //
7402 // For every pair (T, VQ), where T is a cv-qualified or
7403 // cv-unqualified object type, and VQ is either volatile or
7404 // empty, there exist candidate operator functions of the form
7405 //
7406 // T*VQ& operator++(T*VQ&);
7407 // T*VQ& operator--(T*VQ&);
7408 // T* operator++(T*VQ&, int);
7409 // T* operator--(T*VQ&, int);
7410 void addPlusPlusMinusMinusPointerOverloads() {
7411 for (BuiltinCandidateTypeSet::iterator
7412 Ptr = CandidateTypes[0].pointer_begin(),
7413 PtrEnd = CandidateTypes[0].pointer_end();
7414 Ptr != PtrEnd; ++Ptr) {
7415 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007416 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007417 continue;
7418
7419 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007420 (!(*Ptr).isVolatileQualified() &&
7421 VisibleTypeConversionsQuals.hasVolatile()),
7422 (!(*Ptr).isRestrictQualified() &&
7423 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007424 }
7425 }
7426
7427 // C++ [over.built]p6:
7428 // For every cv-qualified or cv-unqualified object type T, there
7429 // exist candidate operator functions of the form
7430 //
7431 // T& operator*(T*);
7432 //
7433 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007434 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007435 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007436 // T& operator*(T*);
7437 void addUnaryStarPointerOverloads() {
7438 for (BuiltinCandidateTypeSet::iterator
7439 Ptr = CandidateTypes[0].pointer_begin(),
7440 PtrEnd = CandidateTypes[0].pointer_end();
7441 Ptr != PtrEnd; ++Ptr) {
7442 QualType ParamTy = *Ptr;
7443 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007444 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7445 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446
Douglas Gregor02824322011-01-26 19:30:28 +00007447 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7448 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7449 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007452 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007453 }
7454 }
7455
7456 // C++ [over.built]p9:
7457 // For every promoted arithmetic type T, there exist candidate
7458 // operator functions of the form
7459 //
7460 // T operator+(T);
7461 // T operator-(T);
7462 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007463 if (!HasArithmeticOrEnumeralCandidateType)
7464 return;
7465
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007466 for (unsigned Arith = FirstPromotedArithmeticType;
7467 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007468 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007469 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 }
7471
7472 // Extension: We also add these operators for vector types.
7473 for (BuiltinCandidateTypeSet::iterator
7474 Vec = CandidateTypes[0].vector_begin(),
7475 VecEnd = CandidateTypes[0].vector_end();
7476 Vec != VecEnd; ++Vec) {
7477 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007478 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007479 }
7480 }
7481
7482 // C++ [over.built]p8:
7483 // For every type T, there exist candidate operator functions of
7484 // the form
7485 //
7486 // T* operator+(T*);
7487 void addUnaryPlusPointerOverloads() {
7488 for (BuiltinCandidateTypeSet::iterator
7489 Ptr = CandidateTypes[0].pointer_begin(),
7490 PtrEnd = CandidateTypes[0].pointer_end();
7491 Ptr != PtrEnd; ++Ptr) {
7492 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007493 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007494 }
7495 }
7496
7497 // C++ [over.built]p10:
7498 // For every promoted integral type T, there exist candidate
7499 // operator functions of the form
7500 //
7501 // T operator~(T);
7502 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007503 if (!HasArithmeticOrEnumeralCandidateType)
7504 return;
7505
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007506 for (unsigned Int = FirstPromotedIntegralType;
7507 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007508 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007509 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 }
7511
7512 // Extension: We also add this operator for vector types.
7513 for (BuiltinCandidateTypeSet::iterator
7514 Vec = CandidateTypes[0].vector_begin(),
7515 VecEnd = CandidateTypes[0].vector_end();
7516 Vec != VecEnd; ++Vec) {
7517 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007518 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007519 }
7520 }
7521
7522 // C++ [over.match.oper]p16:
7523 // For every pointer to member type T, there exist candidate operator
7524 // functions of the form
7525 //
7526 // bool operator==(T,T);
7527 // bool operator!=(T,T);
7528 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7529 /// Set of (canonical) types that we've already handled.
7530 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7531
Richard Smithe54c3072013-05-05 15:51:06 +00007532 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007533 for (BuiltinCandidateTypeSet::iterator
7534 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7535 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7536 MemPtr != MemPtrEnd;
7537 ++MemPtr) {
7538 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007539 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007540 continue;
7541
7542 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007543 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007544 }
7545 }
7546 }
7547
7548 // C++ [over.built]p15:
7549 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007550 // For every T, where T is an enumeration type, a pointer type, or
7551 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007552 //
7553 // bool operator<(T, T);
7554 // bool operator>(T, T);
7555 // bool operator<=(T, T);
7556 // bool operator>=(T, T);
7557 // bool operator==(T, T);
7558 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007559 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007560 // C++ [over.match.oper]p3:
7561 // [...]the built-in candidates include all of the candidate operator
7562 // functions defined in 13.6 that, compared to the given operator, [...]
7563 // do not have the same parameter-type-list as any non-template non-member
7564 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007565 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007566 // Note that in practice, this only affects enumeration types because there
7567 // aren't any built-in candidates of record type, and a user-defined operator
7568 // must have an operand of record or enumeration type. Also, the only other
7569 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007570 // cannot be overloaded for enumeration types, so this is the only place
7571 // where we must suppress candidates like this.
7572 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7573 UserDefinedBinaryOperators;
7574
Richard Smithe54c3072013-05-05 15:51:06 +00007575 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007576 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7577 CandidateTypes[ArgIdx].enumeration_end()) {
7578 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7579 CEnd = CandidateSet.end();
7580 C != CEnd; ++C) {
7581 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7582 continue;
7583
Eli Friedman14f082b2012-09-18 21:52:24 +00007584 if (C->Function->isFunctionTemplateSpecialization())
7585 continue;
7586
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007587 QualType FirstParamType =
7588 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7589 QualType SecondParamType =
7590 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7591
7592 // Skip if either parameter isn't of enumeral type.
7593 if (!FirstParamType->isEnumeralType() ||
7594 !SecondParamType->isEnumeralType())
7595 continue;
7596
7597 // Add this operator to the set of known user-defined operators.
7598 UserDefinedBinaryOperators.insert(
7599 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7600 S.Context.getCanonicalType(SecondParamType)));
7601 }
7602 }
7603 }
7604
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007605 /// Set of (canonical) types that we've already handled.
7606 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7607
Richard Smithe54c3072013-05-05 15:51:06 +00007608 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007609 for (BuiltinCandidateTypeSet::iterator
7610 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7611 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7612 Ptr != PtrEnd; ++Ptr) {
7613 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007614 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007615 continue;
7616
7617 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007618 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007619 }
7620 for (BuiltinCandidateTypeSet::iterator
7621 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7622 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7623 Enum != EnumEnd; ++Enum) {
7624 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7625
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007626 // Don't add the same builtin candidate twice, or if a user defined
7627 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007628 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007629 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7630 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007631 continue;
7632
7633 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007634 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007635 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007636
7637 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7638 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007639 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007640 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007641 NullPtrTy))) {
7642 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007643 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007644 CandidateSet);
7645 }
7646 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007647 }
7648 }
7649
7650 // C++ [over.built]p13:
7651 //
7652 // For every cv-qualified or cv-unqualified object type T
7653 // there exist candidate operator functions of the form
7654 //
7655 // T* operator+(T*, ptrdiff_t);
7656 // T& operator[](T*, ptrdiff_t); [BELOW]
7657 // T* operator-(T*, ptrdiff_t);
7658 // T* operator+(ptrdiff_t, T*);
7659 // T& operator[](ptrdiff_t, T*); [BELOW]
7660 //
7661 // C++ [over.built]p14:
7662 //
7663 // For every T, where T is a pointer to object type, there
7664 // exist candidate operator functions of the form
7665 //
7666 // ptrdiff_t operator-(T, T);
7667 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7668 /// Set of (canonical) types that we've already handled.
7669 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7670
7671 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007672 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007673 S.Context.getPointerDiffType(),
7674 S.Context.getPointerDiffType(),
7675 };
7676 for (BuiltinCandidateTypeSet::iterator
7677 Ptr = CandidateTypes[Arg].pointer_begin(),
7678 PtrEnd = CandidateTypes[Arg].pointer_end();
7679 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007680 QualType PointeeTy = (*Ptr)->getPointeeType();
7681 if (!PointeeTy->isObjectType())
7682 continue;
7683
Eric Christopher9207a522015-08-21 16:24:01 +00007684 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007685 if (Arg == 0 || Op == OO_Plus) {
7686 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7687 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007688 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007689 }
7690 if (Op == OO_Minus) {
7691 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007692 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 continue;
7694
7695 QualType ParamTypes[2] = { *Ptr, *Ptr };
7696 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007697 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007698 }
7699 }
7700 }
7701 }
7702
7703 // C++ [over.built]p12:
7704 //
7705 // For every pair of promoted arithmetic types L and R, there
7706 // exist candidate operator functions of the form
7707 //
7708 // LR operator*(L, R);
7709 // LR operator/(L, R);
7710 // LR operator+(L, R);
7711 // LR operator-(L, R);
7712 // bool operator<(L, R);
7713 // bool operator>(L, R);
7714 // bool operator<=(L, R);
7715 // bool operator>=(L, R);
7716 // bool operator==(L, R);
7717 // bool operator!=(L, R);
7718 //
7719 // where LR is the result of the usual arithmetic conversions
7720 // between types L and R.
7721 //
7722 // C++ [over.built]p24:
7723 //
7724 // For every pair of promoted arithmetic types L and R, there exist
7725 // candidate operator functions of the form
7726 //
7727 // LR operator?(bool, L, R);
7728 //
7729 // where LR is the result of the usual arithmetic conversions
7730 // between types L and R.
7731 // Our candidates ignore the first parameter.
7732 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007733 if (!HasArithmeticOrEnumeralCandidateType)
7734 return;
7735
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007736 for (unsigned Left = FirstPromotedArithmeticType;
7737 Left < LastPromotedArithmeticType; ++Left) {
7738 for (unsigned Right = FirstPromotedArithmeticType;
7739 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007740 QualType LandR[2] = { getArithmeticType(Left),
7741 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 QualType Result =
7743 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007744 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007745 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 }
7747 }
7748
7749 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7750 // conditional operator for vector types.
7751 for (BuiltinCandidateTypeSet::iterator
7752 Vec1 = CandidateTypes[0].vector_begin(),
7753 Vec1End = CandidateTypes[0].vector_end();
7754 Vec1 != Vec1End; ++Vec1) {
7755 for (BuiltinCandidateTypeSet::iterator
7756 Vec2 = CandidateTypes[1].vector_begin(),
7757 Vec2End = CandidateTypes[1].vector_end();
7758 Vec2 != Vec2End; ++Vec2) {
7759 QualType LandR[2] = { *Vec1, *Vec2 };
7760 QualType Result = S.Context.BoolTy;
7761 if (!isComparison) {
7762 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7763 Result = *Vec1;
7764 else
7765 Result = *Vec2;
7766 }
7767
Richard Smithe54c3072013-05-05 15:51:06 +00007768 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 }
7770 }
7771 }
7772
7773 // C++ [over.built]p17:
7774 //
7775 // For every pair of promoted integral types L and R, there
7776 // exist candidate operator functions of the form
7777 //
7778 // LR operator%(L, R);
7779 // LR operator&(L, R);
7780 // LR operator^(L, R);
7781 // LR operator|(L, R);
7782 // L operator<<(L, R);
7783 // L operator>>(L, R);
7784 //
7785 // where LR is the result of the usual arithmetic conversions
7786 // between types L and R.
7787 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007788 if (!HasArithmeticOrEnumeralCandidateType)
7789 return;
7790
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007791 for (unsigned Left = FirstPromotedIntegralType;
7792 Left < LastPromotedIntegralType; ++Left) {
7793 for (unsigned Right = FirstPromotedIntegralType;
7794 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007795 QualType LandR[2] = { getArithmeticType(Left),
7796 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7798 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007799 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007800 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007801 }
7802 }
7803 }
7804
7805 // C++ [over.built]p20:
7806 //
7807 // For every pair (T, VQ), where T is an enumeration or
7808 // pointer to member type and VQ is either volatile or
7809 // empty, there exist candidate operator functions of the form
7810 //
7811 // VQ T& operator=(VQ T&, T);
7812 void addAssignmentMemberPointerOrEnumeralOverloads() {
7813 /// Set of (canonical) types that we've already handled.
7814 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7815
7816 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7817 for (BuiltinCandidateTypeSet::iterator
7818 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7819 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7820 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007821 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007822 continue;
7823
Richard Smithe54c3072013-05-05 15:51:06 +00007824 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007825 }
7826
7827 for (BuiltinCandidateTypeSet::iterator
7828 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7829 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7830 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007831 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007832 continue;
7833
Richard Smithe54c3072013-05-05 15:51:06 +00007834 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007835 }
7836 }
7837 }
7838
7839 // C++ [over.built]p19:
7840 //
7841 // For every pair (T, VQ), where T is any type and VQ is either
7842 // volatile or empty, there exist candidate operator functions
7843 // of the form
7844 //
7845 // T*VQ& operator=(T*VQ&, T*);
7846 //
7847 // C++ [over.built]p21:
7848 //
7849 // For every pair (T, VQ), where T is a cv-qualified or
7850 // cv-unqualified object type and VQ is either volatile or
7851 // empty, there exist candidate operator functions of the form
7852 //
7853 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7854 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7855 void addAssignmentPointerOverloads(bool isEqualOp) {
7856 /// Set of (canonical) types that we've already handled.
7857 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7858
7859 for (BuiltinCandidateTypeSet::iterator
7860 Ptr = CandidateTypes[0].pointer_begin(),
7861 PtrEnd = CandidateTypes[0].pointer_end();
7862 Ptr != PtrEnd; ++Ptr) {
7863 // If this is operator=, keep track of the builtin candidates we added.
7864 if (isEqualOp)
7865 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007866 else if (!(*Ptr)->getPointeeType()->isObjectType())
7867 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007868
7869 // non-volatile version
7870 QualType ParamTypes[2] = {
7871 S.Context.getLValueReferenceType(*Ptr),
7872 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7873 };
Richard Smithe54c3072013-05-05 15:51:06 +00007874 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007875 /*IsAssigmentOperator=*/ isEqualOp);
7876
Douglas Gregor5bee2582012-06-04 00:15:09 +00007877 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7878 VisibleTypeConversionsQuals.hasVolatile();
7879 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 // volatile version
7881 ParamTypes[0] =
7882 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 /*IsAssigmentOperator=*/isEqualOp);
7885 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007886
7887 if (!(*Ptr).isRestrictQualified() &&
7888 VisibleTypeConversionsQuals.hasRestrict()) {
7889 // restrict version
7890 ParamTypes[0]
7891 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007893 /*IsAssigmentOperator=*/isEqualOp);
7894
7895 if (NeedVolatile) {
7896 // volatile restrict version
7897 ParamTypes[0]
7898 = S.Context.getLValueReferenceType(
7899 S.Context.getCVRQualifiedType(*Ptr,
7900 (Qualifiers::Volatile |
7901 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007902 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007903 /*IsAssigmentOperator=*/isEqualOp);
7904 }
7905 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007906 }
7907
7908 if (isEqualOp) {
7909 for (BuiltinCandidateTypeSet::iterator
7910 Ptr = CandidateTypes[1].pointer_begin(),
7911 PtrEnd = CandidateTypes[1].pointer_end();
7912 Ptr != PtrEnd; ++Ptr) {
7913 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007914 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007915 continue;
7916
Chandler Carruth8e543b32010-12-12 08:17:55 +00007917 QualType ParamTypes[2] = {
7918 S.Context.getLValueReferenceType(*Ptr),
7919 *Ptr,
7920 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007921
7922 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007923 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 /*IsAssigmentOperator=*/true);
7925
Douglas Gregor5bee2582012-06-04 00:15:09 +00007926 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7927 VisibleTypeConversionsQuals.hasVolatile();
7928 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007929 // volatile version
7930 ParamTypes[0] =
7931 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007932 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7933 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007934 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007935
7936 if (!(*Ptr).isRestrictQualified() &&
7937 VisibleTypeConversionsQuals.hasRestrict()) {
7938 // restrict version
7939 ParamTypes[0]
7940 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7942 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007943
7944 if (NeedVolatile) {
7945 // volatile restrict version
7946 ParamTypes[0]
7947 = S.Context.getLValueReferenceType(
7948 S.Context.getCVRQualifiedType(*Ptr,
7949 (Qualifiers::Volatile |
7950 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007951 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7952 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007953 }
7954 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007955 }
7956 }
7957 }
7958
7959 // C++ [over.built]p18:
7960 //
7961 // For every triple (L, VQ, R), where L is an arithmetic type,
7962 // VQ is either volatile or empty, and R is a promoted
7963 // arithmetic type, there exist candidate operator functions of
7964 // the form
7965 //
7966 // VQ L& operator=(VQ L&, R);
7967 // VQ L& operator*=(VQ L&, R);
7968 // VQ L& operator/=(VQ L&, R);
7969 // VQ L& operator+=(VQ L&, R);
7970 // VQ L& operator-=(VQ L&, R);
7971 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007972 if (!HasArithmeticOrEnumeralCandidateType)
7973 return;
7974
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007975 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7976 for (unsigned Right = FirstPromotedArithmeticType;
7977 Right < LastPromotedArithmeticType; ++Right) {
7978 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007979 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007980
7981 // Add this built-in operator as a candidate (VQ is empty).
7982 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007983 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007985 /*IsAssigmentOperator=*/isEqualOp);
7986
7987 // Add this built-in operator as a candidate (VQ is 'volatile').
7988 if (VisibleTypeConversionsQuals.hasVolatile()) {
7989 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007990 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 /*IsAssigmentOperator=*/isEqualOp);
7994 }
7995 }
7996 }
7997
7998 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7999 for (BuiltinCandidateTypeSet::iterator
8000 Vec1 = CandidateTypes[0].vector_begin(),
8001 Vec1End = CandidateTypes[0].vector_end();
8002 Vec1 != Vec1End; ++Vec1) {
8003 for (BuiltinCandidateTypeSet::iterator
8004 Vec2 = CandidateTypes[1].vector_begin(),
8005 Vec2End = CandidateTypes[1].vector_end();
8006 Vec2 != Vec2End; ++Vec2) {
8007 QualType ParamTypes[2];
8008 ParamTypes[1] = *Vec2;
8009 // Add this built-in operator as a candidate (VQ is empty).
8010 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008012 /*IsAssigmentOperator=*/isEqualOp);
8013
8014 // Add this built-in operator as a candidate (VQ is 'volatile').
8015 if (VisibleTypeConversionsQuals.hasVolatile()) {
8016 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8017 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008018 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008019 /*IsAssigmentOperator=*/isEqualOp);
8020 }
8021 }
8022 }
8023 }
8024
8025 // C++ [over.built]p22:
8026 //
8027 // For every triple (L, VQ, R), where L is an integral type, VQ
8028 // is either volatile or empty, and R is a promoted integral
8029 // type, there exist candidate operator functions of the form
8030 //
8031 // VQ L& operator%=(VQ L&, R);
8032 // VQ L& operator<<=(VQ L&, R);
8033 // VQ L& operator>>=(VQ L&, R);
8034 // VQ L& operator&=(VQ L&, R);
8035 // VQ L& operator^=(VQ L&, R);
8036 // VQ L& operator|=(VQ L&, R);
8037 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008038 if (!HasArithmeticOrEnumeralCandidateType)
8039 return;
8040
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008041 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8042 for (unsigned Right = FirstPromotedIntegralType;
8043 Right < LastPromotedIntegralType; ++Right) {
8044 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008045 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046
8047 // Add this built-in operator as a candidate (VQ is empty).
8048 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008049 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 if (VisibleTypeConversionsQuals.hasVolatile()) {
8052 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008053 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8055 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008057 }
8058 }
8059 }
8060 }
8061
8062 // C++ [over.operator]p23:
8063 //
8064 // There also exist candidate operator functions of the form
8065 //
8066 // bool operator!(bool);
8067 // bool operator&&(bool, bool);
8068 // bool operator||(bool, bool);
8069 void addExclaimOverload() {
8070 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008071 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 /*IsAssignmentOperator=*/false,
8073 /*NumContextualBoolArguments=*/1);
8074 }
8075 void addAmpAmpOrPipePipeOverload() {
8076 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008077 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008078 /*IsAssignmentOperator=*/false,
8079 /*NumContextualBoolArguments=*/2);
8080 }
8081
8082 // C++ [over.built]p13:
8083 //
8084 // For every cv-qualified or cv-unqualified object type T there
8085 // exist candidate operator functions of the form
8086 //
8087 // T* operator+(T*, ptrdiff_t); [ABOVE]
8088 // T& operator[](T*, ptrdiff_t);
8089 // T* operator-(T*, ptrdiff_t); [ABOVE]
8090 // T* operator+(ptrdiff_t, T*); [ABOVE]
8091 // T& operator[](ptrdiff_t, T*);
8092 void addSubscriptOverloads() {
8093 for (BuiltinCandidateTypeSet::iterator
8094 Ptr = CandidateTypes[0].pointer_begin(),
8095 PtrEnd = CandidateTypes[0].pointer_end();
8096 Ptr != PtrEnd; ++Ptr) {
8097 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8098 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008099 if (!PointeeType->isObjectType())
8100 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008101
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008102 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8103
8104 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008105 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008106 }
8107
8108 for (BuiltinCandidateTypeSet::iterator
8109 Ptr = CandidateTypes[1].pointer_begin(),
8110 PtrEnd = CandidateTypes[1].pointer_end();
8111 Ptr != PtrEnd; ++Ptr) {
8112 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8113 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008114 if (!PointeeType->isObjectType())
8115 continue;
8116
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008117 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8118
8119 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008120 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008121 }
8122 }
8123
8124 // C++ [over.built]p11:
8125 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8126 // C1 is the same type as C2 or is a derived class of C2, T is an object
8127 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8128 // there exist candidate operator functions of the form
8129 //
8130 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8131 //
8132 // where CV12 is the union of CV1 and CV2.
8133 void addArrowStarOverloads() {
8134 for (BuiltinCandidateTypeSet::iterator
8135 Ptr = CandidateTypes[0].pointer_begin(),
8136 PtrEnd = CandidateTypes[0].pointer_end();
8137 Ptr != PtrEnd; ++Ptr) {
8138 QualType C1Ty = (*Ptr);
8139 QualType C1;
8140 QualifierCollector Q1;
8141 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8142 if (!isa<RecordType>(C1))
8143 continue;
8144 // heuristic to reduce number of builtin candidates in the set.
8145 // Add volatile/restrict version only if there are conversions to a
8146 // volatile/restrict type.
8147 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8148 continue;
8149 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8150 continue;
8151 for (BuiltinCandidateTypeSet::iterator
8152 MemPtr = CandidateTypes[1].member_pointer_begin(),
8153 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8154 MemPtr != MemPtrEnd; ++MemPtr) {
8155 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8156 QualType C2 = QualType(mptr->getClass(), 0);
8157 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008158 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008159 break;
8160 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8161 // build CV12 T&
8162 QualType T = mptr->getPointeeType();
8163 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8164 T.isVolatileQualified())
8165 continue;
8166 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8167 T.isRestrictQualified())
8168 continue;
8169 T = Q1.apply(S.Context, T);
8170 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008171 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008172 }
8173 }
8174 }
8175
8176 // Note that we don't consider the first argument, since it has been
8177 // contextually converted to bool long ago. The candidates below are
8178 // therefore added as binary.
8179 //
8180 // C++ [over.built]p25:
8181 // For every type T, where T is a pointer, pointer-to-member, or scoped
8182 // enumeration type, there exist candidate operator functions of the form
8183 //
8184 // T operator?(bool, T, T);
8185 //
8186 void addConditionalOperatorOverloads() {
8187 /// Set of (canonical) types that we've already handled.
8188 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8189
8190 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8191 for (BuiltinCandidateTypeSet::iterator
8192 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8193 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8194 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008195 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008196 continue;
8197
8198 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008199 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200 }
8201
8202 for (BuiltinCandidateTypeSet::iterator
8203 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8204 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8205 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008206 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008207 continue;
8208
8209 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008210 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 }
8212
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008213 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008214 for (BuiltinCandidateTypeSet::iterator
8215 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8216 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8217 Enum != EnumEnd; ++Enum) {
8218 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8219 continue;
8220
David Blaikie82e95a32014-11-19 07:49:47 +00008221 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008222 continue;
8223
8224 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008225 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 }
8227 }
8228 }
8229 }
8230};
8231
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232} // end anonymous namespace
8233
8234/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8235/// operator overloads to the candidate set (C++ [over.built]), based
8236/// on the operator @p Op and the arguments given. For example, if the
8237/// operator is a binary '+', this routine might add "int
8238/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008239void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8240 SourceLocation OpLoc,
8241 ArrayRef<Expr *> Args,
8242 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008243 // Find all of the types that the arguments can convert to, but only
8244 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008245 // that make use of these types. Also record whether we encounter non-record
8246 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008247 Qualifiers VisibleTypeConversionsQuals;
8248 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008249 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008250 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008251
8252 bool HasNonRecordCandidateType = false;
8253 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008254 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008255 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008256 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008257 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8258 OpLoc,
8259 true,
8260 (Op == OO_Exclaim ||
8261 Op == OO_AmpAmp ||
8262 Op == OO_PipePipe),
8263 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008264 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8265 CandidateTypes[ArgIdx].hasNonRecordTypes();
8266 HasArithmeticOrEnumeralCandidateType =
8267 HasArithmeticOrEnumeralCandidateType ||
8268 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008269 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008270
Chandler Carruth00a38332010-12-13 01:44:01 +00008271 // Exit early when no non-record types have been added to the candidate set
8272 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008273 //
8274 // We can't exit early for !, ||, or &&, since there we have always have
8275 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008276 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008277 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008278 return;
8279
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008280 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008281 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008282 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008283 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284 CandidateTypes, CandidateSet);
8285
8286 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008287 switch (Op) {
8288 case OO_None:
8289 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008290 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008291
Chandler Carruth5184de02010-12-12 08:51:33 +00008292 case OO_New:
8293 case OO_Delete:
8294 case OO_Array_New:
8295 case OO_Array_Delete:
8296 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008297 llvm_unreachable(
8298 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008299
8300 case OO_Comma:
8301 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008302 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008303 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008304 // -- For the operator ',', the unary operator '&', the
8305 // operator '->', or the operator 'co_await', the
8306 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008307 break;
8308
8309 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008310 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008311 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008312 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008313
8314 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008315 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008316 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008317 } else {
8318 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8319 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8320 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008321 break;
8322
Chandler Carruth5184de02010-12-12 08:51:33 +00008323 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008324 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008325 OpBuilder.addUnaryStarPointerOverloads();
8326 else
8327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8328 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008329
Chandler Carruth5184de02010-12-12 08:51:33 +00008330 case OO_Slash:
8331 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008332 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008333
8334 case OO_PlusPlus:
8335 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008336 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8337 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008338 break;
8339
Douglas Gregor84605ae2009-08-24 13:43:27 +00008340 case OO_EqualEqual:
8341 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008343 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008344
Douglas Gregora11693b2008-11-12 17:17:38 +00008345 case OO_Less:
8346 case OO_Greater:
8347 case OO_LessEqual:
8348 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008349 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008350 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8351 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008352
Douglas Gregora11693b2008-11-12 17:17:38 +00008353 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008354 case OO_Caret:
8355 case OO_Pipe:
8356 case OO_LessLess:
8357 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008358 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008359 break;
8360
Chandler Carruth5184de02010-12-12 08:51:33 +00008361 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008362 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008363 // C++ [over.match.oper]p3:
8364 // -- For the operator ',', the unary operator '&', or the
8365 // operator '->', the built-in candidates set is empty.
8366 break;
8367
8368 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8369 break;
8370
8371 case OO_Tilde:
8372 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8373 break;
8374
Douglas Gregora11693b2008-11-12 17:17:38 +00008375 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008377 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008378
8379 case OO_PlusEqual:
8380 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008381 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008382 // Fall through.
8383
8384 case OO_StarEqual:
8385 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008386 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008387 break;
8388
8389 case OO_PercentEqual:
8390 case OO_LessLessEqual:
8391 case OO_GreaterGreaterEqual:
8392 case OO_AmpEqual:
8393 case OO_CaretEqual:
8394 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008395 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008396 break;
8397
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008398 case OO_Exclaim:
8399 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008400 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008401
Douglas Gregora11693b2008-11-12 17:17:38 +00008402 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403 case OO_PipePipe:
8404 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008405 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008406
8407 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008408 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008409 break;
8410
8411 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008412 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008413 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008414
8415 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008416 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008417 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8418 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008419 }
8420}
8421
Douglas Gregore254f902009-02-04 00:32:51 +00008422/// \brief Add function candidates found via argument-dependent lookup
8423/// to the set of overloading candidates.
8424///
8425/// This routine performs argument-dependent name lookup based on the
8426/// given function name (which may also be an operator name) and adds
8427/// all of the overload candidates found by ADL to the overload
8428/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008429void
Douglas Gregore254f902009-02-04 00:32:51 +00008430Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008431 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008432 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008433 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008434 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008435 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008436 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008437
John McCall91f61fc2010-01-26 06:04:06 +00008438 // FIXME: This approach for uniquing ADL results (and removing
8439 // redundant candidates from the set) relies on pointer-equality,
8440 // which means we need to key off the canonical decl. However,
8441 // always going back to the canonical decl might not get us the
8442 // right set of default arguments. What default arguments are
8443 // we supposed to consider on ADL candidates, anyway?
8444
Douglas Gregorcabea402009-09-22 15:41:20 +00008445 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008446 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008447
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008448 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008449 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8450 CandEnd = CandidateSet.end();
8451 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008452 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008453 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008454 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008455 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008456 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008457
8458 // For each of the ADL candidates we found, add it to the overload
8459 // set.
John McCall8fe68082010-01-26 07:16:45 +00008460 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008461 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008462 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008463 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008464 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008465
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008466 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8467 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008468 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008469 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008470 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008471 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008472 }
Douglas Gregore254f902009-02-04 00:32:51 +00008473}
8474
George Burgess IV2a6150d2015-10-16 01:17:38 +00008475// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8476// Cand2 for overloading. This function assumes that all of the enable_if attrs
8477// on Cand1 and Cand2 have conditions that evaluate to true.
8478//
8479// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8480// Cand1's first N enable_if attributes have precisely the same conditions as
8481// Cand2's first N enable_if attributes (where N = the number of enable_if
8482// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8483static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8484 const FunctionDecl *Cand2) {
8485
8486 // FIXME: The next several lines are just
8487 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8488 // instead of reverse order which is how they're stored in the AST.
8489 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8490 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8491
8492 // Candidate 1 is better if it has strictly more attributes and
8493 // the common sequence is identical.
8494 if (Cand1Attrs.size() <= Cand2Attrs.size())
8495 return false;
8496
8497 auto Cand1I = Cand1Attrs.begin();
8498 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8499 for (auto &Cand2A : Cand2Attrs) {
8500 Cand1ID.clear();
8501 Cand2ID.clear();
8502
8503 auto &Cand1A = *Cand1I++;
8504 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8505 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8506 if (Cand1ID != Cand2ID)
8507 return false;
8508 }
8509
8510 return true;
8511}
8512
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008513/// isBetterOverloadCandidate - Determines whether the first overload
8514/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008515bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8516 const OverloadCandidate &Cand2,
8517 SourceLocation Loc,
8518 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008519 // Define viable functions to be better candidates than non-viable
8520 // functions.
8521 if (!Cand2.Viable)
8522 return Cand1.Viable;
8523 else if (!Cand1.Viable)
8524 return false;
8525
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008526 // C++ [over.match.best]p1:
8527 //
8528 // -- if F is a static member function, ICS1(F) is defined such
8529 // that ICS1(F) is neither better nor worse than ICS1(G) for
8530 // any function G, and, symmetrically, ICS1(G) is neither
8531 // better nor worse than ICS1(F).
8532 unsigned StartArg = 0;
8533 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8534 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008535
Douglas Gregord3cb3562009-07-07 23:38:56 +00008536 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008537 // A viable function F1 is defined to be a better function than another
8538 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008539 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008540 unsigned NumArgs = Cand1.NumConversions;
8541 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008542 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008543 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008544 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008545 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008546 Cand2.Conversions[ArgIdx])) {
8547 case ImplicitConversionSequence::Better:
8548 // Cand1 has a better conversion sequence.
8549 HasBetterConversion = true;
8550 break;
8551
8552 case ImplicitConversionSequence::Worse:
8553 // Cand1 can't be better than Cand2.
8554 return false;
8555
8556 case ImplicitConversionSequence::Indistinguishable:
8557 // Do nothing.
8558 break;
8559 }
8560 }
8561
Mike Stump11289f42009-09-09 15:08:12 +00008562 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008563 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008564 if (HasBetterConversion)
8565 return true;
8566
Douglas Gregora1f013e2008-11-07 22:36:19 +00008567 // -- the context is an initialization by user-defined conversion
8568 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8569 // from the return type of F1 to the destination type (i.e.,
8570 // the type of the entity being initialized) is a better
8571 // conversion sequence than the standard conversion sequence
8572 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008573 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008574 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008575 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008576 // First check whether we prefer one of the conversion functions over the
8577 // other. This only distinguishes the results in non-standard, extension
8578 // cases such as the conversion from a lambda closure type to a function
8579 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008580 ImplicitConversionSequence::CompareKind Result =
8581 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8582 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008583 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008584 Cand1.FinalConversion,
8585 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008586
Richard Smithec2748a2014-05-17 04:36:39 +00008587 if (Result != ImplicitConversionSequence::Indistinguishable)
8588 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008589
8590 // FIXME: Compare kind of reference binding if conversion functions
8591 // convert to a reference type used in direct reference binding, per
8592 // C++14 [over.match.best]p1 section 2 bullet 3.
8593 }
8594
8595 // -- F1 is a non-template function and F2 is a function template
8596 // specialization, or, if not that,
8597 bool Cand1IsSpecialization = Cand1.Function &&
8598 Cand1.Function->getPrimaryTemplate();
8599 bool Cand2IsSpecialization = Cand2.Function &&
8600 Cand2.Function->getPrimaryTemplate();
8601 if (Cand1IsSpecialization != Cand2IsSpecialization)
8602 return Cand2IsSpecialization;
8603
8604 // -- F1 and F2 are function template specializations, and the function
8605 // template for F1 is more specialized than the template for F2
8606 // according to the partial ordering rules described in 14.5.5.2, or,
8607 // if not that,
8608 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8609 if (FunctionTemplateDecl *BetterTemplate
8610 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8611 Cand2.Function->getPrimaryTemplate(),
8612 Loc,
8613 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8614 : TPOC_Call,
8615 Cand1.ExplicitCallArguments,
8616 Cand2.ExplicitCallArguments))
8617 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008618 }
8619
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008620 // Check for enable_if value-based overload resolution.
8621 if (Cand1.Function && Cand2.Function &&
8622 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008623 Cand2.Function->hasAttr<EnableIfAttr>()))
8624 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008625
Artem Belevich94a55e82015-09-22 17:22:59 +00008626 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8627 Cand1.Function && Cand2.Function) {
8628 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8629 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8630 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8631 }
8632
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008633 bool HasPS1 = Cand1.Function != nullptr &&
8634 functionHasPassObjectSizeParams(Cand1.Function);
8635 bool HasPS2 = Cand2.Function != nullptr &&
8636 functionHasPassObjectSizeParams(Cand2.Function);
8637 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008638}
8639
Richard Smith2dbe4042015-11-04 19:26:32 +00008640/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008641/// name lookup and overload resolution. This applies when the same internal/no
8642/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008643/// the same header). In such a case, we don't consider the declarations to
8644/// declare the same entity, but we also don't want lookups with both
8645/// declarations visible to be ambiguous in some cases (this happens when using
8646/// a modularized libstdc++).
8647bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8648 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008649 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8650 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8651 if (!VA || !VB)
8652 return false;
8653
8654 // The declarations must be declaring the same name as an internal linkage
8655 // entity in different modules.
8656 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8657 VB->getDeclContext()->getRedeclContext()) ||
8658 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8659 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8660 VA->isExternallyVisible() || VB->isExternallyVisible())
8661 return false;
8662
8663 // Check that the declarations appear to be equivalent.
8664 //
8665 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8666 // For constants and functions, we should check the initializer or body is
8667 // the same. For non-constant variables, we shouldn't allow it at all.
8668 if (Context.hasSameType(VA->getType(), VB->getType()))
8669 return true;
8670
8671 // Enum constants within unnamed enumerations will have different types, but
8672 // may still be similar enough to be interchangeable for our purposes.
8673 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8674 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8675 // Only handle anonymous enums. If the enumerations were named and
8676 // equivalent, they would have been merged to the same type.
8677 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8678 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8679 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8680 !Context.hasSameType(EnumA->getIntegerType(),
8681 EnumB->getIntegerType()))
8682 return false;
8683 // Allow this only if the value is the same for both enumerators.
8684 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8685 }
8686 }
8687
8688 // Nothing else is sufficiently similar.
8689 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008690}
8691
8692void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8693 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8694 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8695
8696 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8697 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8698 << !M << (M ? M->getFullModuleName() : "");
8699
8700 for (auto *E : Equiv) {
8701 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8702 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8703 << !M << (M ? M->getFullModuleName() : "");
8704 }
Richard Smith896c66e2015-10-21 07:13:52 +00008705}
8706
Mike Stump11289f42009-09-09 15:08:12 +00008707/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008708/// within an overload candidate set.
8709///
James Dennettffad8b72012-06-22 08:10:18 +00008710/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008711/// which overload resolution occurs.
8712///
James Dennettffad8b72012-06-22 08:10:18 +00008713/// \param Best If overload resolution was successful or found a deleted
8714/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008715///
8716/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008717OverloadingResult
8718OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008719 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008720 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008721 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8722 std::transform(begin(), end(), std::back_inserter(Candidates),
8723 [](OverloadCandidate &Cand) { return &Cand; });
8724
8725 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8726 // but accepted by both clang and NVCC. However during a particular
8727 // compilation mode only one call variant is viable. We need to
8728 // exclude non-viable overload candidates from consideration based
8729 // only on their host/device attributes. Specifically, if one
8730 // candidate call is WrongSide and the other is SameSide, we ignore
8731 // the WrongSide candidate.
8732 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) {
8733 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8734 bool ContainsSameSideCandidate =
8735 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8736 return Cand->Function &&
8737 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8738 Sema::CFP_SameSide;
8739 });
8740 if (ContainsSameSideCandidate) {
8741 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8742 return Cand->Function &&
8743 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8744 Sema::CFP_WrongSide;
8745 };
8746 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8747 IsWrongSideCandidate),
8748 Candidates.end());
8749 }
8750 }
8751
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008752 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008753 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008754 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008755 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008756 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008757 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008758 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008759
8760 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008761 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008762 return OR_No_Viable_Function;
8763
Richard Smith2dbe4042015-11-04 19:26:32 +00008764 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008765
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008766 // Make sure that this function is better than every other viable
8767 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008768 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008769 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008770 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008771 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008772 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008773 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8774 Cand->Function)) {
8775 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008776 continue;
8777 }
8778
John McCall5c32be02010-08-24 20:38:10 +00008779 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008780 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008781 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008782 }
Mike Stump11289f42009-09-09 15:08:12 +00008783
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008784 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008785 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008786 (Best->Function->isDeleted() ||
8787 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008788 return OR_Deleted;
8789
Richard Smith2dbe4042015-11-04 19:26:32 +00008790 if (!EquivalentCands.empty())
8791 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8792 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008793
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008794 return OR_Success;
8795}
8796
John McCall53262c92010-01-12 02:15:36 +00008797namespace {
8798
8799enum OverloadCandidateKind {
8800 oc_function,
8801 oc_method,
8802 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008803 oc_function_template,
8804 oc_method_template,
8805 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008806 oc_implicit_default_constructor,
8807 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008808 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008809 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008810 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008811 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008812};
8813
John McCalle1ac8d12010-01-13 00:25:19 +00008814OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8815 FunctionDecl *Fn,
8816 std::string &Description) {
8817 bool isTemplate = false;
8818
8819 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8820 isTemplate = true;
8821 Description = S.getTemplateArgumentBindingsText(
8822 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8823 }
John McCallfd0b2f82010-01-06 09:43:14 +00008824
8825 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008826 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008827 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008828
Sebastian Redl08905022011-02-05 19:23:19 +00008829 if (Ctor->getInheritedConstructor())
8830 return oc_implicit_inherited_constructor;
8831
Alexis Hunt119c10e2011-05-25 23:16:36 +00008832 if (Ctor->isDefaultConstructor())
8833 return oc_implicit_default_constructor;
8834
8835 if (Ctor->isMoveConstructor())
8836 return oc_implicit_move_constructor;
8837
8838 assert(Ctor->isCopyConstructor() &&
8839 "unexpected sort of implicit constructor");
8840 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008841 }
8842
8843 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8844 // This actually gets spelled 'candidate function' for now, but
8845 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008846 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008847 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008848
Alexis Hunt119c10e2011-05-25 23:16:36 +00008849 if (Meth->isMoveAssignmentOperator())
8850 return oc_implicit_move_assignment;
8851
Douglas Gregor12695102012-02-10 08:36:38 +00008852 if (Meth->isCopyAssignmentOperator())
8853 return oc_implicit_copy_assignment;
8854
8855 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8856 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008857 }
8858
John McCalle1ac8d12010-01-13 00:25:19 +00008859 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008860}
8861
Larisse Voufo98b20f12013-07-19 23:00:19 +00008862void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008863 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8864 if (!Ctor) return;
8865
8866 Ctor = Ctor->getInheritedConstructor();
8867 if (!Ctor) return;
8868
8869 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8870}
8871
John McCall53262c92010-01-12 02:15:36 +00008872} // end anonymous namespace
8873
George Burgess IV5f21c712015-10-12 19:57:04 +00008874static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8875 const FunctionDecl *FD) {
8876 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8877 bool AlwaysTrue;
8878 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8879 return false;
8880 if (!AlwaysTrue)
8881 return false;
8882 }
8883 return true;
8884}
8885
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008886/// \brief Returns true if we can take the address of the function.
8887///
8888/// \param Complain - If true, we'll emit a diagnostic
8889/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8890/// we in overload resolution?
8891/// \param Loc - The location of the statement we're complaining about. Ignored
8892/// if we're not complaining, or if we're in overload resolution.
8893static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8894 bool Complain,
8895 bool InOverloadResolution,
8896 SourceLocation Loc) {
8897 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8898 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008899 if (InOverloadResolution)
8900 S.Diag(FD->getLocStart(),
8901 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8902 else
8903 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8904 }
8905 return false;
8906 }
8907
8908 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8909 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8910 if (I == FD->param_end())
8911 return true;
8912
8913 if (Complain) {
8914 // Add one to ParamNo because it's user-facing
8915 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8916 if (InOverloadResolution)
8917 S.Diag(FD->getLocation(),
8918 diag::note_ovl_candidate_has_pass_object_size_params)
8919 << ParamNo;
8920 else
8921 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8922 << FD << ParamNo;
8923 }
8924 return false;
8925}
8926
8927static bool checkAddressOfCandidateIsAvailable(Sema &S,
8928 const FunctionDecl *FD) {
8929 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8930 /*InOverloadResolution=*/true,
8931 /*Loc=*/SourceLocation());
8932}
8933
8934bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8935 bool Complain,
8936 SourceLocation Loc) {
8937 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8938 /*InOverloadResolution=*/false,
8939 Loc);
8940}
8941
John McCall53262c92010-01-12 02:15:36 +00008942// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008943void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8944 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008945 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8946 return;
8947
John McCalle1ac8d12010-01-13 00:25:19 +00008948 std::string FnDesc;
8949 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008950 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8951 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008952
8953 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008954 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008955 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008956}
8957
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008958// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008959// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008960void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8961 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008962 assert(OverloadedExpr->getType() == Context.OverloadTy);
8963
8964 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8965 OverloadExpr *OvlExpr = Ovl.Expression;
8966
8967 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8968 IEnd = OvlExpr->decls_end();
8969 I != IEnd; ++I) {
8970 if (FunctionTemplateDecl *FunTmpl =
8971 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008972 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8973 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008974 } else if (FunctionDecl *Fun
8975 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008976 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008977 }
8978 }
8979}
8980
John McCall0d1da222010-01-12 00:44:57 +00008981/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8982/// "lead" diagnostic; it will be given two arguments, the source and
8983/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008984void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8985 Sema &S,
8986 SourceLocation CaretLoc,
8987 const PartialDiagnostic &PDiag) const {
8988 S.Diag(CaretLoc, PDiag)
8989 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008990 // FIXME: The note limiting machinery is borrowed from
8991 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8992 // refactoring here.
8993 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8994 unsigned CandsShown = 0;
8995 AmbiguousConversionSequence::const_iterator I, E;
8996 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8997 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8998 break;
8999 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00009000 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00009001 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009002 if (I != E)
9003 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009004}
9005
Richard Smith17c00b42014-11-12 01:24:00 +00009006static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009007 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009008 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9009 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009010 assert(Cand->Function && "for now, candidate must be a function");
9011 FunctionDecl *Fn = Cand->Function;
9012
9013 // There's a conversion slot for the object argument if this is a
9014 // non-constructor method. Note that 'I' corresponds the
9015 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009016 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009017 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009018 if (I == 0)
9019 isObjectArgument = true;
9020 else
9021 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009022 }
9023
John McCalle1ac8d12010-01-13 00:25:19 +00009024 std::string FnDesc;
9025 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9026
John McCall6a61b522010-01-13 09:16:55 +00009027 Expr *FromExpr = Conv.Bad.FromExpr;
9028 QualType FromTy = Conv.Bad.getFromType();
9029 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009030
John McCallfb7ad0f2010-02-02 02:42:52 +00009031 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009032 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009033 Expr *E = FromExpr->IgnoreParens();
9034 if (isa<UnaryOperator>(E))
9035 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009036 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009037
9038 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9039 << (unsigned) FnKind << FnDesc
9040 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9041 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009042 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009043 return;
9044 }
9045
John McCall6d174642010-01-23 08:10:49 +00009046 // Do some hand-waving analysis to see if the non-viability is due
9047 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009048 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9049 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9050 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9051 CToTy = RT->getPointeeType();
9052 else {
9053 // TODO: detect and diagnose the full richness of const mismatches.
9054 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009055 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9056 CFromTy = FromPT->getPointeeType();
9057 CToTy = ToPT->getPointeeType();
9058 }
John McCall47000992010-01-14 03:28:57 +00009059 }
9060
9061 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9062 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009063 Qualifiers FromQs = CFromTy.getQualifiers();
9064 Qualifiers ToQs = CToTy.getQualifiers();
9065
9066 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9068 << (unsigned) FnKind << FnDesc
9069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9070 << FromTy
9071 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9072 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009073 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009074 return;
9075 }
9076
John McCall31168b02011-06-15 23:02:42 +00009077 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009079 << (unsigned) FnKind << FnDesc
9080 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9081 << FromTy
9082 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9083 << (unsigned) isObjectArgument << I+1;
9084 MaybeEmitInheritedConstructorNote(S, Fn);
9085 return;
9086 }
9087
Douglas Gregoraec25842011-04-26 23:16:46 +00009088 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9090 << (unsigned) FnKind << FnDesc
9091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9092 << FromTy
9093 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9094 << (unsigned) isObjectArgument << I+1;
9095 MaybeEmitInheritedConstructorNote(S, Fn);
9096 return;
9097 }
9098
John McCall47000992010-01-14 03:28:57 +00009099 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9100 assert(CVR && "unexpected qualifiers mismatch");
9101
9102 if (isObjectArgument) {
9103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9104 << (unsigned) FnKind << FnDesc
9105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9106 << FromTy << (CVR - 1);
9107 } else {
9108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9109 << (unsigned) FnKind << FnDesc
9110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9111 << FromTy << (CVR - 1) << I+1;
9112 }
Sebastian Redl08905022011-02-05 19:23:19 +00009113 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009114 return;
9115 }
9116
Sebastian Redla72462c2011-09-24 17:48:32 +00009117 // Special diagnostic for failure to convert an initializer list, since
9118 // telling the user that it has type void is not useful.
9119 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9121 << (unsigned) FnKind << FnDesc
9122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9123 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9124 MaybeEmitInheritedConstructorNote(S, Fn);
9125 return;
9126 }
9127
John McCall6d174642010-01-23 08:10:49 +00009128 // Diagnose references or pointers to incomplete types differently,
9129 // since it's far from impossible that the incompleteness triggered
9130 // the failure.
9131 QualType TempFromTy = FromTy.getNonReferenceType();
9132 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9133 TempFromTy = PTy->getPointeeType();
9134 if (TempFromTy->isIncompleteType()) {
9135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9136 << (unsigned) FnKind << FnDesc
9137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009139 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009140 return;
9141 }
9142
Douglas Gregor56f2e342010-06-30 23:01:39 +00009143 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009144 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009145 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9146 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9147 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9148 FromPtrTy->getPointeeType()) &&
9149 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9150 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009151 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009152 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009153 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009154 }
9155 } else if (const ObjCObjectPointerType *FromPtrTy
9156 = FromTy->getAs<ObjCObjectPointerType>()) {
9157 if (const ObjCObjectPointerType *ToPtrTy
9158 = ToTy->getAs<ObjCObjectPointerType>())
9159 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9160 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9161 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9162 FromPtrTy->getPointeeType()) &&
9163 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009164 BaseToDerivedConversion = 2;
9165 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009166 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9167 !FromTy->isIncompleteType() &&
9168 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009169 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009170 BaseToDerivedConversion = 3;
9171 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9172 ToTy.getNonReferenceType().getCanonicalType() ==
9173 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9175 << (unsigned) FnKind << FnDesc
9176 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9177 << (unsigned) isObjectArgument << I + 1;
9178 MaybeEmitInheritedConstructorNote(S, Fn);
9179 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009180 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009182
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009183 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009184 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009185 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009186 << (unsigned) FnKind << FnDesc
9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009188 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009189 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009190 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009191 return;
9192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009193
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009194 if (isa<ObjCObjectPointerType>(CFromTy) &&
9195 isa<PointerType>(CToTy)) {
9196 Qualifiers FromQs = CFromTy.getQualifiers();
9197 Qualifiers ToQs = CToTy.getQualifiers();
9198 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9200 << (unsigned) FnKind << FnDesc
9201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9202 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9203 MaybeEmitInheritedConstructorNote(S, Fn);
9204 return;
9205 }
9206 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009207
9208 if (TakingCandidateAddress &&
9209 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9210 return;
9211
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009212 // Emit the generic diagnostic and, optionally, add the hints to it.
9213 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9214 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009215 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009216 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9217 << (unsigned) (Cand->Fix.Kind);
9218
9219 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009220 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9221 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009222 FDiag << *HI;
9223 S.Diag(Fn->getLocation(), FDiag);
9224
Sebastian Redl08905022011-02-05 19:23:19 +00009225 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009226}
9227
Larisse Voufo98b20f12013-07-19 23:00:19 +00009228/// Additional arity mismatch diagnosis specific to a function overload
9229/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9230/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009231static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9232 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009233 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009234 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009235
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009236 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009237 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009238 // right number of arguments, because only overloaded operators have
9239 // the weird behavior of overloading member and non-member functions.
9240 // Just don't report anything.
9241 if (Fn->isInvalidDecl() &&
9242 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009243 return true;
9244
9245 if (NumArgs < MinParams) {
9246 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9247 (Cand->FailureKind == ovl_fail_bad_deduction &&
9248 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9249 } else {
9250 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9251 (Cand->FailureKind == ovl_fail_bad_deduction &&
9252 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9253 }
9254
9255 return false;
9256}
9257
9258/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009259static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009260 assert(isa<FunctionDecl>(D) &&
9261 "The templated declaration should at least be a function"
9262 " when diagnosing bad template argument deduction due to too many"
9263 " or too few arguments");
9264
9265 FunctionDecl *Fn = cast<FunctionDecl>(D);
9266
9267 // TODO: treat calls to a missing default constructor as a special case
9268 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9269 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009270
John McCall6a61b522010-01-13 09:16:55 +00009271 // at least / at most / exactly
9272 unsigned mode, modeCount;
9273 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009274 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9275 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009276 mode = 0; // "at least"
9277 else
9278 mode = 2; // "exactly"
9279 modeCount = MinParams;
9280 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009281 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009282 mode = 1; // "at most"
9283 else
9284 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009285 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009286 }
9287
9288 std::string Description;
9289 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9290
Richard Smith10ff50d2012-05-11 05:16:41 +00009291 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009293 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9294 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009295 else
9296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009297 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9298 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009299 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009300}
9301
Larisse Voufo98b20f12013-07-19 23:00:19 +00009302/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009303static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9304 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009305 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9306 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9307}
Larisse Voufo47c08452013-07-19 22:53:23 +00009308
Richard Smith17c00b42014-11-12 01:24:00 +00009309static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009310 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9311 return FD->getDescribedFunctionTemplate();
9312 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9313 return RD->getDescribedClassTemplate();
9314
9315 llvm_unreachable("Unsupported: Getting the described template declaration"
9316 " for bad deduction diagnosis");
9317}
9318
9319/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009320static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9321 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009322 unsigned NumArgs,
9323 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009324 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009325 NamedDecl *ParamD;
9326 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9327 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9328 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009329 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009330 case Sema::TDK_Success:
9331 llvm_unreachable("TDK_success while diagnosing bad deduction");
9332
9333 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009334 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009335 S.Diag(Templated->getLocation(),
9336 diag::note_ovl_candidate_incomplete_deduction)
9337 << ParamD->getDeclName();
9338 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009339 return;
9340 }
9341
John McCall42d7d192010-08-05 09:05:08 +00009342 case Sema::TDK_Underqualified: {
9343 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9344 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9345
Larisse Voufo98b20f12013-07-19 23:00:19 +00009346 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009347
9348 // Param will have been canonicalized, but it should just be a
9349 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009350 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009351 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009352 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009353 assert(S.Context.hasSameType(Param, NonCanonParam));
9354
9355 // Arg has also been canonicalized, but there's nothing we can do
9356 // about that. It also doesn't matter as much, because it won't
9357 // have any template parameters in it (because deduction isn't
9358 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009359 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009360
Larisse Voufo98b20f12013-07-19 23:00:19 +00009361 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9362 << ParamD->getDeclName() << Arg << NonCanonParam;
9363 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009364 return;
9365 }
9366
9367 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009368 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009369 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009370 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009371 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009372 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009373 which = 1;
9374 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009375 which = 2;
9376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009377
Larisse Voufo98b20f12013-07-19 23:00:19 +00009378 S.Diag(Templated->getLocation(),
9379 diag::note_ovl_candidate_inconsistent_deduction)
9380 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9381 << *DeductionFailure.getSecondArg();
9382 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009383 return;
9384 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009385
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009386 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009387 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009388 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009389 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009390 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009391 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009392 else {
9393 int index = 0;
9394 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9395 index = TTP->getIndex();
9396 else if (NonTypeTemplateParmDecl *NTTP
9397 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9398 index = NTTP->getIndex();
9399 else
9400 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009401 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009402 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009403 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009404 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009405 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009406 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009407
Douglas Gregor02eb4832010-05-08 18:13:28 +00009408 case Sema::TDK_TooManyArguments:
9409 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009410 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009411 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009412
9413 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009414 S.Diag(Templated->getLocation(),
9415 diag::note_ovl_candidate_instantiation_depth);
9416 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009417 return;
9418
9419 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009420 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009421 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009422 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009423 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009424 TemplateArgString = " ";
9425 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009426 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009427 }
9428
Richard Smith6f8d2c62012-05-09 05:17:00 +00009429 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009430 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009431 if (PDiag && PDiag->second.getDiagID() ==
9432 diag::err_typename_nested_not_found_enable_if) {
9433 // FIXME: Use the source range of the condition, and the fully-qualified
9434 // name of the enable_if template. These are both present in PDiag.
9435 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9436 << "'enable_if'" << TemplateArgString;
9437 return;
9438 }
9439
Richard Smith9ca64612012-05-07 09:03:25 +00009440 // Format the SFINAE diagnostic into the argument string.
9441 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9442 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009443 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009444 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009445 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009446 SFINAEArgString = ": ";
9447 R = SourceRange(PDiag->first, PDiag->first);
9448 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9449 }
9450
Larisse Voufo98b20f12013-07-19 23:00:19 +00009451 S.Diag(Templated->getLocation(),
9452 diag::note_ovl_candidate_substitution_failure)
9453 << TemplateArgString << SFINAEArgString << R;
9454 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009455 return;
9456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009457
Richard Smith8c6eeb92013-01-31 04:03:12 +00009458 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009459 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9460 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009461 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009462 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009463 return;
9464 }
9465
Richard Smith9b534542015-12-31 02:02:54 +00009466 case Sema::TDK_DeducedMismatch: {
9467 // Format the template argument list into the argument string.
9468 SmallString<128> TemplateArgString;
9469 if (TemplateArgumentList *Args =
9470 DeductionFailure.getTemplateArgumentList()) {
9471 TemplateArgString = " ";
9472 TemplateArgString += S.getTemplateArgumentBindingsText(
9473 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9474 }
9475
9476 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9477 << (*DeductionFailure.getCallArgIndex() + 1)
9478 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9479 << TemplateArgString;
9480 break;
9481 }
9482
Richard Trieue3732352013-04-08 21:11:40 +00009483 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009484 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009485 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9486 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009487 if (FirstTA.getKind() == TemplateArgument::Template &&
9488 SecondTA.getKind() == TemplateArgument::Template) {
9489 TemplateName FirstTN = FirstTA.getAsTemplate();
9490 TemplateName SecondTN = SecondTA.getAsTemplate();
9491 if (FirstTN.getKind() == TemplateName::Template &&
9492 SecondTN.getKind() == TemplateName::Template) {
9493 if (FirstTN.getAsTemplateDecl()->getName() ==
9494 SecondTN.getAsTemplateDecl()->getName()) {
9495 // FIXME: This fixes a bad diagnostic where both templates are named
9496 // the same. This particular case is a bit difficult since:
9497 // 1) It is passed as a string to the diagnostic printer.
9498 // 2) The diagnostic printer only attempts to find a better
9499 // name for types, not decls.
9500 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009501 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009502 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9503 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9504 return;
9505 }
9506 }
9507 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009508
9509 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9510 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9511 return;
9512
Faisal Vali2b391ab2013-09-26 19:54:12 +00009513 // FIXME: For generic lambda parameters, check if the function is a lambda
9514 // call operator, and if so, emit a prettier and more informative
9515 // diagnostic that mentions 'auto' and lambda in addition to
9516 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009517 S.Diag(Templated->getLocation(),
9518 diag::note_ovl_candidate_non_deduced_mismatch)
9519 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009520 return;
Richard Trieue3732352013-04-08 21:11:40 +00009521 }
John McCall8b9ed552010-02-01 18:53:26 +00009522 // TODO: diagnose these individually, then kill off
9523 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009524 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009525 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9526 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009527 return;
9528 }
9529}
9530
Larisse Voufo98b20f12013-07-19 23:00:19 +00009531/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009532static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009533 unsigned NumArgs,
9534 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535 unsigned TDK = Cand->DeductionFailure.Result;
9536 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9537 if (CheckArityMismatch(S, Cand, NumArgs))
9538 return;
9539 }
9540 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009541 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009542}
9543
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009544/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009545static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009546 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9547 FunctionDecl *Callee = Cand->Function;
9548
9549 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9550 CalleeTarget = S.IdentifyCUDATarget(Callee);
9551
9552 std::string FnDesc;
9553 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9554
9555 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009556 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9557
9558 // This could be an implicit constructor for which we could not infer the
9559 // target due to a collsion. Diagnose that case.
9560 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9561 if (Meth != nullptr && Meth->isImplicit()) {
9562 CXXRecordDecl *ParentClass = Meth->getParent();
9563 Sema::CXXSpecialMember CSM;
9564
9565 switch (FnKind) {
9566 default:
9567 return;
9568 case oc_implicit_default_constructor:
9569 CSM = Sema::CXXDefaultConstructor;
9570 break;
9571 case oc_implicit_copy_constructor:
9572 CSM = Sema::CXXCopyConstructor;
9573 break;
9574 case oc_implicit_move_constructor:
9575 CSM = Sema::CXXMoveConstructor;
9576 break;
9577 case oc_implicit_copy_assignment:
9578 CSM = Sema::CXXCopyAssignment;
9579 break;
9580 case oc_implicit_move_assignment:
9581 CSM = Sema::CXXMoveAssignment;
9582 break;
9583 };
9584
9585 bool ConstRHS = false;
9586 if (Meth->getNumParams()) {
9587 if (const ReferenceType *RT =
9588 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9589 ConstRHS = RT->getPointeeType().isConstQualified();
9590 }
9591 }
9592
9593 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9594 /* ConstRHS */ ConstRHS,
9595 /* Diagnose */ true);
9596 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009597}
9598
Richard Smith17c00b42014-11-12 01:24:00 +00009599static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009600 FunctionDecl *Callee = Cand->Function;
9601 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9602
9603 S.Diag(Callee->getLocation(),
9604 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9605 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9606}
9607
John McCall8b9ed552010-02-01 18:53:26 +00009608/// Generates a 'note' diagnostic for an overload candidate. We've
9609/// already generated a primary error at the call site.
9610///
9611/// It really does need to be a single diagnostic with its caret
9612/// pointed at the candidate declaration. Yes, this creates some
9613/// major challenges of technical writing. Yes, this makes pointing
9614/// out problems with specific arguments quite awkward. It's still
9615/// better than generating twenty screens of text for every failed
9616/// overload.
9617///
9618/// It would be great to be able to express per-candidate problems
9619/// more richly for those diagnostic clients that cared, but we'd
9620/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009621static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009622 unsigned NumArgs,
9623 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009624 FunctionDecl *Fn = Cand->Function;
9625
John McCall12f97bc2010-01-08 04:41:39 +00009626 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009627 if (Cand->Viable && (Fn->isDeleted() ||
9628 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009629 std::string FnDesc;
9630 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009631
9632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009633 << FnKind << FnDesc
9634 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009635 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009636 return;
John McCall12f97bc2010-01-08 04:41:39 +00009637 }
9638
John McCalle1ac8d12010-01-13 00:25:19 +00009639 // We don't really have anything else to say about viable candidates.
9640 if (Cand->Viable) {
9641 S.NoteOverloadCandidate(Fn);
9642 return;
9643 }
John McCall0d1da222010-01-12 00:44:57 +00009644
John McCall6a61b522010-01-13 09:16:55 +00009645 switch (Cand->FailureKind) {
9646 case ovl_fail_too_many_arguments:
9647 case ovl_fail_too_few_arguments:
9648 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009649
John McCall6a61b522010-01-13 09:16:55 +00009650 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009651 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009652
John McCall578a1f82014-12-14 01:46:53 +00009653 case ovl_fail_illegal_constructor: {
9654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9655 << (Fn->getPrimaryTemplate() ? 1 : 0);
9656 MaybeEmitInheritedConstructorNote(S, Fn);
9657 return;
9658 }
9659
John McCallfe796dd2010-01-23 05:17:32 +00009660 case ovl_fail_trivial_conversion:
9661 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009662 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009663 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009664
John McCall65eb8792010-02-25 01:37:24 +00009665 case ovl_fail_bad_conversion: {
9666 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009667 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009668 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009669 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009670
John McCall6a61b522010-01-13 09:16:55 +00009671 // FIXME: this currently happens when we're called from SemaInit
9672 // when user-conversion overload fails. Figure out how to handle
9673 // those conditions and diagnose them well.
9674 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009675 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009676
9677 case ovl_fail_bad_target:
9678 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009679
9680 case ovl_fail_enable_if:
9681 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009682
9683 case ovl_fail_addr_not_available: {
9684 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9685 (void)Available;
9686 assert(!Available);
9687 break;
9688 }
John McCall65eb8792010-02-25 01:37:24 +00009689 }
John McCalld3224162010-01-08 00:58:21 +00009690}
9691
Richard Smith17c00b42014-11-12 01:24:00 +00009692static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009693 // Desugar the type of the surrogate down to a function type,
9694 // retaining as many typedefs as possible while still showing
9695 // the function type (and, therefore, its parameter types).
9696 QualType FnType = Cand->Surrogate->getConversionType();
9697 bool isLValueReference = false;
9698 bool isRValueReference = false;
9699 bool isPointer = false;
9700 if (const LValueReferenceType *FnTypeRef =
9701 FnType->getAs<LValueReferenceType>()) {
9702 FnType = FnTypeRef->getPointeeType();
9703 isLValueReference = true;
9704 } else if (const RValueReferenceType *FnTypeRef =
9705 FnType->getAs<RValueReferenceType>()) {
9706 FnType = FnTypeRef->getPointeeType();
9707 isRValueReference = true;
9708 }
9709 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9710 FnType = FnTypePtr->getPointeeType();
9711 isPointer = true;
9712 }
9713 // Desugar down to a function type.
9714 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9715 // Reconstruct the pointer/reference as appropriate.
9716 if (isPointer) FnType = S.Context.getPointerType(FnType);
9717 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9718 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9719
9720 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9721 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009722 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009723}
9724
Richard Smith17c00b42014-11-12 01:24:00 +00009725static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9726 SourceLocation OpLoc,
9727 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009728 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009729 std::string TypeStr("operator");
9730 TypeStr += Opc;
9731 TypeStr += "(";
9732 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009733 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009734 TypeStr += ")";
9735 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9736 } else {
9737 TypeStr += ", ";
9738 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9739 TypeStr += ")";
9740 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9741 }
9742}
9743
Richard Smith17c00b42014-11-12 01:24:00 +00009744static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9745 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009746 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009747 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9748 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009749 if (ICS.isBad()) break; // all meaningless after first invalid
9750 if (!ICS.isAmbiguous()) continue;
9751
John McCall5c32be02010-08-24 20:38:10 +00009752 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009753 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009754 }
9755}
9756
Larisse Voufo98b20f12013-07-19 23:00:19 +00009757static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009758 if (Cand->Function)
9759 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009760 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009761 return Cand->Surrogate->getLocation();
9762 return SourceLocation();
9763}
9764
Larisse Voufo98b20f12013-07-19 23:00:19 +00009765static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009766 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009767 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009768 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009769
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009770 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009771 case Sema::TDK_Incomplete:
9772 return 1;
9773
9774 case Sema::TDK_Underqualified:
9775 case Sema::TDK_Inconsistent:
9776 return 2;
9777
9778 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009779 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009780 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009781 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009782 return 3;
9783
9784 case Sema::TDK_InstantiationDepth:
9785 case Sema::TDK_FailedOverloadResolution:
9786 return 4;
9787
9788 case Sema::TDK_InvalidExplicitArguments:
9789 return 5;
9790
9791 case Sema::TDK_TooManyArguments:
9792 case Sema::TDK_TooFewArguments:
9793 return 6;
9794 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009795 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009796}
9797
Richard Smith17c00b42014-11-12 01:24:00 +00009798namespace {
John McCallad2587a2010-01-12 00:48:53 +00009799struct CompareOverloadCandidatesForDisplay {
9800 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009801 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009802 size_t NumArgs;
9803
Richard Smith0f59cb32015-12-18 21:45:41 +00009804 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009805 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009806
9807 bool operator()(const OverloadCandidate *L,
9808 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009809 // Fast-path this check.
9810 if (L == R) return false;
9811
John McCall12f97bc2010-01-08 04:41:39 +00009812 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009813 if (L->Viable) {
9814 if (!R->Viable) return true;
9815
9816 // TODO: introduce a tri-valued comparison for overload
9817 // candidates. Would be more worthwhile if we had a sort
9818 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009819 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9820 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009821 } else if (R->Viable)
9822 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009823
John McCall3712d9e2010-01-15 23:32:50 +00009824 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009825
John McCall3712d9e2010-01-15 23:32:50 +00009826 // Criteria by which we can sort non-viable candidates:
9827 if (!L->Viable) {
9828 // 1. Arity mismatches come after other candidates.
9829 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009830 L->FailureKind == ovl_fail_too_few_arguments) {
9831 if (R->FailureKind == ovl_fail_too_many_arguments ||
9832 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009833 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9834 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9835 if (LDist == RDist) {
9836 if (L->FailureKind == R->FailureKind)
9837 // Sort non-surrogates before surrogates.
9838 return !L->IsSurrogate && R->IsSurrogate;
9839 // Sort candidates requiring fewer parameters than there were
9840 // arguments given after candidates requiring more parameters
9841 // than there were arguments given.
9842 return L->FailureKind == ovl_fail_too_many_arguments;
9843 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009844 return LDist < RDist;
9845 }
John McCall3712d9e2010-01-15 23:32:50 +00009846 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009847 }
John McCall3712d9e2010-01-15 23:32:50 +00009848 if (R->FailureKind == ovl_fail_too_many_arguments ||
9849 R->FailureKind == ovl_fail_too_few_arguments)
9850 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009851
John McCallfe796dd2010-01-23 05:17:32 +00009852 // 2. Bad conversions come first and are ordered by the number
9853 // of bad conversions and quality of good conversions.
9854 if (L->FailureKind == ovl_fail_bad_conversion) {
9855 if (R->FailureKind != ovl_fail_bad_conversion)
9856 return true;
9857
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009858 // The conversion that can be fixed with a smaller number of changes,
9859 // comes first.
9860 unsigned numLFixes = L->Fix.NumConversionsFixed;
9861 unsigned numRFixes = R->Fix.NumConversionsFixed;
9862 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9863 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009864 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009865 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009866 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009867
John McCallfe796dd2010-01-23 05:17:32 +00009868 // If there's any ordering between the defined conversions...
9869 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009870 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009871
9872 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009873 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009874 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009875 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009876 L->Conversions[I],
9877 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009878 case ImplicitConversionSequence::Better:
9879 leftBetter++;
9880 break;
9881
9882 case ImplicitConversionSequence::Worse:
9883 leftBetter--;
9884 break;
9885
9886 case ImplicitConversionSequence::Indistinguishable:
9887 break;
9888 }
9889 }
9890 if (leftBetter > 0) return true;
9891 if (leftBetter < 0) return false;
9892
9893 } else if (R->FailureKind == ovl_fail_bad_conversion)
9894 return false;
9895
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009896 if (L->FailureKind == ovl_fail_bad_deduction) {
9897 if (R->FailureKind != ovl_fail_bad_deduction)
9898 return true;
9899
9900 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9901 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009902 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009903 } else if (R->FailureKind == ovl_fail_bad_deduction)
9904 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009905
John McCall3712d9e2010-01-15 23:32:50 +00009906 // TODO: others?
9907 }
9908
9909 // Sort everything else by location.
9910 SourceLocation LLoc = GetLocationForCandidate(L);
9911 SourceLocation RLoc = GetLocationForCandidate(R);
9912
9913 // Put candidates without locations (e.g. builtins) at the end.
9914 if (LLoc.isInvalid()) return false;
9915 if (RLoc.isInvalid()) return true;
9916
9917 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009918 }
9919};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009920}
John McCall12f97bc2010-01-08 04:41:39 +00009921
John McCallfe796dd2010-01-23 05:17:32 +00009922/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009923/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009924static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9925 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009926 assert(!Cand->Viable);
9927
9928 // Don't do anything on failures other than bad conversion.
9929 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9930
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009931 // We only want the FixIts if all the arguments can be corrected.
9932 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009933 // Use a implicit copy initialization to check conversion fixes.
9934 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009935
John McCallfe796dd2010-01-23 05:17:32 +00009936 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009937 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009938 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009939 while (true) {
9940 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9941 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009942 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009943 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009944 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009945 }
John McCallfe796dd2010-01-23 05:17:32 +00009946 }
9947
9948 if (ConvIdx == ConvCount)
9949 return;
9950
John McCall65eb8792010-02-25 01:37:24 +00009951 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9952 "remaining conversion is initialized?");
9953
Douglas Gregoradc7a702010-04-16 17:45:54 +00009954 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009955 // operation somehow.
9956 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009957
9958 const FunctionProtoType* Proto;
9959 unsigned ArgIdx = ConvIdx;
9960
9961 if (Cand->IsSurrogate) {
9962 QualType ConvType
9963 = Cand->Surrogate->getConversionType().getNonReferenceType();
9964 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9965 ConvType = ConvPtrType->getPointeeType();
9966 Proto = ConvType->getAs<FunctionProtoType>();
9967 ArgIdx--;
9968 } else if (Cand->Function) {
9969 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9970 if (isa<CXXMethodDecl>(Cand->Function) &&
9971 !isa<CXXConstructorDecl>(Cand->Function))
9972 ArgIdx--;
9973 } else {
9974 // Builtin binary operator with a bad first conversion.
9975 assert(ConvCount <= 3);
9976 for (; ConvIdx != ConvCount; ++ConvIdx)
9977 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009978 = TryCopyInitialization(S, Args[ConvIdx],
9979 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009980 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009981 /*InOverloadResolution*/ true,
9982 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009983 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009984 return;
9985 }
9986
9987 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009988 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009989 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009990 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009991 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9992 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9993 /*InOverloadResolution=*/true,
9994 /*AllowObjCWritebackConversion=*/
9995 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009996 // Store the FixIt in the candidate if it exists.
9997 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009998 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009999 }
John McCallfe796dd2010-01-23 05:17:32 +000010000 else
10001 Cand->Conversions[ConvIdx].setEllipsis();
10002 }
10003}
10004
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010005/// PrintOverloadCandidates - When overload resolution fails, prints
10006/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010007/// set.
John McCall5c32be02010-08-24 20:38:10 +000010008void OverloadCandidateSet::NoteCandidates(Sema &S,
10009 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010010 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010011 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010012 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010013 // Sort the candidates by viability and position. Sorting directly would
10014 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010015 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010016 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10017 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010018 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010019 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010020 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010021 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010022 if (Cand->Function || Cand->IsSurrogate)
10023 Cands.push_back(Cand);
10024 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10025 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010026 }
10027 }
10028
John McCallad2587a2010-01-12 00:48:53 +000010029 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010030 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010031
John McCall0d1da222010-01-12 00:44:57 +000010032 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010033
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010034 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010035 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010036 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010037 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10038 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010039
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010040 // Set an arbitrary limit on the number of candidate functions we'll spam
10041 // the user with. FIXME: This limit should depend on details of the
10042 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010043 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010044 break;
10045 }
10046 ++CandsShown;
10047
John McCalld3224162010-01-08 00:58:21 +000010048 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010049 NoteFunctionCandidate(S, Cand, Args.size(),
10050 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010051 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010052 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010053 else {
10054 assert(Cand->Viable &&
10055 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010056 // Generally we only see ambiguities including viable builtin
10057 // operators if overload resolution got screwed up by an
10058 // ambiguous user-defined conversion.
10059 //
10060 // FIXME: It's quite possible for different conversions to see
10061 // different ambiguities, though.
10062 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010063 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010064 ReportedAmbiguousConversions = true;
10065 }
John McCalld3224162010-01-08 00:58:21 +000010066
John McCall0d1da222010-01-12 00:44:57 +000010067 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010068 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010069 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010070 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010071
10072 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010073 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010074}
10075
Larisse Voufo98b20f12013-07-19 23:00:19 +000010076static SourceLocation
10077GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10078 return Cand->Specialization ? Cand->Specialization->getLocation()
10079 : SourceLocation();
10080}
10081
Richard Smith17c00b42014-11-12 01:24:00 +000010082namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010083struct CompareTemplateSpecCandidatesForDisplay {
10084 Sema &S;
10085 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10086
10087 bool operator()(const TemplateSpecCandidate *L,
10088 const TemplateSpecCandidate *R) {
10089 // Fast-path this check.
10090 if (L == R)
10091 return false;
10092
10093 // Assuming that both candidates are not matches...
10094
10095 // Sort by the ranking of deduction failures.
10096 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10097 return RankDeductionFailure(L->DeductionFailure) <
10098 RankDeductionFailure(R->DeductionFailure);
10099
10100 // Sort everything else by location.
10101 SourceLocation LLoc = GetLocationForCandidate(L);
10102 SourceLocation RLoc = GetLocationForCandidate(R);
10103
10104 // Put candidates without locations (e.g. builtins) at the end.
10105 if (LLoc.isInvalid())
10106 return false;
10107 if (RLoc.isInvalid())
10108 return true;
10109
10110 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10111 }
10112};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010113}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010114
10115/// Diagnose a template argument deduction failure.
10116/// We are treating these failures as overload failures due to bad
10117/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010118void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10119 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010120 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010121 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010122}
10123
10124void TemplateSpecCandidateSet::destroyCandidates() {
10125 for (iterator i = begin(), e = end(); i != e; ++i) {
10126 i->DeductionFailure.Destroy();
10127 }
10128}
10129
10130void TemplateSpecCandidateSet::clear() {
10131 destroyCandidates();
10132 Candidates.clear();
10133}
10134
10135/// NoteCandidates - When no template specialization match is found, prints
10136/// diagnostic messages containing the non-matching specializations that form
10137/// the candidate set.
10138/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10139/// OCD == OCD_AllCandidates and Cand->Viable == false.
10140void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10141 // Sort the candidates by position (assuming no candidate is a match).
10142 // Sorting directly would be prohibitive, so we make a set of pointers
10143 // and sort those.
10144 SmallVector<TemplateSpecCandidate *, 32> Cands;
10145 Cands.reserve(size());
10146 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10147 if (Cand->Specialization)
10148 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010149 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010150 // in general, want to list every possible builtin candidate.
10151 }
10152
10153 std::sort(Cands.begin(), Cands.end(),
10154 CompareTemplateSpecCandidatesForDisplay(S));
10155
10156 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10157 // for generalization purposes (?).
10158 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10159
10160 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10161 unsigned CandsShown = 0;
10162 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10163 TemplateSpecCandidate *Cand = *I;
10164
10165 // Set an arbitrary limit on the number of candidates we'll spam
10166 // the user with. FIXME: This limit should depend on details of the
10167 // candidate list.
10168 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10169 break;
10170 ++CandsShown;
10171
10172 assert(Cand->Specialization &&
10173 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010174 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010175 }
10176
10177 if (I != E)
10178 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10179}
10180
Douglas Gregorb491ed32011-02-19 21:32:49 +000010181// [PossiblyAFunctionType] --> [Return]
10182// NonFunctionType --> NonFunctionType
10183// R (A) --> R(A)
10184// R (*)(A) --> R (A)
10185// R (&)(A) --> R (A)
10186// R (S::*)(A) --> R (A)
10187QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10188 QualType Ret = PossiblyAFunctionType;
10189 if (const PointerType *ToTypePtr =
10190 PossiblyAFunctionType->getAs<PointerType>())
10191 Ret = ToTypePtr->getPointeeType();
10192 else if (const ReferenceType *ToTypeRef =
10193 PossiblyAFunctionType->getAs<ReferenceType>())
10194 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010195 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010196 PossiblyAFunctionType->getAs<MemberPointerType>())
10197 Ret = MemTypePtr->getPointeeType();
10198 Ret =
10199 Context.getCanonicalType(Ret).getUnqualifiedType();
10200 return Ret;
10201}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010202
Richard Smith17c00b42014-11-12 01:24:00 +000010203namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010204// A helper class to help with address of function resolution
10205// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010206class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010207 Sema& S;
10208 Expr* SourceExpr;
10209 const QualType& TargetType;
10210 QualType TargetFunctionType; // Extracted function type from target type
10211
10212 bool Complain;
10213 //DeclAccessPair& ResultFunctionAccessPair;
10214 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010215
Douglas Gregorb491ed32011-02-19 21:32:49 +000010216 bool TargetTypeIsNonStaticMemberFunction;
10217 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010218 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010219 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010220
Douglas Gregorb491ed32011-02-19 21:32:49 +000010221 OverloadExpr::FindResult OvlExprInfo;
10222 OverloadExpr *OvlExpr;
10223 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010224 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010225 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010226
Douglas Gregorb491ed32011-02-19 21:32:49 +000010227public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010228 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10229 const QualType &TargetType, bool Complain)
10230 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10231 Complain(Complain), Context(S.getASTContext()),
10232 TargetTypeIsNonStaticMemberFunction(
10233 !!TargetType->getAs<MemberPointerType>()),
10234 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010235 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010236 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010237 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10238 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010239 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010240 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010241
David Majnemera4f7c7a2013-08-01 06:13:59 +000010242 if (TargetFunctionType->isFunctionType()) {
10243 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10244 if (!UME->isImplicitAccess() &&
10245 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10246 StaticMemberFunctionFromBoundPointer = true;
10247 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10248 DeclAccessPair dap;
10249 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10250 OvlExpr, false, &dap)) {
10251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10252 if (!Method->isStatic()) {
10253 // If the target type is a non-function type and the function found
10254 // is a non-static member function, pretend as if that was the
10255 // target, it's the only possible type to end up with.
10256 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010257
David Majnemera4f7c7a2013-08-01 06:13:59 +000010258 // And skip adding the function if its not in the proper form.
10259 // We'll diagnose this due to an empty set of functions.
10260 if (!OvlExprInfo.HasFormOfMemberPointer)
10261 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010262 }
10263
David Majnemera4f7c7a2013-08-01 06:13:59 +000010264 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010265 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010266 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010267 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010268
10269 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010270 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010271
Douglas Gregorb491ed32011-02-19 21:32:49 +000010272 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10273 // C++ [over.over]p4:
10274 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010275 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010276 if (FoundNonTemplateFunction)
10277 EliminateAllTemplateMatches();
10278 else
10279 EliminateAllExceptMostSpecializedTemplate();
10280 }
10281 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010282
10283 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10284 Matches.size() > 1)
10285 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010286 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010287
10288 bool hasComplained() const { return HasComplained; }
10289
Douglas Gregorb491ed32011-02-19 21:32:49 +000010290private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010291 // Is A considered a better overload candidate for the desired type than B?
10292 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10293 return hasBetterEnableIfAttrs(S, A, B);
10294 }
10295
10296 // Returns true if we've eliminated any (read: all but one) candidates, false
10297 // otherwise.
10298 bool eliminiateSuboptimalOverloadCandidates() {
10299 // Same algorithm as overload resolution -- one pass to pick the "best",
10300 // another pass to be sure that nothing is better than the best.
10301 auto Best = Matches.begin();
10302 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10303 if (isBetterCandidate(I->second, Best->second))
10304 Best = I;
10305
10306 const FunctionDecl *BestFn = Best->second;
10307 auto IsBestOrInferiorToBest = [this, BestFn](
10308 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10309 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10310 };
10311
10312 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10313 // option, so we can potentially give the user a better error
10314 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10315 return false;
10316 Matches[0] = *Best;
10317 Matches.resize(1);
10318 return true;
10319 }
10320
Douglas Gregorb491ed32011-02-19 21:32:49 +000010321 bool isTargetTypeAFunction() const {
10322 return TargetFunctionType->isFunctionType();
10323 }
10324
10325 // [ToType] [Return]
10326
10327 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10328 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10329 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10330 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10331 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10332 }
10333
10334 // return true if any matching specializations were found
10335 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10336 const DeclAccessPair& CurAccessFunPair) {
10337 if (CXXMethodDecl *Method
10338 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10339 // Skip non-static function templates when converting to pointer, and
10340 // static when converting to member pointer.
10341 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10342 return false;
10343 }
10344 else if (TargetTypeIsNonStaticMemberFunction)
10345 return false;
10346
10347 // C++ [over.over]p2:
10348 // If the name is a function template, template argument deduction is
10349 // done (14.8.2.2), and if the argument deduction succeeds, the
10350 // resulting template argument list is used to generate a single
10351 // function template specialization, which is added to the set of
10352 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010353 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010354 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010355 if (Sema::TemplateDeductionResult Result
10356 = S.DeduceTemplateArguments(FunctionTemplate,
10357 &OvlExplicitTemplateArgs,
10358 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010359 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010360 // Make a note of the failed deduction for diagnostics.
10361 FailedCandidates.addCandidate()
10362 .set(FunctionTemplate->getTemplatedDecl(),
10363 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010364 return false;
10365 }
10366
Douglas Gregor19a41f12013-04-17 08:45:07 +000010367 // Template argument deduction ensures that we have an exact match or
10368 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010369 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010370 assert(S.isSameOrCompatibleFunctionType(
10371 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010372 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010373
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010374 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010375 return false;
10376
Douglas Gregorb491ed32011-02-19 21:32:49 +000010377 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10378 return true;
10379 }
10380
10381 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10382 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010384 // Skip non-static functions when converting to pointer, and static
10385 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010386 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10387 return false;
10388 }
10389 else if (TargetTypeIsNonStaticMemberFunction)
10390 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010391
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010392 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010393 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010394 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010395 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010396 return false;
10397
Richard Smith2a7d4812013-05-04 07:00:32 +000010398 // If any candidate has a placeholder return type, trigger its deduction
10399 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010400 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010401 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010402 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10403 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010404 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010405 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010406
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010407 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010408 return false;
10409
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010410 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010411 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10412 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010413 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010414 ResultTy) ||
10415 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10416 Matches.push_back(std::make_pair(
10417 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010418 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010419 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010420 }
Mike Stump11289f42009-09-09 15:08:12 +000010421 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010422
10423 return false;
10424 }
10425
10426 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10427 bool Ret = false;
10428
10429 // If the overload expression doesn't have the form of a pointer to
10430 // member, don't try to convert it to a pointer-to-member type.
10431 if (IsInvalidFormOfPointerToMemberFunction())
10432 return false;
10433
10434 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10435 E = OvlExpr->decls_end();
10436 I != E; ++I) {
10437 // Look through any using declarations to find the underlying function.
10438 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10439
10440 // C++ [over.over]p3:
10441 // Non-member functions and static member functions match
10442 // targets of type "pointer-to-function" or "reference-to-function."
10443 // Nonstatic member functions match targets of
10444 // type "pointer-to-member-function."
10445 // Note that according to DR 247, the containing class does not matter.
10446 if (FunctionTemplateDecl *FunctionTemplate
10447 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10448 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10449 Ret = true;
10450 }
10451 // If we have explicit template arguments supplied, skip non-templates.
10452 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10453 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10454 Ret = true;
10455 }
10456 assert(Ret || Matches.empty());
10457 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010458 }
10459
Douglas Gregorb491ed32011-02-19 21:32:49 +000010460 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010461 // [...] and any given function template specialization F1 is
10462 // eliminated if the set contains a second function template
10463 // specialization whose function template is more specialized
10464 // than the function template of F1 according to the partial
10465 // ordering rules of 14.5.5.2.
10466
10467 // The algorithm specified above is quadratic. We instead use a
10468 // two-pass algorithm (similar to the one used to identify the
10469 // best viable function in an overload set) that identifies the
10470 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010471
10472 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10473 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10474 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010475
Larisse Voufo98b20f12013-07-19 23:00:19 +000010476 // TODO: It looks like FailedCandidates does not serve much purpose
10477 // here, since the no_viable diagnostic has index 0.
10478 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010479 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010480 SourceExpr->getLocStart(), S.PDiag(),
10481 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10482 .second->getDeclName(),
10483 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10484 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010485
Douglas Gregorb491ed32011-02-19 21:32:49 +000010486 if (Result != MatchesCopy.end()) {
10487 // Make it the first and only element
10488 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10489 Matches[0].second = cast<FunctionDecl>(*Result);
10490 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010491 } else
10492 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010494
Douglas Gregorb491ed32011-02-19 21:32:49 +000010495 void EliminateAllTemplateMatches() {
10496 // [...] any function template specializations in the set are
10497 // eliminated if the set also contains a non-template function, [...]
10498 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010499 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010500 ++I;
10501 else {
10502 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010503 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010504 }
10505 }
10506 }
10507
Artem Belevich94a55e82015-09-22 17:22:59 +000010508 void EliminateSuboptimalCudaMatches() {
10509 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10510 }
10511
Douglas Gregorb491ed32011-02-19 21:32:49 +000010512public:
10513 void ComplainNoMatchesFound() const {
10514 assert(Matches.empty());
10515 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10516 << OvlExpr->getName() << TargetFunctionType
10517 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010518 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010519 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10520 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010521 else {
10522 // We have some deduction failure messages. Use them to diagnose
10523 // the function templates, and diagnose the non-template candidates
10524 // normally.
10525 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10526 IEnd = OvlExpr->decls_end();
10527 I != IEnd; ++I)
10528 if (FunctionDecl *Fun =
10529 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010530 if (!functionHasPassObjectSizeParams(Fun))
10531 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10532 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010533 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10534 }
10535 }
10536
Douglas Gregorb491ed32011-02-19 21:32:49 +000010537 bool IsInvalidFormOfPointerToMemberFunction() const {
10538 return TargetTypeIsNonStaticMemberFunction &&
10539 !OvlExprInfo.HasFormOfMemberPointer;
10540 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010541
Douglas Gregorb491ed32011-02-19 21:32:49 +000010542 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10543 // TODO: Should we condition this on whether any functions might
10544 // have matched, or is it more appropriate to do that in callers?
10545 // TODO: a fixit wouldn't hurt.
10546 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10547 << TargetType << OvlExpr->getSourceRange();
10548 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010549
10550 bool IsStaticMemberFunctionFromBoundPointer() const {
10551 return StaticMemberFunctionFromBoundPointer;
10552 }
10553
10554 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10555 S.Diag(OvlExpr->getLocStart(),
10556 diag::err_invalid_form_pointer_member_function)
10557 << OvlExpr->getSourceRange();
10558 }
10559
Douglas Gregorb491ed32011-02-19 21:32:49 +000010560 void ComplainOfInvalidConversion() const {
10561 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10562 << OvlExpr->getName() << TargetType;
10563 }
10564
10565 void ComplainMultipleMatchesFound() const {
10566 assert(Matches.size() > 1);
10567 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10568 << OvlExpr->getName()
10569 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010570 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10571 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010572 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010573
10574 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10575
Douglas Gregorb491ed32011-02-19 21:32:49 +000010576 int getNumMatches() const { return Matches.size(); }
10577
10578 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010579 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010580 return Matches[0].second;
10581 }
10582
10583 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010584 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010585 return &Matches[0].first;
10586 }
10587};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010588}
Richard Smith17c00b42014-11-12 01:24:00 +000010589
Douglas Gregorb491ed32011-02-19 21:32:49 +000010590/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10591/// an overloaded function (C++ [over.over]), where @p From is an
10592/// expression with overloaded function type and @p ToType is the type
10593/// we're trying to resolve to. For example:
10594///
10595/// @code
10596/// int f(double);
10597/// int f(int);
10598///
10599/// int (*pfd)(double) = f; // selects f(double)
10600/// @endcode
10601///
10602/// This routine returns the resulting FunctionDecl if it could be
10603/// resolved, and NULL otherwise. When @p Complain is true, this
10604/// routine will emit diagnostics if there is an error.
10605FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010606Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10607 QualType TargetType,
10608 bool Complain,
10609 DeclAccessPair &FoundResult,
10610 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010611 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010612
10613 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10614 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010615 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010616 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010617 bool ShouldComplain = Complain && !Resolver.hasComplained();
10618 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010619 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10620 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10621 else
10622 Resolver.ComplainNoMatchesFound();
10623 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010624 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010625 Resolver.ComplainMultipleMatchesFound();
10626 else if (NumMatches == 1) {
10627 Fn = Resolver.getMatchingFunctionDecl();
10628 assert(Fn);
10629 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010630 if (Complain) {
10631 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10632 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10633 else
10634 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10635 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010636 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010637
10638 if (pHadMultipleCandidates)
10639 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010640 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010641}
10642
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010643/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010644/// resolve that overloaded function expression down to a single function.
10645///
10646/// This routine can only resolve template-ids that refer to a single function
10647/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010648/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010649/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010650///
10651/// If no template-ids are found, no diagnostics are emitted and NULL is
10652/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010653FunctionDecl *
10654Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10655 bool Complain,
10656 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010657 // C++ [over.over]p1:
10658 // [...] [Note: any redundant set of parentheses surrounding the
10659 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010660 // C++ [over.over]p1:
10661 // [...] The overloaded function name can be preceded by the &
10662 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010663
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010664 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010665 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010666 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010667
10668 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010669 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010670 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010671
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010672 // Look through all of the overloaded functions, searching for one
10673 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010674 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010675 for (UnresolvedSetIterator I = ovl->decls_begin(),
10676 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010677 // C++0x [temp.arg.explicit]p3:
10678 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010679 // where deduction is not done, if a template argument list is
10680 // specified and it, along with any default template arguments,
10681 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010682 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010683 FunctionTemplateDecl *FunctionTemplate
10684 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010685
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010686 // C++ [over.over]p2:
10687 // If the name is a function template, template argument deduction is
10688 // done (14.8.2.2), and if the argument deduction succeeds, the
10689 // resulting template argument list is used to generate a single
10690 // function template specialization, which is added to the set of
10691 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010692 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010693 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010694 if (TemplateDeductionResult Result
10695 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010696 Specialization, Info,
10697 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010698 // Make a note of the failed deduction for diagnostics.
10699 // TODO: Actually use the failed-deduction info?
10700 FailedCandidates.addCandidate()
10701 .set(FunctionTemplate->getTemplatedDecl(),
10702 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010704 }
10705
John McCall0009fcc2011-04-26 20:42:42 +000010706 assert(Specialization && "no specialization and no error?");
10707
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010708 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010709 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010710 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010711 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10712 << ovl->getName();
10713 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010714 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010715 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010716 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010717
John McCall0009fcc2011-04-26 20:42:42 +000010718 Matched = Specialization;
10719 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010721
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010722 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010723 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010724 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010725 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010726
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010727 return Matched;
10728}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010729
Douglas Gregor1beec452011-03-12 01:48:56 +000010730
10731
10732
John McCall50a2c2c2011-10-11 23:14:30 +000010733// Resolve and fix an overloaded expression that can be resolved
10734// because it identifies a single function template specialization.
10735//
Douglas Gregor1beec452011-03-12 01:48:56 +000010736// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010737//
10738// Return true if it was logically possible to so resolve the
10739// expression, regardless of whether or not it succeeded. Always
10740// returns true if 'complain' is set.
10741bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10742 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010743 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010744 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010745 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010746 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010747
John McCall50a2c2c2011-10-11 23:14:30 +000010748 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010749
John McCall0009fcc2011-04-26 20:42:42 +000010750 DeclAccessPair found;
10751 ExprResult SingleFunctionExpression;
10752 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10753 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010754 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010755 SrcExpr = ExprError();
10756 return true;
10757 }
John McCall0009fcc2011-04-26 20:42:42 +000010758
10759 // It is only correct to resolve to an instance method if we're
10760 // resolving a form that's permitted to be a pointer to member.
10761 // Otherwise we'll end up making a bound member expression, which
10762 // is illegal in all the contexts we resolve like this.
10763 if (!ovl.HasFormOfMemberPointer &&
10764 isa<CXXMethodDecl>(fn) &&
10765 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010766 if (!complain) return false;
10767
10768 Diag(ovl.Expression->getExprLoc(),
10769 diag::err_bound_member_function)
10770 << 0 << ovl.Expression->getSourceRange();
10771
10772 // TODO: I believe we only end up here if there's a mix of
10773 // static and non-static candidates (otherwise the expression
10774 // would have 'bound member' type, not 'overload' type).
10775 // Ideally we would note which candidate was chosen and why
10776 // the static candidates were rejected.
10777 SrcExpr = ExprError();
10778 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010779 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010780
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010781 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010782 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010783 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010784
10785 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010786 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010787 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010788 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010789 if (SingleFunctionExpression.isInvalid()) {
10790 SrcExpr = ExprError();
10791 return true;
10792 }
10793 }
John McCall0009fcc2011-04-26 20:42:42 +000010794 }
10795
10796 if (!SingleFunctionExpression.isUsable()) {
10797 if (complain) {
10798 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10799 << ovl.Expression->getName()
10800 << DestTypeForComplaining
10801 << OpRangeForComplaining
10802 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010803 NoteAllOverloadCandidates(SrcExpr.get());
10804
10805 SrcExpr = ExprError();
10806 return true;
10807 }
10808
10809 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010810 }
10811
John McCall50a2c2c2011-10-11 23:14:30 +000010812 SrcExpr = SingleFunctionExpression;
10813 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010814}
10815
Douglas Gregorcabea402009-09-22 15:41:20 +000010816/// \brief Add a single candidate to the overload set.
10817static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010818 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010819 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010820 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010821 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010822 bool PartialOverloading,
10823 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010824 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010825 if (isa<UsingShadowDecl>(Callee))
10826 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10827
Douglas Gregorcabea402009-09-22 15:41:20 +000010828 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010829 if (ExplicitTemplateArgs) {
10830 assert(!KnownValid && "Explicit template arguments?");
10831 return;
10832 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010833 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10834 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010835 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010836 return;
John McCalld14a8642009-11-21 08:51:07 +000010837 }
10838
10839 if (FunctionTemplateDecl *FuncTemplate
10840 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010841 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010842 ExplicitTemplateArgs, Args, CandidateSet,
10843 /*SuppressUsedConversions=*/false,
10844 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010845 return;
10846 }
10847
Richard Smith95ce4f62011-06-26 22:19:54 +000010848 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010849}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010850
Douglas Gregorcabea402009-09-22 15:41:20 +000010851/// \brief Add the overload candidates named by callee and/or found by argument
10852/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010853void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010854 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010855 OverloadCandidateSet &CandidateSet,
10856 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010857
10858#ifndef NDEBUG
10859 // Verify that ArgumentDependentLookup is consistent with the rules
10860 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010861 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010862 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10863 // and let Y be the lookup set produced by argument dependent
10864 // lookup (defined as follows). If X contains
10865 //
10866 // -- a declaration of a class member, or
10867 //
10868 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010869 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010870 //
10871 // -- a declaration that is neither a function or a function
10872 // template
10873 //
10874 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010875
John McCall57500772009-12-16 12:17:52 +000010876 if (ULE->requiresADL()) {
10877 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10878 E = ULE->decls_end(); I != E; ++I) {
10879 assert(!(*I)->getDeclContext()->isRecord());
10880 assert(isa<UsingShadowDecl>(*I) ||
10881 !(*I)->getDeclContext()->isFunctionOrMethod());
10882 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010883 }
10884 }
10885#endif
10886
John McCall57500772009-12-16 12:17:52 +000010887 // It would be nice to avoid this copy.
10888 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010889 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010890 if (ULE->hasExplicitTemplateArgs()) {
10891 ULE->copyTemplateArgumentsInto(TABuffer);
10892 ExplicitTemplateArgs = &TABuffer;
10893 }
10894
10895 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10896 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010897 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10898 CandidateSet, PartialOverloading,
10899 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010900
John McCall57500772009-12-16 12:17:52 +000010901 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010902 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010903 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010904 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010905}
John McCalld681c392009-12-16 08:11:27 +000010906
Richard Smith0603bbb2013-06-12 22:56:54 +000010907/// Determine whether a declaration with the specified name could be moved into
10908/// a different namespace.
10909static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10910 switch (Name.getCXXOverloadedOperator()) {
10911 case OO_New: case OO_Array_New:
10912 case OO_Delete: case OO_Array_Delete:
10913 return false;
10914
10915 default:
10916 return true;
10917 }
10918}
10919
Richard Smith998a5912011-06-05 22:42:48 +000010920/// Attempt to recover from an ill-formed use of a non-dependent name in a
10921/// template, where the non-dependent name was declared after the template
10922/// was defined. This is common in code written for a compilers which do not
10923/// correctly implement two-stage name lookup.
10924///
10925/// Returns true if a viable candidate was found and a diagnostic was issued.
10926static bool
10927DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10928 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010929 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010930 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010931 ArrayRef<Expr *> Args,
10932 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010933 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10934 return false;
10935
10936 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010937 if (DC->isTransparentContext())
10938 continue;
10939
Richard Smith998a5912011-06-05 22:42:48 +000010940 SemaRef.LookupQualifiedName(R, DC);
10941
10942 if (!R.empty()) {
10943 R.suppressDiagnostics();
10944
10945 if (isa<CXXRecordDecl>(DC)) {
10946 // Don't diagnose names we find in classes; we get much better
10947 // diagnostics for these from DiagnoseEmptyLookup.
10948 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010949 if (DoDiagnoseEmptyLookup)
10950 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010951 return false;
10952 }
10953
Richard Smith100b24a2014-04-17 01:52:14 +000010954 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10956 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010957 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010958 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010959
10960 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010961 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010962 // No viable functions. Don't bother the user with notes for functions
10963 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010964 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010965 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010966 }
Richard Smith998a5912011-06-05 22:42:48 +000010967
10968 // Find the namespaces where ADL would have looked, and suggest
10969 // declaring the function there instead.
10970 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10971 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010972 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010973 AssociatedNamespaces,
10974 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010975 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010976 if (canBeDeclaredInNamespace(R.getLookupName())) {
10977 DeclContext *Std = SemaRef.getStdNamespace();
10978 for (Sema::AssociatedNamespaceSet::iterator
10979 it = AssociatedNamespaces.begin(),
10980 end = AssociatedNamespaces.end(); it != end; ++it) {
10981 // Never suggest declaring a function within namespace 'std'.
10982 if (Std && Std->Encloses(*it))
10983 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010984
Richard Smith0603bbb2013-06-12 22:56:54 +000010985 // Never suggest declaring a function within a namespace with a
10986 // reserved name, like __gnu_cxx.
10987 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10988 if (NS &&
10989 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10990 continue;
10991
10992 SuggestedNamespaces.insert(*it);
10993 }
Richard Smith998a5912011-06-05 22:42:48 +000010994 }
10995
10996 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10997 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010998 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010999 SemaRef.Diag(Best->Function->getLocation(),
11000 diag::note_not_found_by_two_phase_lookup)
11001 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011002 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011003 SemaRef.Diag(Best->Function->getLocation(),
11004 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011005 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011006 } else {
11007 // FIXME: It would be useful to list the associated namespaces here,
11008 // but the diagnostics infrastructure doesn't provide a way to produce
11009 // a localized representation of a list of items.
11010 SemaRef.Diag(Best->Function->getLocation(),
11011 diag::note_not_found_by_two_phase_lookup)
11012 << R.getLookupName() << 2;
11013 }
11014
11015 // Try to recover by calling this function.
11016 return true;
11017 }
11018
11019 R.clear();
11020 }
11021
11022 return false;
11023}
11024
11025/// Attempt to recover from ill-formed use of a non-dependent operator in a
11026/// template, where the non-dependent operator was declared after the template
11027/// was defined.
11028///
11029/// Returns true if a viable candidate was found and a diagnostic was issued.
11030static bool
11031DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11032 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011033 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011034 DeclarationName OpName =
11035 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11036 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11037 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011038 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011039 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011040}
11041
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011042namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011043class BuildRecoveryCallExprRAII {
11044 Sema &SemaRef;
11045public:
11046 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11047 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11048 SemaRef.IsBuildingRecoveryCallExpr = true;
11049 }
11050
11051 ~BuildRecoveryCallExprRAII() {
11052 SemaRef.IsBuildingRecoveryCallExpr = false;
11053 }
11054};
11055
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011056}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011057
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011058static std::unique_ptr<CorrectionCandidateCallback>
11059MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11060 bool HasTemplateArgs, bool AllowTypoCorrection) {
11061 if (!AllowTypoCorrection)
11062 return llvm::make_unique<NoTypoCorrectionCCC>();
11063 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11064 HasTemplateArgs, ME);
11065}
11066
John McCalld681c392009-12-16 08:11:27 +000011067/// Attempts to recover from a call where no functions were found.
11068///
11069/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011070static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011071BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011072 UnresolvedLookupExpr *ULE,
11073 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011074 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011075 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011076 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011077 // Do not try to recover if it is already building a recovery call.
11078 // This stops infinite loops for template instantiations like
11079 //
11080 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11081 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11082 //
11083 if (SemaRef.IsBuildingRecoveryCallExpr)
11084 return ExprError();
11085 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011086
11087 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011088 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011089 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011090
John McCall57500772009-12-16 12:17:52 +000011091 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011092 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011093 if (ULE->hasExplicitTemplateArgs()) {
11094 ULE->copyTemplateArgumentsInto(TABuffer);
11095 ExplicitTemplateArgs = &TABuffer;
11096 }
11097
John McCalld681c392009-12-16 08:11:27 +000011098 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11099 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011100 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011101 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011102 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011103 ExplicitTemplateArgs, Args,
11104 &DoDiagnoseEmptyLookup) &&
11105 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11106 S, SS, R,
11107 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11108 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11109 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011110 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011111
John McCall57500772009-12-16 12:17:52 +000011112 assert(!R.empty() && "lookup results empty despite recovery");
11113
11114 // Build an implicit member call if appropriate. Just drop the
11115 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011116 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011117 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011118 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11119 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011120 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011121 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011122 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011123 else
11124 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11125
11126 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011127 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011128
11129 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011130 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011131 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011132 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011133 MultiExprArg(Args.data(), Args.size()),
11134 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011135}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011136
Sam Panzer0f384432012-08-21 00:52:01 +000011137/// \brief Constructs and populates an OverloadedCandidateSet from
11138/// the given function.
11139/// \returns true when an the ExprResult output parameter has been set.
11140bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11141 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011142 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011143 SourceLocation RParenLoc,
11144 OverloadCandidateSet *CandidateSet,
11145 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011146#ifndef NDEBUG
11147 if (ULE->requiresADL()) {
11148 // To do ADL, we must have found an unqualified name.
11149 assert(!ULE->getQualifier() && "qualified name with ADL");
11150
11151 // We don't perform ADL for implicit declarations of builtins.
11152 // Verify that this was correctly set up.
11153 FunctionDecl *F;
11154 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11155 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11156 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011157 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011158
John McCall57500772009-12-16 12:17:52 +000011159 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011160 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011161 }
John McCall57500772009-12-16 12:17:52 +000011162#endif
11163
John McCall4124c492011-10-17 18:40:02 +000011164 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011165 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011166 *Result = ExprError();
11167 return true;
11168 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011169
John McCall57500772009-12-16 12:17:52 +000011170 // Add the functions denoted by the callee to the set of candidate
11171 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011172 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011173
Hans Wennborgb2747382015-06-12 21:23:23 +000011174 if (getLangOpts().MSVCCompat &&
11175 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011176 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11177
11178 OverloadCandidateSet::iterator Best;
11179 if (CandidateSet->empty() ||
11180 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11181 OR_No_Viable_Function) {
11182 // In Microsoft mode, if we are inside a template class member function then
11183 // create a type dependent CallExpr. The goal is to postpone name lookup
11184 // to instantiation time to be able to search into type dependent base
11185 // classes.
11186 CallExpr *CE = new (Context) CallExpr(
11187 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011188 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011189 CE->setValueDependent(true);
11190 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011191 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011192 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011193 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011194 }
John McCalld681c392009-12-16 08:11:27 +000011195
Hans Wennborg64937c62015-06-11 21:21:57 +000011196 if (CandidateSet->empty())
11197 return false;
11198
John McCall4124c492011-10-17 18:40:02 +000011199 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011200 return false;
11201}
John McCall4124c492011-10-17 18:40:02 +000011202
Sam Panzer0f384432012-08-21 00:52:01 +000011203/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11204/// the completed call expression. If overload resolution fails, emits
11205/// diagnostics and returns ExprError()
11206static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11207 UnresolvedLookupExpr *ULE,
11208 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011209 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011210 SourceLocation RParenLoc,
11211 Expr *ExecConfig,
11212 OverloadCandidateSet *CandidateSet,
11213 OverloadCandidateSet::iterator *Best,
11214 OverloadingResult OverloadResult,
11215 bool AllowTypoCorrection) {
11216 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011217 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011218 RParenLoc, /*EmptyLookup=*/true,
11219 AllowTypoCorrection);
11220
11221 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011222 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011223 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011224 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011225 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11226 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011227 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011228 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11229 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011230 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011231
Richard Smith998a5912011-06-05 22:42:48 +000011232 case OR_No_Viable_Function: {
11233 // Try to recover by looking for viable functions which the user might
11234 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011235 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011236 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011237 /*EmptyLookup=*/false,
11238 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011239 if (!Recovery.isInvalid())
11240 return Recovery;
11241
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011242 // If the user passes in a function that we can't take the address of, we
11243 // generally end up emitting really bad error messages. Here, we attempt to
11244 // emit better ones.
11245 for (const Expr *Arg : Args) {
11246 if (!Arg->getType()->isFunctionType())
11247 continue;
11248 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11249 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11250 if (FD &&
11251 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11252 Arg->getExprLoc()))
11253 return ExprError();
11254 }
11255 }
11256
11257 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11258 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011259 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011260 break;
Richard Smith998a5912011-06-05 22:42:48 +000011261 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011262
11263 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011264 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011265 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011266 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011267 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011268
Sam Panzer0f384432012-08-21 00:52:01 +000011269 case OR_Deleted: {
11270 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11271 << (*Best)->Function->isDeleted()
11272 << ULE->getName()
11273 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11274 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011275 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011276
Sam Panzer0f384432012-08-21 00:52:01 +000011277 // We emitted an error for the unvailable/deleted function call but keep
11278 // the call in the AST.
11279 FunctionDecl *FDecl = (*Best)->Function;
11280 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011281 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11282 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011283 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011284 }
11285
Douglas Gregorb412e172010-07-25 18:17:45 +000011286 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011287 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011288}
11289
George Burgess IV7204ed92016-01-07 02:26:57 +000011290static void markUnaddressableCandidatesUnviable(Sema &S,
11291 OverloadCandidateSet &CS) {
11292 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11293 if (I->Viable &&
11294 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11295 I->Viable = false;
11296 I->FailureKind = ovl_fail_addr_not_available;
11297 }
11298 }
11299}
11300
Sam Panzer0f384432012-08-21 00:52:01 +000011301/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11302/// (which eventually refers to the declaration Func) and the call
11303/// arguments Args/NumArgs, attempt to resolve the function call down
11304/// to a specific function. If overload resolution succeeds, returns
11305/// the call expression produced by overload resolution.
11306/// Otherwise, emits diagnostics and returns ExprError.
11307ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11308 UnresolvedLookupExpr *ULE,
11309 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011310 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011311 SourceLocation RParenLoc,
11312 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011313 bool AllowTypoCorrection,
11314 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011315 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11316 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011317 ExprResult result;
11318
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011319 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11320 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011321 return result;
11322
George Burgess IV7204ed92016-01-07 02:26:57 +000011323 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11324 // functions that aren't addressible are considered unviable.
11325 if (CalleesAddressIsTaken)
11326 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11327
Sam Panzer0f384432012-08-21 00:52:01 +000011328 OverloadCandidateSet::iterator Best;
11329 OverloadingResult OverloadResult =
11330 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11331
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011332 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011333 RParenLoc, ExecConfig, &CandidateSet,
11334 &Best, OverloadResult,
11335 AllowTypoCorrection);
11336}
11337
John McCall4c4c1df2010-01-26 03:27:55 +000011338static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011339 return Functions.size() > 1 ||
11340 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11341}
11342
Douglas Gregor084d8552009-03-13 23:49:33 +000011343/// \brief Create a unary operation that may resolve to an overloaded
11344/// operator.
11345///
11346/// \param OpLoc The location of the operator itself (e.g., '*').
11347///
Craig Toppera92ffb02015-12-10 08:51:49 +000011348/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011349///
James Dennett18348b62012-06-22 08:52:37 +000011350/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011351/// considered by overload resolution. The caller needs to build this
11352/// set based on the context using, e.g.,
11353/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11354/// set should not contain any member functions; those will be added
11355/// by CreateOverloadedUnaryOp().
11356///
James Dennett91738ff2012-06-22 10:32:46 +000011357/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011358ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011359Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011360 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011361 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011362 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11363 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11364 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011365 // TODO: provide better source location info.
11366 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011367
John McCall4124c492011-10-17 18:40:02 +000011368 if (checkPlaceholderForOverload(*this, Input))
11369 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011370
Craig Topperc3ec1492014-05-26 06:22:03 +000011371 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011372 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011373
Douglas Gregor084d8552009-03-13 23:49:33 +000011374 // For post-increment and post-decrement, add the implicit '0' as
11375 // the second argument, so that we know this is a post-increment or
11376 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011377 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011378 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011379 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11380 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011381 NumArgs = 2;
11382 }
11383
Richard Smithe54c3072013-05-05 15:51:06 +000011384 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11385
Douglas Gregor084d8552009-03-13 23:49:33 +000011386 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011387 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011388 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11389 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011390
Craig Topperc3ec1492014-05-26 06:22:03 +000011391 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011392 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011393 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011394 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011395 /*ADL*/ true, IsOverloaded(Fns),
11396 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011397 return new (Context)
11398 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11399 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011400 }
11401
11402 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011403 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011404
11405 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011406 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011407
11408 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011409 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011410
John McCall4c4c1df2010-01-26 03:27:55 +000011411 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011412 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011413 /*ExplicitTemplateArgs*/nullptr,
11414 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011415
Douglas Gregor084d8552009-03-13 23:49:33 +000011416 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011417 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011418
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11420
Douglas Gregor084d8552009-03-13 23:49:33 +000011421 // Perform overload resolution.
11422 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011423 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011424 case OR_Success: {
11425 // We found a built-in operator or an overloaded operator.
11426 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011427
Douglas Gregor084d8552009-03-13 23:49:33 +000011428 if (FnDecl) {
11429 // We matched an overloaded operator. Build a call to that
11430 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011431
Douglas Gregor084d8552009-03-13 23:49:33 +000011432 // Convert the arguments.
11433 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011434 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011435
John Wiegley01296292011-04-08 18:41:53 +000011436 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011437 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011438 Best->FoundDecl, Method);
11439 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011441 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011442 } else {
11443 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011444 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011445 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011446 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011447 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011448 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011449 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011450 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011451 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011452 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011453 }
11454
Douglas Gregor084d8552009-03-13 23:49:33 +000011455 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011456 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011457 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011458 if (FnExpr.isInvalid())
11459 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011460
Richard Smithc1564702013-11-15 02:58:23 +000011461 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011462 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011463 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11464 ResultTy = ResultTy.getNonLValueExprType(Context);
11465
Eli Friedman030eee42009-11-18 03:58:17 +000011466 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011467 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011468 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011469 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011470
Alp Toker314cc812014-01-25 16:55:45 +000011471 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011472 return ExprError();
11473
John McCallb268a282010-08-23 23:25:46 +000011474 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011475 } else {
11476 // We matched a built-in operator. Convert the arguments, then
11477 // break out so that we will build the appropriate built-in
11478 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011479 ExprResult InputRes =
11480 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11481 Best->Conversions[0], AA_Passing);
11482 if (InputRes.isInvalid())
11483 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011484 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011485 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011486 }
John Wiegley01296292011-04-08 18:41:53 +000011487 }
11488
11489 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011490 // This is an erroneous use of an operator which can be overloaded by
11491 // a non-member function. Check for non-member operators which were
11492 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011493 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011494 // FIXME: Recover by calling the found function.
11495 return ExprError();
11496
John Wiegley01296292011-04-08 18:41:53 +000011497 // No viable function; fall through to handling this as a
11498 // built-in operator, which will produce an error message for us.
11499 break;
11500
11501 case OR_Ambiguous:
11502 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11503 << UnaryOperator::getOpcodeStr(Opc)
11504 << Input->getType()
11505 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011506 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011507 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11508 return ExprError();
11509
11510 case OR_Deleted:
11511 Diag(OpLoc, diag::err_ovl_deleted_oper)
11512 << Best->Function->isDeleted()
11513 << UnaryOperator::getOpcodeStr(Opc)
11514 << getDeletedOrUnavailableSuffix(Best->Function)
11515 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011516 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011517 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011518 return ExprError();
11519 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011520
11521 // Either we found no viable overloaded operator or we matched a
11522 // built-in operator. In either case, fall through to trying to
11523 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011524 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011525}
11526
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011527/// \brief Create a binary operation that may resolve to an overloaded
11528/// operator.
11529///
11530/// \param OpLoc The location of the operator itself (e.g., '+').
11531///
Craig Toppera92ffb02015-12-10 08:51:49 +000011532/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011533///
James Dennett18348b62012-06-22 08:52:37 +000011534/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011535/// considered by overload resolution. The caller needs to build this
11536/// set based on the context using, e.g.,
11537/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11538/// set should not contain any member functions; those will be added
11539/// by CreateOverloadedBinOp().
11540///
11541/// \param LHS Left-hand argument.
11542/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011543ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011544Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011545 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011546 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011547 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011548 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011549 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011550
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011551 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11552 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11553
11554 // If either side is type-dependent, create an appropriate dependent
11555 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011556 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011557 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011558 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011559 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011560 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011561 return new (Context) BinaryOperator(
11562 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11563 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011564
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011565 return new (Context) CompoundAssignOperator(
11566 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11567 Context.DependentTy, Context.DependentTy, OpLoc,
11568 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011569 }
John McCall4c4c1df2010-01-26 03:27:55 +000011570
11571 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011572 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011573 // TODO: provide better source location info in DNLoc component.
11574 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011575 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011576 = UnresolvedLookupExpr::Create(Context, NamingClass,
11577 NestedNameSpecifierLoc(), OpNameInfo,
11578 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011579 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011580 return new (Context)
11581 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11582 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011583 }
11584
John McCall4124c492011-10-17 18:40:02 +000011585 // Always do placeholder-like conversions on the RHS.
11586 if (checkPlaceholderForOverload(*this, Args[1]))
11587 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011588
John McCall526ab472011-10-25 17:37:35 +000011589 // Do placeholder-like conversion on the LHS; note that we should
11590 // not get here with a PseudoObject LHS.
11591 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011592 if (checkPlaceholderForOverload(*this, Args[0]))
11593 return ExprError();
11594
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011595 // If this is the assignment operator, we only perform overload resolution
11596 // if the left-hand side is a class or enumeration type. This is actually
11597 // a hack. The standard requires that we do overload resolution between the
11598 // various built-in candidates, but as DR507 points out, this can lead to
11599 // problems. So we do it this way, which pretty much follows what GCC does.
11600 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011601 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011602 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011603
John McCalle26a8722010-12-04 08:14:53 +000011604 // If this is the .* operator, which is not overloadable, just
11605 // create a built-in binary operator.
11606 if (Opc == BO_PtrMemD)
11607 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11608
Douglas Gregor084d8552009-03-13 23:49:33 +000011609 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011610 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011611
11612 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011613 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011614
11615 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011616 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011617
Richard Smith0daabd72014-09-23 20:31:39 +000011618 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11619 // performed for an assignment operator (nor for operator[] nor operator->,
11620 // which don't get here).
11621 if (Opc != BO_Assign)
11622 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11623 /*ExplicitTemplateArgs*/ nullptr,
11624 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011625
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011626 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011627 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011628
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011629 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11630
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011631 // Perform overload resolution.
11632 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011633 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011634 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011635 // We found a built-in operator or an overloaded operator.
11636 FunctionDecl *FnDecl = Best->Function;
11637
11638 if (FnDecl) {
11639 // We matched an overloaded operator. Build a call to that
11640 // operator.
11641
11642 // Convert the arguments.
11643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011644 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011645 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011646
Chandler Carruth8e543b32010-12-12 08:17:55 +000011647 ExprResult Arg1 =
11648 PerformCopyInitialization(
11649 InitializedEntity::InitializeParameter(Context,
11650 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011651 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011652 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011653 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011654
John Wiegley01296292011-04-08 18:41:53 +000011655 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011656 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011657 Best->FoundDecl, Method);
11658 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011659 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011660 Args[0] = Arg0.getAs<Expr>();
11661 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011662 } else {
11663 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011664 ExprResult Arg0 = PerformCopyInitialization(
11665 InitializedEntity::InitializeParameter(Context,
11666 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011667 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011668 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011669 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011670
Chandler Carruth8e543b32010-12-12 08:17:55 +000011671 ExprResult Arg1 =
11672 PerformCopyInitialization(
11673 InitializedEntity::InitializeParameter(Context,
11674 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011675 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011676 if (Arg1.isInvalid())
11677 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011678 Args[0] = LHS = Arg0.getAs<Expr>();
11679 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011680 }
11681
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011682 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011683 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011684 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011685 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011686 if (FnExpr.isInvalid())
11687 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011688
Richard Smithc1564702013-11-15 02:58:23 +000011689 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011690 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011691 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11692 ResultTy = ResultTy.getNonLValueExprType(Context);
11693
John McCallb268a282010-08-23 23:25:46 +000011694 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011695 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011696 Args, ResultTy, VK, OpLoc,
11697 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011698
Alp Toker314cc812014-01-25 16:55:45 +000011699 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011700 FnDecl))
11701 return ExprError();
11702
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011703 ArrayRef<const Expr *> ArgsArray(Args, 2);
11704 // Cut off the implicit 'this'.
11705 if (isa<CXXMethodDecl>(FnDecl))
11706 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011707
11708 // Check for a self move.
11709 if (Op == OO_Equal)
11710 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11711
Douglas Gregorb4866e82015-06-19 18:13:19 +000011712 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011713 TheCall->getSourceRange(), VariadicDoesNotApply);
11714
John McCallb268a282010-08-23 23:25:46 +000011715 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011716 } else {
11717 // We matched a built-in operator. Convert the arguments, then
11718 // break out so that we will build the appropriate built-in
11719 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011720 ExprResult ArgsRes0 =
11721 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11722 Best->Conversions[0], AA_Passing);
11723 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011724 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011725 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011726
John Wiegley01296292011-04-08 18:41:53 +000011727 ExprResult ArgsRes1 =
11728 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11729 Best->Conversions[1], AA_Passing);
11730 if (ArgsRes1.isInvalid())
11731 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011732 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011733 break;
11734 }
11735 }
11736
Douglas Gregor66950a32009-09-30 21:46:01 +000011737 case OR_No_Viable_Function: {
11738 // C++ [over.match.oper]p9:
11739 // If the operator is the operator , [...] and there are no
11740 // viable functions, then the operator is assumed to be the
11741 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011742 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011743 break;
11744
Chandler Carruth8e543b32010-12-12 08:17:55 +000011745 // For class as left operand for assignment or compound assigment
11746 // operator do not fall through to handling in built-in, but report that
11747 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011748 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011749 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011750 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011751 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11752 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011753 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011754 if (Args[0]->getType()->isIncompleteType()) {
11755 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11756 << Args[0]->getType()
11757 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11758 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011759 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011760 // This is an erroneous use of an operator which can be overloaded by
11761 // a non-member function. Check for non-member operators which were
11762 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011763 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011764 // FIXME: Recover by calling the found function.
11765 return ExprError();
11766
Douglas Gregor66950a32009-09-30 21:46:01 +000011767 // No viable function; try to create a built-in operation, which will
11768 // produce an error. Then, show the non-viable candidates.
11769 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011771 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011772 "C++ binary operator overloading is missing candidates!");
11773 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011774 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011775 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011776 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011777 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011778
11779 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011780 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011781 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011782 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011783 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011784 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011785 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011786 return ExprError();
11787
11788 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011789 if (isImplicitlyDeleted(Best->Function)) {
11790 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11791 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011792 << Context.getRecordType(Method->getParent())
11793 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011794
Richard Smithde1a4872012-12-28 12:23:24 +000011795 // The user probably meant to call this special member. Just
11796 // explain why it's deleted.
11797 NoteDeletedFunction(Method);
11798 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011799 } else {
11800 Diag(OpLoc, diag::err_ovl_deleted_oper)
11801 << Best->Function->isDeleted()
11802 << BinaryOperator::getOpcodeStr(Opc)
11803 << getDeletedOrUnavailableSuffix(Best->Function)
11804 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11805 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011807 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011808 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011809 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011810
Douglas Gregor66950a32009-09-30 21:46:01 +000011811 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011812 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011813}
11814
John McCalldadc5752010-08-24 06:29:42 +000011815ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011816Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11817 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011818 Expr *Base, Expr *Idx) {
11819 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011820 DeclarationName OpName =
11821 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11822
11823 // If either side is type-dependent, create an appropriate dependent
11824 // expression.
11825 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11826
Craig Topperc3ec1492014-05-26 06:22:03 +000011827 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011828 // CHECKME: no 'operator' keyword?
11829 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11830 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011831 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011832 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011833 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011834 /*ADL*/ true, /*Overloaded*/ false,
11835 UnresolvedSetIterator(),
11836 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011837 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011838
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011839 return new (Context)
11840 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11841 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011842 }
11843
John McCall4124c492011-10-17 18:40:02 +000011844 // Handle placeholders on both operands.
11845 if (checkPlaceholderForOverload(*this, Args[0]))
11846 return ExprError();
11847 if (checkPlaceholderForOverload(*this, Args[1]))
11848 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011849
Sebastian Redladba46e2009-10-29 20:17:01 +000011850 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011851 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011852
11853 // Subscript can only be overloaded as a member function.
11854
11855 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011856 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011857
11858 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011859 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011860
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011861 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11862
Sebastian Redladba46e2009-10-29 20:17:01 +000011863 // Perform overload resolution.
11864 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011865 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011866 case OR_Success: {
11867 // We found a built-in operator or an overloaded operator.
11868 FunctionDecl *FnDecl = Best->Function;
11869
11870 if (FnDecl) {
11871 // We matched an overloaded operator. Build a call to that
11872 // operator.
11873
John McCalla0296f72010-03-19 07:35:19 +000011874 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011875
Sebastian Redladba46e2009-10-29 20:17:01 +000011876 // Convert the arguments.
11877 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011878 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011879 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011880 Best->FoundDecl, Method);
11881 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011882 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011883 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011884
Anders Carlssona68e51e2010-01-29 18:37:50 +000011885 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011886 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011887 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011888 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011889 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011890 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011891 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011892 if (InputInit.isInvalid())
11893 return ExprError();
11894
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011895 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011896
Sebastian Redladba46e2009-10-29 20:17:01 +000011897 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011898 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11899 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011900 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011901 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011902 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011903 OpLocInfo.getLoc(),
11904 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011905 if (FnExpr.isInvalid())
11906 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011907
Richard Smithc1564702013-11-15 02:58:23 +000011908 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011909 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011910 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11911 ResultTy = ResultTy.getNonLValueExprType(Context);
11912
John McCallb268a282010-08-23 23:25:46 +000011913 CXXOperatorCallExpr *TheCall =
11914 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011915 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011916 ResultTy, VK, RLoc,
11917 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011918
Alp Toker314cc812014-01-25 16:55:45 +000011919 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011920 return ExprError();
11921
John McCallb268a282010-08-23 23:25:46 +000011922 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011923 } else {
11924 // We matched a built-in operator. Convert the arguments, then
11925 // break out so that we will build the appropriate built-in
11926 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011927 ExprResult ArgsRes0 =
11928 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11929 Best->Conversions[0], AA_Passing);
11930 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011931 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011932 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011933
11934 ExprResult ArgsRes1 =
11935 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11936 Best->Conversions[1], AA_Passing);
11937 if (ArgsRes1.isInvalid())
11938 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011939 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011940
11941 break;
11942 }
11943 }
11944
11945 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011946 if (CandidateSet.empty())
11947 Diag(LLoc, diag::err_ovl_no_oper)
11948 << Args[0]->getType() << /*subscript*/ 0
11949 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11950 else
11951 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11952 << Args[0]->getType()
11953 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011954 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011955 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011956 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011957 }
11958
11959 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011960 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011961 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011962 << Args[0]->getType() << Args[1]->getType()
11963 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011964 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011965 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011966 return ExprError();
11967
11968 case OR_Deleted:
11969 Diag(LLoc, diag::err_ovl_deleted_oper)
11970 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011971 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011972 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011973 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011974 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011975 return ExprError();
11976 }
11977
11978 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011979 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011980}
11981
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011982/// BuildCallToMemberFunction - Build a call to a member
11983/// function. MemExpr is the expression that refers to the member
11984/// function (and includes the object parameter), Args/NumArgs are the
11985/// arguments to the function call (not including the object
11986/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011987/// expression refers to a non-static member function or an overloaded
11988/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011989ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011990Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011991 SourceLocation LParenLoc,
11992 MultiExprArg Args,
11993 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011994 assert(MemExprE->getType() == Context.BoundMemberTy ||
11995 MemExprE->getType() == Context.OverloadTy);
11996
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011997 // Dig out the member expression. This holds both the object
11998 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011999 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012000
John McCall0009fcc2011-04-26 20:42:42 +000012001 // Determine whether this is a call to a pointer-to-member function.
12002 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12003 assert(op->getType() == Context.BoundMemberTy);
12004 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12005
12006 QualType fnType =
12007 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12008
12009 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12010 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012011 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012012
12013 // Check that the object type isn't more qualified than the
12014 // member function we're calling.
12015 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12016
12017 QualType objectType = op->getLHS()->getType();
12018 if (op->getOpcode() == BO_PtrMemI)
12019 objectType = objectType->castAs<PointerType>()->getPointeeType();
12020 Qualifiers objectQuals = objectType.getQualifiers();
12021
12022 Qualifiers difference = objectQuals - funcQuals;
12023 difference.removeObjCGCAttr();
12024 difference.removeAddressSpace();
12025 if (difference) {
12026 std::string qualsString = difference.getAsString();
12027 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12028 << fnType.getUnqualifiedType()
12029 << qualsString
12030 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12031 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012032
John McCall0009fcc2011-04-26 20:42:42 +000012033 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012034 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012035 resultType, valueKind, RParenLoc);
12036
Alp Toker314cc812014-01-25 16:55:45 +000012037 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012038 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012039 return ExprError();
12040
Craig Topperc3ec1492014-05-26 06:22:03 +000012041 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012042 return ExprError();
12043
Richard Trieu9be9c682013-06-22 02:30:38 +000012044 if (CheckOtherCall(call, proto))
12045 return ExprError();
12046
John McCall0009fcc2011-04-26 20:42:42 +000012047 return MaybeBindToTemporary(call);
12048 }
12049
David Majnemerced8bdf2015-02-25 17:36:15 +000012050 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12051 return new (Context)
12052 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12053
John McCall4124c492011-10-17 18:40:02 +000012054 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012055 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012056 return ExprError();
12057
John McCall10eae182009-11-30 22:42:35 +000012058 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012059 CXXMethodDecl *Method = nullptr;
12060 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12061 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012062 if (isa<MemberExpr>(NakedMemExpr)) {
12063 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012064 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012065 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012066 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012067 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012068 } else {
12069 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012070 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012071
John McCall6e9f8f62009-12-03 04:06:58 +000012072 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012073 Expr::Classification ObjectClassification
12074 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12075 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012076
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012077 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012078 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12079 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012080
John McCall2d74de92009-12-01 22:10:20 +000012081 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012082 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012083 if (UnresExpr->hasExplicitTemplateArgs()) {
12084 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12085 TemplateArgs = &TemplateArgsBuffer;
12086 }
12087
John McCall10eae182009-11-30 22:42:35 +000012088 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12089 E = UnresExpr->decls_end(); I != E; ++I) {
12090
John McCall6e9f8f62009-12-03 04:06:58 +000012091 NamedDecl *Func = *I;
12092 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12093 if (isa<UsingShadowDecl>(Func))
12094 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12095
Douglas Gregor02824322011-01-26 19:30:28 +000012096
Francois Pichet64225792011-01-18 05:04:39 +000012097 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012098 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012099 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012100 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012101 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012102 // If explicit template arguments were provided, we can't call a
12103 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012104 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012105 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012106
John McCalla0296f72010-03-19 07:35:19 +000012107 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012108 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012109 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012110 } else {
John McCall10eae182009-11-30 22:42:35 +000012111 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012112 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012113 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012114 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012115 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012116 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012117 }
Mike Stump11289f42009-09-09 15:08:12 +000012118
John McCall10eae182009-11-30 22:42:35 +000012119 DeclarationName DeclName = UnresExpr->getMemberName();
12120
John McCall4124c492011-10-17 18:40:02 +000012121 UnbridgedCasts.restore();
12122
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012123 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012124 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012125 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012126 case OR_Success:
12127 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012128 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012129 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012130 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12131 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012132 // If FoundDecl is different from Method (such as if one is a template
12133 // and the other a specialization), make sure DiagnoseUseOfDecl is
12134 // called on both.
12135 // FIXME: This would be more comprehensively addressed by modifying
12136 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12137 // being used.
12138 if (Method != FoundDecl.getDecl() &&
12139 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12140 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012141 break;
12142
12143 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012144 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012145 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012146 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012147 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012148 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012149 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012150
12151 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012152 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012153 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012155 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012156 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012157
12158 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012159 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012160 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012161 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012162 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012163 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012164 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012165 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012166 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012167 }
12168
John McCall16df1e52010-03-30 21:47:33 +000012169 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012170
John McCall2d74de92009-12-01 22:10:20 +000012171 // If overload resolution picked a static member, build a
12172 // non-member call based on that function.
12173 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012174 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12175 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012176 }
12177
John McCall10eae182009-11-30 22:42:35 +000012178 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012179 }
12180
Alp Toker314cc812014-01-25 16:55:45 +000012181 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012182 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12183 ResultType = ResultType.getNonLValueExprType(Context);
12184
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012185 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012186 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012187 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012188 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012189
Eli Bendersky291a57e2014-09-25 23:59:08 +000012190 // (CUDA B.1): Check for invalid calls between targets.
12191 if (getLangOpts().CUDA) {
12192 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12193 if (CheckCUDATarget(Caller, Method)) {
12194 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12195 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12196 << IdentifyCUDATarget(Caller);
12197 return ExprError();
12198 }
12199 }
12200 }
12201
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012202 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012203 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012204 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012205 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012206
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012207 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012208 // We only need to do this if there was actually an overload; otherwise
12209 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012210 if (!Method->isStatic()) {
12211 ExprResult ObjectArg =
12212 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12213 FoundDecl, Method);
12214 if (ObjectArg.isInvalid())
12215 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012216 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012217 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012218
12219 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012220 const FunctionProtoType *Proto =
12221 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012222 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012223 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012224 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012225
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012226 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012227
Richard Smith55ce3522012-06-25 20:30:08 +000012228 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012229 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012230
George Burgess IVaea6ade2015-09-25 17:53:16 +000012231 // In the case the method to call was not selected by the overloading
12232 // resolution process, we still need to handle the enable_if attribute. Do
12233 // that here, so it will not hide previous -- and more relevant -- errors
12234 if (isa<MemberExpr>(NakedMemExpr)) {
12235 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12236 Diag(MemExprE->getLocStart(),
12237 diag::err_ovl_no_viable_member_function_in_call)
12238 << Method << Method->getSourceRange();
12239 Diag(Method->getLocation(),
12240 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12241 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12242 return ExprError();
12243 }
12244 }
12245
Anders Carlsson47061ee2011-05-06 14:25:31 +000012246 if ((isa<CXXConstructorDecl>(CurContext) ||
12247 isa<CXXDestructorDecl>(CurContext)) &&
12248 TheCall->getMethodDecl()->isPure()) {
12249 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12250
Davide Italianoccb37382015-07-14 23:36:10 +000012251 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12252 MemExpr->performsVirtualDispatch(getLangOpts())) {
12253 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012254 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12255 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12256 << MD->getParent()->getDeclName();
12257
12258 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012259 if (getLangOpts().AppleKext)
12260 Diag(MemExpr->getLocStart(),
12261 diag::note_pure_qualified_call_kext)
12262 << MD->getParent()->getDeclName()
12263 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012264 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012265 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012266
12267 if (CXXDestructorDecl *DD =
12268 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12269 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12270 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12271 getLangOpts().AppleKext;
12272 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12273 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12274 MemExpr->getMemberLoc());
12275 }
12276
John McCallb268a282010-08-23 23:25:46 +000012277 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012278}
12279
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012280/// BuildCallToObjectOfClassType - Build a call to an object of class
12281/// type (C++ [over.call.object]), which can end up invoking an
12282/// overloaded function call operator (@c operator()) or performing a
12283/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012284ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012285Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012286 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012287 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012288 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012289 if (checkPlaceholderForOverload(*this, Obj))
12290 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012291 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012292
12293 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012294 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012295 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012296
Nico Weberb58e51c2014-11-19 05:21:39 +000012297 assert(Object.get()->getType()->isRecordType() &&
12298 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012299 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012300
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012301 // C++ [over.call.object]p1:
12302 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012303 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012304 // candidate functions includes at least the function call
12305 // operators of T. The function call operators of T are obtained by
12306 // ordinary lookup of the name operator() in the context of
12307 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012308 OverloadCandidateSet CandidateSet(LParenLoc,
12309 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012310 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012311
John Wiegley01296292011-04-08 18:41:53 +000012312 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012313 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012314 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012315
John McCall27b18f82009-11-17 02:14:36 +000012316 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12317 LookupQualifiedName(R, Record->getDecl());
12318 R.suppressDiagnostics();
12319
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012320 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012321 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012322 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012323 Object.get()->Classify(Context),
12324 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012325 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012327
Douglas Gregorab7897a2008-11-19 22:57:39 +000012328 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012329 // In addition, for each (non-explicit in C++0x) conversion function
12330 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012331 //
12332 // operator conversion-type-id () cv-qualifier;
12333 //
12334 // where cv-qualifier is the same cv-qualification as, or a
12335 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012336 // denotes the type "pointer to function of (P1,...,Pn) returning
12337 // R", or the type "reference to pointer to function of
12338 // (P1,...,Pn) returning R", or the type "reference to function
12339 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012340 // is also considered as a candidate function. Similarly,
12341 // surrogate call functions are added to the set of candidate
12342 // functions for each conversion function declared in an
12343 // accessible base class provided the function is not hidden
12344 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012345 const auto &Conversions =
12346 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012348 NamedDecl *D = *I;
12349 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12350 if (isa<UsingShadowDecl>(D))
12351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012352
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012353 // Skip over templated conversion functions; they aren't
12354 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012355 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012356 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012357
John McCall6e9f8f62009-12-03 04:06:58 +000012358 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012359 if (!Conv->isExplicit()) {
12360 // Strip the reference type (if any) and then the pointer type (if
12361 // any) to get down to what might be a function type.
12362 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12363 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12364 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012365
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012366 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12367 {
12368 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012369 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012370 }
12371 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012372 }
Mike Stump11289f42009-09-09 15:08:12 +000012373
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12375
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012376 // Perform overload resolution.
12377 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012378 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012379 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012380 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012381 // Overload resolution succeeded; we'll build the appropriate call
12382 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012383 break;
12384
12385 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012386 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012387 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012388 << Object.get()->getType() << /*call*/ 1
12389 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012390 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012391 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012392 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012393 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012394 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012395 break;
12396
12397 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012398 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012399 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012400 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012401 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012402 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012403
12404 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012405 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012406 diag::err_ovl_deleted_object_call)
12407 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012408 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012409 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012410 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012411 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012412 break;
Mike Stump11289f42009-09-09 15:08:12 +000012413 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012414
Douglas Gregorb412e172010-07-25 18:17:45 +000012415 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012416 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012417
John McCall4124c492011-10-17 18:40:02 +000012418 UnbridgedCasts.restore();
12419
Craig Topperc3ec1492014-05-26 06:22:03 +000012420 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012421 // Since there is no function declaration, this is one of the
12422 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012423 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012424 = cast<CXXConversionDecl>(
12425 Best->Conversions[0].UserDefined.ConversionFunction);
12426
Craig Topperc3ec1492014-05-26 06:22:03 +000012427 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12428 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012429 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12430 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012431 assert(Conv == Best->FoundDecl.getDecl() &&
12432 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012433 // We selected one of the surrogate functions that converts the
12434 // object parameter to a function pointer. Perform the conversion
12435 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012436
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012437 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012438 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012439 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12440 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012441 if (Call.isInvalid())
12442 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012443 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012444 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12445 CK_UserDefinedConversion, Call.get(),
12446 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012447
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012448 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012449 }
12450
Craig Topperc3ec1492014-05-26 06:22:03 +000012451 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012452
Douglas Gregorab7897a2008-11-19 22:57:39 +000012453 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12454 // that calls this method, using Object for the implicit object
12455 // parameter and passing along the remaining arguments.
12456 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012457
12458 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012459 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012460 return ExprError();
12461
Chandler Carruth8e543b32010-12-12 08:17:55 +000012462 const FunctionProtoType *Proto =
12463 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012464
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012465 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012466
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012467 DeclarationNameInfo OpLocInfo(
12468 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12469 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012470 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012471 HadMultipleCandidates,
12472 OpLocInfo.getLoc(),
12473 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012474 if (NewFn.isInvalid())
12475 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012476
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012477 // Build the full argument list for the method call (the implicit object
12478 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012479 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012480 MethodArgs[0] = Object.get();
12481 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12482
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012483 // Once we've built TheCall, all of the expressions are properly
12484 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012485 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012486 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12487 ResultTy = ResultTy.getNonLValueExprType(Context);
12488
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012489 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012490 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012491 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12492 ResultTy, VK, RParenLoc, false);
12493 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012494
Alp Toker314cc812014-01-25 16:55:45 +000012495 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012496 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012497
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012498 // We may have default arguments. If so, we need to allocate more
12499 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012500 if (Args.size() < NumParams)
12501 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012502
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012503 bool IsError = false;
12504
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012505 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012506 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012507 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012508 Best->FoundDecl, Method);
12509 if (ObjRes.isInvalid())
12510 IsError = true;
12511 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012512 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012513 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012514
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012515 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012516 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012517 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012518 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012519 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012520
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012521 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012522
John McCalldadc5752010-08-24 06:29:42 +000012523 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012524 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012525 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012526 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012527 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012528
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012529 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012530 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012531 } else {
John McCalldadc5752010-08-24 06:29:42 +000012532 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012533 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12534 if (DefArg.isInvalid()) {
12535 IsError = true;
12536 break;
12537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012538
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012539 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012540 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012541
12542 TheCall->setArg(i + 1, Arg);
12543 }
12544
12545 // If this is a variadic call, handle args passed through "...".
12546 if (Proto->isVariadic()) {
12547 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012548 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012549 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12550 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012551 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012552 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012553 }
12554 }
12555
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012556 if (IsError) return true;
12557
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012558 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012559
Richard Smith55ce3522012-06-25 20:30:08 +000012560 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012561 return true;
12562
John McCalle172be52010-08-24 06:09:16 +000012563 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012564}
12565
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012566/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012567/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012568/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012569ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012570Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12571 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012572 assert(Base->getType()->isRecordType() &&
12573 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012574
John McCall4124c492011-10-17 18:40:02 +000012575 if (checkPlaceholderForOverload(*this, Base))
12576 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012577
John McCallbc077cf2010-02-08 23:07:23 +000012578 SourceLocation Loc = Base->getExprLoc();
12579
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012580 // C++ [over.ref]p1:
12581 //
12582 // [...] An expression x->m is interpreted as (x.operator->())->m
12583 // for a class object x of type T if T::operator->() exists and if
12584 // the operator is selected as the best match function by the
12585 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012586 DeclarationName OpName =
12587 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012588 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012589 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012590
John McCallbc077cf2010-02-08 23:07:23 +000012591 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012592 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012593 return ExprError();
12594
John McCall27b18f82009-11-17 02:14:36 +000012595 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12596 LookupQualifiedName(R, BaseRecord->getDecl());
12597 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012598
12599 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012600 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012601 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012602 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012603 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012604
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012605 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12606
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012607 // Perform overload resolution.
12608 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012609 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012610 case OR_Success:
12611 // Overload resolution succeeded; we'll build the call below.
12612 break;
12613
12614 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012615 if (CandidateSet.empty()) {
12616 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012617 if (NoArrowOperatorFound) {
12618 // Report this specific error to the caller instead of emitting a
12619 // diagnostic, as requested.
12620 *NoArrowOperatorFound = true;
12621 return ExprError();
12622 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012623 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12624 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012625 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012626 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012627 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012628 }
12629 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012630 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012631 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012633 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012634
12635 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012636 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12637 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012638 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012639 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012640
12641 case OR_Deleted:
12642 Diag(OpLoc, diag::err_ovl_deleted_oper)
12643 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012644 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012645 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012646 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012648 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012649 }
12650
Craig Topperc3ec1492014-05-26 06:22:03 +000012651 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012652
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012653 // Convert the object parameter.
12654 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012655 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012656 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012657 Best->FoundDecl, Method);
12658 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012659 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012660 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012661
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012662 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012663 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012664 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012665 if (FnExpr.isInvalid())
12666 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012667
Alp Toker314cc812014-01-25 16:55:45 +000012668 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012669 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12670 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012671 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012672 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012673 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012674
Alp Toker314cc812014-01-25 16:55:45 +000012675 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012676 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012677
12678 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012679}
12680
Richard Smithbcc22fc2012-03-09 08:00:36 +000012681/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12682/// a literal operator described by the provided lookup results.
12683ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12684 DeclarationNameInfo &SuffixInfo,
12685 ArrayRef<Expr*> Args,
12686 SourceLocation LitEndLoc,
12687 TemplateArgumentListInfo *TemplateArgs) {
12688 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012689
Richard Smith100b24a2014-04-17 01:52:14 +000012690 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12691 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012692 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12693 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012694
Richard Smithbcc22fc2012-03-09 08:00:36 +000012695 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12696
Richard Smithbcc22fc2012-03-09 08:00:36 +000012697 // Perform overload resolution. This will usually be trivial, but might need
12698 // to perform substitutions for a literal operator template.
12699 OverloadCandidateSet::iterator Best;
12700 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12701 case OR_Success:
12702 case OR_Deleted:
12703 break;
12704
12705 case OR_No_Viable_Function:
12706 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12707 << R.getLookupName();
12708 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12709 return ExprError();
12710
12711 case OR_Ambiguous:
12712 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12713 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12714 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012715 }
12716
Richard Smithbcc22fc2012-03-09 08:00:36 +000012717 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012718 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12719 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012720 SuffixInfo.getLoc(),
12721 SuffixInfo.getInfo());
12722 if (Fn.isInvalid())
12723 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012724
12725 // Check the argument types. This should almost always be a no-op, except
12726 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012727 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012728 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012729 ExprResult InputInit = PerformCopyInitialization(
12730 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12731 SourceLocation(), Args[ArgIdx]);
12732 if (InputInit.isInvalid())
12733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012734 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012735 }
12736
Alp Toker314cc812014-01-25 16:55:45 +000012737 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012738 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12739 ResultTy = ResultTy.getNonLValueExprType(Context);
12740
Richard Smithc67fdd42012-03-07 08:35:16 +000012741 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012742 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012743 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012744 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12745
Alp Toker314cc812014-01-25 16:55:45 +000012746 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012747 return ExprError();
12748
Craig Topperc3ec1492014-05-26 06:22:03 +000012749 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012750 return ExprError();
12751
12752 return MaybeBindToTemporary(UDL);
12753}
12754
Sam Panzer0f384432012-08-21 00:52:01 +000012755/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12756/// given LookupResult is non-empty, it is assumed to describe a member which
12757/// will be invoked. Otherwise, the function will be found via argument
12758/// dependent lookup.
12759/// CallExpr is set to a valid expression and FRS_Success returned on success,
12760/// otherwise CallExpr is set to ExprError() and some non-success value
12761/// is returned.
12762Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012763Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12764 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012765 const DeclarationNameInfo &NameInfo,
12766 LookupResult &MemberLookup,
12767 OverloadCandidateSet *CandidateSet,
12768 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012769 Scope *S = nullptr;
12770
Sam Panzer0f384432012-08-21 00:52:01 +000012771 CandidateSet->clear();
12772 if (!MemberLookup.empty()) {
12773 ExprResult MemberRef =
12774 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12775 /*IsPtr=*/false, CXXScopeSpec(),
12776 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012777 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012778 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012779 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012780 if (MemberRef.isInvalid()) {
12781 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012782 return FRS_DiagnosticIssued;
12783 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012784 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012785 if (CallExpr->isInvalid()) {
12786 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012787 return FRS_DiagnosticIssued;
12788 }
12789 } else {
12790 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012791 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012792 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012793 NestedNameSpecifierLoc(), NameInfo,
12794 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012795 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012796
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012797 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012798 CandidateSet, CallExpr);
12799 if (CandidateSet->empty() || CandidateSetError) {
12800 *CallExpr = ExprError();
12801 return FRS_NoViableFunction;
12802 }
12803 OverloadCandidateSet::iterator Best;
12804 OverloadingResult OverloadResult =
12805 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12806
12807 if (OverloadResult == OR_No_Viable_Function) {
12808 *CallExpr = ExprError();
12809 return FRS_NoViableFunction;
12810 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012811 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012812 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012813 OverloadResult,
12814 /*AllowTypoCorrection=*/false);
12815 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12816 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012817 return FRS_DiagnosticIssued;
12818 }
12819 }
12820 return FRS_Success;
12821}
12822
12823
Douglas Gregorcd695e52008-11-10 20:40:00 +000012824/// FixOverloadedFunctionReference - E is an expression that refers to
12825/// a C++ overloaded function (possibly with some parentheses and
12826/// perhaps a '&' around it). We have resolved the overloaded function
12827/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012828/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012829Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012830 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012831 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012832 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12833 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012834 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012835 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012836
Douglas Gregor51c538b2009-11-20 19:42:02 +000012837 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012838 }
12839
Douglas Gregor51c538b2009-11-20 19:42:02 +000012840 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012841 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12842 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012843 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012844 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012845 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012846 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012847 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012848 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012849
12850 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012851 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012852 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012853 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012854 }
12855
Douglas Gregor51c538b2009-11-20 19:42:02 +000012856 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012857 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012858 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012859 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12860 if (Method->isStatic()) {
12861 // Do nothing: static member functions aren't any different
12862 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012863 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012864 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012865 // UnresolvedLookupExpr holding an overloaded member function
12866 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012867 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12868 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012869 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012870 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012871
John McCalld14a8642009-11-21 08:51:07 +000012872 assert(isa<DeclRefExpr>(SubExpr)
12873 && "fixed to something other than a decl ref");
12874 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12875 && "fixed to a member ref with no nested name qualifier");
12876
12877 // We have taken the address of a pointer to member
12878 // function. Perform the computation here so that we get the
12879 // appropriate pointer to member type.
12880 QualType ClassType
12881 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12882 QualType MemPtrType
12883 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12884
John McCall7decc9e2010-11-18 06:31:45 +000012885 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12886 VK_RValue, OK_Ordinary,
12887 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012888 }
12889 }
John McCall16df1e52010-03-30 21:47:33 +000012890 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12891 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012892 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012893 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012894
John McCalle3027922010-08-25 11:45:40 +000012895 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012896 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012897 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012898 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012899 }
John McCalld14a8642009-11-21 08:51:07 +000012900
12901 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012902 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012903 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012904 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012905 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12906 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012907 }
12908
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012909 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12910 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012911 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012912 Fn,
John McCall113bee02012-03-10 09:33:50 +000012913 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012914 ULE->getNameLoc(),
12915 Fn->getType(),
12916 VK_LValue,
12917 Found.getDecl(),
12918 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012919 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012920 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12921 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012922 }
12923
John McCall10eae182009-11-30 22:42:35 +000012924 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012925 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012926 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012927 if (MemExpr->hasExplicitTemplateArgs()) {
12928 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12929 TemplateArgs = &TemplateArgsBuffer;
12930 }
John McCall6b51f282009-11-23 01:53:49 +000012931
John McCall2d74de92009-12-01 22:10:20 +000012932 Expr *Base;
12933
John McCall7decc9e2010-11-18 06:31:45 +000012934 // If we're filling in a static method where we used to have an
12935 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012936 if (MemExpr->isImplicitAccess()) {
12937 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012938 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12939 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012940 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012941 Fn,
John McCall113bee02012-03-10 09:33:50 +000012942 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012943 MemExpr->getMemberLoc(),
12944 Fn->getType(),
12945 VK_LValue,
12946 Found.getDecl(),
12947 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012948 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012949 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12950 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012951 } else {
12952 SourceLocation Loc = MemExpr->getMemberLoc();
12953 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012954 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012955 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012956 Base = new (Context) CXXThisExpr(Loc,
12957 MemExpr->getBaseType(),
12958 /*isImplicit=*/true);
12959 }
John McCall2d74de92009-12-01 22:10:20 +000012960 } else
John McCallc3007a22010-10-26 07:05:15 +000012961 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012962
John McCall4adb38c2011-04-27 00:36:17 +000012963 ExprValueKind valueKind;
12964 QualType type;
12965 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12966 valueKind = VK_LValue;
12967 type = Fn->getType();
12968 } else {
12969 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012970 type = Context.BoundMemberTy;
12971 }
12972
12973 MemberExpr *ME = MemberExpr::Create(
12974 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12975 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12976 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12977 OK_Ordinary);
12978 ME->setHadMultipleCandidates(true);
12979 MarkMemberReferenced(ME);
12980 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012982
John McCallc3007a22010-10-26 07:05:15 +000012983 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012984}
12985
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012986ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012987 DeclAccessPair Found,
12988 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012989 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012990}