blob: 663da0c0e8040bf03215973696c024ac49762be6 [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.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000436void 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 .
1132 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1133 return false;
1134
1135 // Allow overloading of functions with same signature, but
1136 // different CUDA target attributes.
1137 return NewTarget != OldTarget;
1138 }
1139
John McCall1f82f242009-11-18 22:49:29 +00001140 // The signatures match; this is not an overload.
1141 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142}
1143
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001144/// \brief Checks availability of the function depending on the current
1145/// function context. Inside an unavailable function, unavailability is ignored.
1146///
1147/// \returns true if \arg FD is unavailable and current context is inside
1148/// an available function, false otherwise.
1149bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1150 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1151}
1152
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001153/// \brief Tries a user-defined conversion from From to ToType.
1154///
1155/// Produces an implicit conversion sequence for when a standard conversion
1156/// is not an option. See TryImplicitConversion for more information.
1157static ImplicitConversionSequence
1158TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1159 bool SuppressUserConversions,
1160 bool AllowExplicit,
1161 bool InOverloadResolution,
1162 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001163 bool AllowObjCWritebackConversion,
1164 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001165 ImplicitConversionSequence ICS;
1166
1167 if (SuppressUserConversions) {
1168 // We're not in the case above, so there is no conversion that
1169 // we can perform.
1170 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1171 return ICS;
1172 }
1173
1174 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001175 OverloadCandidateSet Conversions(From->getExprLoc(),
1176 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001177 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1178 Conversions, AllowExplicit,
1179 AllowObjCConversionOnExplicit)) {
1180 case OR_Success:
1181 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001182 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001183 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001184 // C++ [over.ics.user]p4:
1185 // A conversion of an expression of class type to the same class
1186 // type is given Exact Match rank, and a conversion of an
1187 // expression of class type to a base class of that type is
1188 // given Conversion rank, in spite of the fact that a copy
1189 // constructor (i.e., a user-defined conversion function) is
1190 // called for those cases.
1191 if (CXXConstructorDecl *Constructor
1192 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1193 QualType FromCanon
1194 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1195 QualType ToCanon
1196 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1197 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001198 (FromCanon == ToCanon ||
1199 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001200 // Turn this into a "standard" conversion sequence, so that it
1201 // gets ranked with standard conversion sequences.
1202 ICS.setStandard();
1203 ICS.Standard.setAsIdentityConversion();
1204 ICS.Standard.setFromType(From->getType());
1205 ICS.Standard.setAllToTypes(ToType);
1206 ICS.Standard.CopyConstructor = Constructor;
1207 if (ToCanon != FromCanon)
1208 ICS.Standard.Second = ICK_Derived_To_Base;
1209 }
1210 }
Richard Smith48372b62015-01-27 03:30:40 +00001211 break;
1212
1213 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001214 ICS.setAmbiguous();
1215 ICS.Ambiguous.setFromType(From->getType());
1216 ICS.Ambiguous.setToType(ToType);
1217 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1218 Cand != Conversions.end(); ++Cand)
1219 if (Cand->Viable)
1220 ICS.Ambiguous.addConversion(Cand->Function);
1221 break;
Richard Smith48372b62015-01-27 03:30:40 +00001222
1223 // Fall through.
1224 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001226 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001227 }
1228
1229 return ICS;
1230}
1231
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001232/// TryImplicitConversion - Attempt to perform an implicit conversion
1233/// from the given expression (Expr) to the given type (ToType). This
1234/// function returns an implicit conversion sequence that can be used
1235/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236///
1237/// void f(float f);
1238/// void g(int i) { f(i); }
1239///
1240/// this routine would produce an implicit conversion sequence to
1241/// describe the initialization of f from i, which will be a standard
1242/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1243/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1244//
1245/// Note that this routine only determines how the conversion can be
1246/// performed; it does not actually perform the conversion. As such,
1247/// it will not produce any diagnostics if no conversion is available,
1248/// but will instead return an implicit conversion sequence of kind
1249/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001250///
1251/// If @p SuppressUserConversions, then user-defined conversions are
1252/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001253/// If @p AllowExplicit, then explicit user-defined conversions are
1254/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001255///
1256/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1257/// writeback conversion, which allows __autoreleasing id* parameters to
1258/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001259static ImplicitConversionSequence
1260TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1261 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001263 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001264 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001265 bool AllowObjCWritebackConversion,
1266 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001268 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001269 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001270 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001271 return ICS;
1272 }
1273
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001276 return ICS;
1277 }
1278
Douglas Gregor836a7e82010-08-11 02:15:33 +00001279 // C++ [over.ics.user]p4:
1280 // A conversion of an expression of class type to the same class
1281 // type is given Exact Match rank, and a conversion of an
1282 // expression of class type to a base class of that type is
1283 // given Conversion rank, in spite of the fact that a copy/move
1284 // constructor (i.e., a user-defined conversion function) is
1285 // called for those cases.
1286 QualType FromType = From->getType();
1287 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001288 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001289 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001290 ICS.setStandard();
1291 ICS.Standard.setAsIdentityConversion();
1292 ICS.Standard.setFromType(FromType);
1293 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294
Douglas Gregor5ab11652010-04-17 22:01:05 +00001295 // We don't actually check at this point whether there is a valid
1296 // copy/move constructor, since overloading just assumes that it
1297 // exists. When we actually perform initialization, we'll find the
1298 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001299 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001300
Douglas Gregor5ab11652010-04-17 22:01:05 +00001301 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001302 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001303 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Douglas Gregor836a7e82010-08-11 02:15:33 +00001305 return ICS;
1306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001307
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001308 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1309 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001310 AllowObjCWritebackConversion,
1311 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312}
1313
John McCall31168b02011-06-15 23:02:42 +00001314ImplicitConversionSequence
1315Sema::TryImplicitConversion(Expr *From, QualType ToType,
1316 bool SuppressUserConversions,
1317 bool AllowExplicit,
1318 bool InOverloadResolution,
1319 bool CStyle,
1320 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001321 return ::TryImplicitConversion(*this, From, ToType,
1322 SuppressUserConversions, AllowExplicit,
1323 InOverloadResolution, CStyle,
1324 AllowObjCWritebackConversion,
1325 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001326}
1327
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001328/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001329/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001330/// converted expression. Flavor is the kind of conversion we're
1331/// performing, used in the error message. If @p AllowExplicit,
1332/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001333ExprResult
1334Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001335 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001336 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001337 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001338}
1339
John Wiegley01296292011-04-08 18:41:53 +00001340ExprResult
1341Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001342 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001343 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001344 if (checkPlaceholderForOverload(*this, From))
1345 return ExprError();
1346
John McCall31168b02011-06-15 23:02:42 +00001347 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1348 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001349 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001350 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001351 if (getLangOpts().ObjC1)
1352 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1353 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001354 ICS = ::TryImplicitConversion(*this, From, ToType,
1355 /*SuppressUserConversions=*/false,
1356 AllowExplicit,
1357 /*InOverloadResolution=*/false,
1358 /*CStyle=*/false,
1359 AllowObjCWritebackConversion,
1360 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001361 return PerformImplicitConversion(From, ToType, ICS, Action);
1362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
1364/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001365/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001366bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1367 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001368 if (Context.hasSameUnqualifiedType(FromType, ToType))
1369 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
John McCall991eb4b2010-12-21 00:44:39 +00001371 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1372 // where F adds one of the following at most once:
1373 // - a pointer
1374 // - a member pointer
1375 // - a block pointer
1376 CanQualType CanTo = Context.getCanonicalType(ToType);
1377 CanQualType CanFrom = Context.getCanonicalType(FromType);
1378 Type::TypeClass TyClass = CanTo->getTypeClass();
1379 if (TyClass != CanFrom->getTypeClass()) return false;
1380 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1381 if (TyClass == Type::Pointer) {
1382 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1383 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1384 } else if (TyClass == Type::BlockPointer) {
1385 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1386 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1387 } else if (TyClass == Type::MemberPointer) {
1388 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1389 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1390 } else {
1391 return false;
1392 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001393
John McCall991eb4b2010-12-21 00:44:39 +00001394 TyClass = CanTo->getTypeClass();
1395 if (TyClass != CanFrom->getTypeClass()) return false;
1396 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1397 return false;
1398 }
1399
1400 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1401 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1402 if (!EInfo.getNoReturn()) return false;
1403
1404 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1405 assert(QualType(FromFn, 0).isCanonical());
1406 if (QualType(FromFn, 0) != CanTo) return false;
1407
1408 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001409 return true;
1410}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411
Douglas Gregor46188682010-05-18 22:42:18 +00001412/// \brief Determine whether the conversion from FromType to ToType is a valid
1413/// vector conversion.
1414///
1415/// \param ICK Will be set to the vector conversion kind, if this is a vector
1416/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001417static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001419 // We need at least one of these types to be a vector type to have a vector
1420 // conversion.
1421 if (!ToType->isVectorType() && !FromType->isVectorType())
1422 return false;
1423
1424 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001425 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001426 return false;
1427
1428 // There are no conversions between extended vector types, only identity.
1429 if (ToType->isExtVectorType()) {
1430 // There are no conversions between extended vector types other than the
1431 // identity conversion.
1432 if (FromType->isExtVectorType())
1433 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor46188682010-05-18 22:42:18 +00001435 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001436 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001437 ICK = ICK_Vector_Splat;
1438 return true;
1439 }
1440 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001441
1442 // We can perform the conversion between vector types in the following cases:
1443 // 1)vector types are equivalent AltiVec and GCC vector types
1444 // 2)lax vector conversions are permitted and the vector types are of the
1445 // same size
1446 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001447 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1448 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001449 ICK = ICK_Vector_Conversion;
1450 return true;
1451 }
Douglas Gregor46188682010-05-18 22:42:18 +00001452 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001453
Douglas Gregor46188682010-05-18 22:42:18 +00001454 return false;
1455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001457static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1458 bool InOverloadResolution,
1459 StandardConversionSequence &SCS,
1460 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001461
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462/// IsStandardConversion - Determines whether there is a standard
1463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1464/// expression From to the type ToType. Standard conversion sequences
1465/// only consider non-class types; for conversions that involve class
1466/// types, use TryImplicitConversion. If a conversion exists, SCS will
1467/// contain the standard conversion sequence required to perform this
1468/// conversion and this routine will return true. Otherwise, this
1469/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001470static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1471 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001472 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001473 bool CStyle,
1474 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001477 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001478 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001479 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001480 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001481 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001483 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001484 // abort early. When overloading in C, however, we do permit them.
1485 if (S.getLangOpts().CPlusPlus &&
1486 (FromType->isRecordType() || ToType->isRecordType()))
1487 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001488
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001489 // The first conversion can be an lvalue-to-rvalue conversion,
1490 // array-to-pointer conversion, or function-to-pointer conversion
1491 // (C++ 4p1).
1492
John McCall5c32be02010-08-24 20:38:10 +00001493 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001494 DeclAccessPair AccessPair;
1495 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001497 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001498 // We were able to resolve the address of the overloaded function,
1499 // so we can convert to the type of that function.
1500 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001501 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001502
1503 // we can sometimes resolve &foo<int> regardless of ToType, so check
1504 // if the type matches (identity) or we are converting to bool
1505 if (!S.Context.hasSameUnqualifiedType(
1506 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1507 QualType resultTy;
1508 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001509 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001510 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1511 // otherwise, only a boolean conversion is standard
1512 if (!ToType->isBooleanType())
1513 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Chandler Carruthffce2452011-03-29 08:08:18 +00001516 // Check if the "from" expression is taking the address of an overloaded
1517 // function and recompute the FromType accordingly. Take advantage of the
1518 // fact that non-static member functions *must* have such an address-of
1519 // expression.
1520 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1521 if (Method && !Method->isStatic()) {
1522 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1523 "Non-unary operator on non-static member address");
1524 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1525 == UO_AddrOf &&
1526 "Non-address-of operator on non-static member address");
1527 const Type *ClassType
1528 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1529 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001530 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1531 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1532 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001533 "Non-address-of operator for overloaded function expression");
1534 FromType = S.Context.getPointerType(FromType);
1535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536
Douglas Gregor980fb162010-04-29 18:24:40 +00001537 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001538 assert(S.Context.hasSameType(
1539 FromType,
1540 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001541 } else {
1542 return false;
1543 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001544 }
John McCall154a2fd2011-08-30 00:57:29 +00001545 // Lvalue-to-rvalue conversion (C++11 4.1):
1546 // A glvalue (3.10) of a non-function, non-array type T can
1547 // be converted to a prvalue.
1548 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001549 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001550 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001551 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553
Douglas Gregorc79862f2012-04-12 17:51:55 +00001554 // C11 6.3.2.1p2:
1555 // ... if the lvalue has atomic type, the value has the non-atomic version
1556 // of the type of the lvalue ...
1557 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1558 FromType = Atomic->getValueType();
1559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560 // If T is a non-class type, the type of the rvalue is the
1561 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001562 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1563 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 } else if (FromType->isArrayType()) {
1566 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568
1569 // An lvalue or rvalue of type "array of N T" or "array of unknown
1570 // bound of T" can be converted to an rvalue of type "pointer to
1571 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001572 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573
John McCall5c32be02010-08-24 20:38:10 +00001574 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001575 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001576 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577
1578 // For the purpose of ranking in overload resolution
1579 // (13.3.3.1.1), this conversion is considered an
1580 // array-to-pointer conversion followed by a qualification
1581 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
1583 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001584 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001585 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 }
John McCall086a4642010-11-24 05:12:34 +00001588 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001592 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1593 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1594 if (!S.checkAddressOfFunctionIsAvailable(FD))
1595 return false;
1596
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 // An lvalue of function type T can be converted to an rvalue of
1598 // type "pointer to T." The result is a pointer to the
1599 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001600 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 } else {
1602 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001603 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001605 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001606
1607 // The second conversion can be an integral promotion, floating
1608 // point promotion, integral conversion, floating point conversion,
1609 // floating-integral conversion, pointer conversion,
1610 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001611 // For overloading in C, this can also be a "compatible-type"
1612 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001613 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001614 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001615 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 // The unqualified versions of the types are the same: there's no
1617 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001619 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001620 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001622 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001623 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001624 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001625 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001627 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001628 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001629 SCS.Second = ICK_Complex_Promotion;
1630 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001631 } else if (ToType->isBooleanType() &&
1632 (FromType->isArithmeticType() ||
1633 FromType->isAnyPointerType() ||
1634 FromType->isBlockPointerType() ||
1635 FromType->isMemberPointerType() ||
1636 FromType->isNullPtrType())) {
1637 // Boolean conversions (C++ 4.12).
1638 SCS.Second = ICK_Boolean_Conversion;
1639 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001640 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001641 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001642 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001645 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001646 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001647 SCS.Second = ICK_Complex_Conversion;
1648 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001649 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1650 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001651 // Complex-real conversions (C99 6.3.1.7)
1652 SCS.Second = ICK_Complex_Real;
1653 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001654 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001655 // Floating point conversions (C++ 4.8).
1656 SCS.Second = ICK_Floating_Conversion;
1657 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001659 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001660 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001661 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001662 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001663 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001665 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001666 SCS.Second = ICK_Block_Pointer_Conversion;
1667 } else if (AllowObjCWritebackConversion &&
1668 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1669 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001670 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1671 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001672 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001674 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001675 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001677 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001678 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001679 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001680 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001681 SCS.Second = SecondICK;
1682 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001683 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001684 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001685 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001686 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001687 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001688 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001689 // Treat a conversion that strips "noreturn" as an identity conversion.
1690 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001691 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1692 InOverloadResolution,
1693 SCS, CStyle)) {
1694 SCS.Second = ICK_TransparentUnionConversion;
1695 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001696 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1697 CStyle)) {
1698 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001699 // appropriately.
1700 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001701 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001702 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001703 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001704 SCS.Second = ICK_Zero_Event_Conversion;
1705 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 } else {
1707 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001708 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001710 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001712 QualType CanonFrom;
1713 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001715 bool ObjCLifetimeConversion;
1716 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1717 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001718 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001719 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001721 CanonFrom = S.Context.getCanonicalType(FromType);
1722 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723 } else {
1724 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001725 SCS.Third = ICK_Identity;
1726
Mike Stump11289f42009-09-09 15:08:12 +00001727 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001728 // [...] Any difference in top-level cv-qualification is
1729 // subsumed by the initialization itself and does not constitute
1730 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001731 CanonFrom = S.Context.getCanonicalType(FromType);
1732 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001734 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001735 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001736 FromType = ToType;
1737 CanonFrom = CanonTo;
1738 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001740 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001741
George Burgess IV45461812015-10-11 20:13:20 +00001742 if (CanonFrom == CanonTo)
1743 return true;
1744
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001746 // this is a bad conversion sequence, unless we're resolving an overload in C.
1747 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001748 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749
George Burgess IV45461812015-10-11 20:13:20 +00001750 ExprResult ER = ExprResult{From};
1751 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1752 /*Diagnose=*/false,
1753 /*DiagnoseCFAudited=*/false,
1754 /*ConvertRHS=*/false);
1755 if (Conv != Sema::Compatible)
1756 return false;
1757
1758 SCS.setAllToTypes(ToType);
1759 // We need to set all three because we want this conversion to rank terribly,
1760 // and we don't know what conversions it may overlap with.
1761 SCS.First = ICK_C_Only_Conversion;
1762 SCS.Second = ICK_C_Only_Conversion;
1763 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001764 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001766
1767static bool
1768IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1769 QualType &ToType,
1770 bool InOverloadResolution,
1771 StandardConversionSequence &SCS,
1772 bool CStyle) {
1773
1774 const RecordType *UT = ToType->getAsUnionType();
1775 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1776 return false;
1777 // The field to initialize within the transparent union.
1778 RecordDecl *UD = UT->getDecl();
1779 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001780 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001781 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1782 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001783 ToType = it->getType();
1784 return true;
1785 }
1786 }
1787 return false;
1788}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789
1790/// IsIntegralPromotion - Determines whether the conversion from the
1791/// expression From (whose potentially-adjusted type is FromType) to
1792/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1793/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001794bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001795 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001796 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001797 if (!To) {
1798 return false;
1799 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800
1801 // An rvalue of type char, signed char, unsigned char, short int, or
1802 // unsigned short int can be converted to an rvalue of type int if
1803 // int can represent all the values of the source type; otherwise,
1804 // the source rvalue can be converted to an rvalue of type unsigned
1805 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001806 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1807 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 if (// We can promote any signed, promotable integer type to an int
1809 (FromType->isSignedIntegerType() ||
1810 // We can promote any unsigned integer type whose size is
1811 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001812 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001813 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001815 }
1816
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 return To->getKind() == BuiltinType::UInt;
1818 }
1819
Richard Smithb9c5a602012-09-13 21:18:54 +00001820 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 // A prvalue of an unscoped enumeration type whose underlying type is not
1822 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1823 // following types that can represent all the values of the enumeration
1824 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1825 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001826 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001827 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001828 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001829 // with lowest integer conversion rank (4.13) greater than the rank of long
1830 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001831 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001832 // C++11 [conv.prom]p4:
1833 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1834 // can be converted to a prvalue of its underlying type. Moreover, if
1835 // integral promotion can be applied to its underlying type, a prvalue of an
1836 // unscoped enumeration type whose underlying type is fixed can also be
1837 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001838 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1839 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1840 // provided for a scoped enumeration.
1841 if (FromEnumType->getDecl()->isScoped())
1842 return false;
1843
Richard Smithb9c5a602012-09-13 21:18:54 +00001844 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001845 // even if that's not the promoted type. Note that the check for promoting
1846 // the underlying type is based on the type alone, and does not consider
1847 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001848 if (FromEnumType->getDecl()->isFixed()) {
1849 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1850 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001851 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001852 }
1853
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001854 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001856 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001857 return Context.hasSameUnqualifiedType(
1858 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001859 }
John McCall56774992009-12-09 09:09:27 +00001860
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001861 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1863 // to an rvalue a prvalue of the first of the following types that can
1864 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001865 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001867 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001869 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001871 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001872 // Determine whether the type we're converting from is signed or
1873 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001874 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001875 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877 // The types we'll try to promote to, in the appropriate
1878 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001879 QualType PromoteTypes[6] = {
1880 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001881 Context.LongTy, Context.UnsignedLongTy ,
1882 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001884 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1886 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001887 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1889 // We found the type that we can promote to. If this is the
1890 // type we wanted, we have a promotion. Otherwise, no
1891 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001892 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001893 }
1894 }
1895 }
1896
1897 // An rvalue for an integral bit-field (9.6) can be converted to an
1898 // rvalue of type int if int can represent all the values of the
1899 // bit-field; otherwise, it can be converted to unsigned int if
1900 // unsigned int can represent all the values of the bit-field. If
1901 // the bit-field is larger yet, no integral promotion applies to
1902 // it. If the bit-field has an enumerated type, it is treated as any
1903 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001904 // FIXME: We should delay checking of bit-fields until we actually perform the
1905 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001906 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001907 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001908 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001909 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001910 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001911 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001912 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001914 // Are we promoting to an int from a bitfield that fits in an int?
1915 if (BitWidth < ToSize ||
1916 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1917 return To->getKind() == BuiltinType::Int;
1918 }
Mike Stump11289f42009-09-09 15:08:12 +00001919
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001920 // Are we promoting to an unsigned int from an unsigned bitfield
1921 // that fits into an unsigned int?
1922 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1923 return To->getKind() == BuiltinType::UInt;
1924 }
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001926 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001927 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001929 }
Mike Stump11289f42009-09-09 15:08:12 +00001930
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931 // An rvalue of type bool can be converted to an rvalue of type int,
1932 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001933 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001935 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936
1937 return false;
1938}
1939
1940/// IsFloatingPointPromotion - Determines whether the conversion from
1941/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1942/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001943bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001944 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1945 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001946 /// An rvalue of type float can be converted to an rvalue of type
1947 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001948 if (FromBuiltin->getKind() == BuiltinType::Float &&
1949 ToBuiltin->getKind() == BuiltinType::Double)
1950 return true;
1951
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001952 // C99 6.3.1.5p1:
1953 // When a float is promoted to double or long double, or a
1954 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001955 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001956 (FromBuiltin->getKind() == BuiltinType::Float ||
1957 FromBuiltin->getKind() == BuiltinType::Double) &&
1958 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1959 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001960
1961 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001962 if (!getLangOpts().NativeHalfType &&
1963 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001964 ToBuiltin->getKind() == BuiltinType::Float)
1965 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001966 }
1967
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 return false;
1969}
1970
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001971/// \brief Determine if a conversion is a complex promotion.
1972///
1973/// A complex promotion is defined as a complex -> complex conversion
1974/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001975/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001976bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001977 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001978 if (!FromComplex)
1979 return false;
1980
John McCall9dd450b2009-09-21 23:43:11 +00001981 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001982 if (!ToComplex)
1983 return false;
1984
1985 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001986 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001987 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001988 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001989}
1990
Douglas Gregor237f96c2008-11-26 23:31:11 +00001991/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1992/// the pointer type FromPtr to a pointer to type ToPointee, with the
1993/// same type qualifiers as FromPtr has on its pointee type. ToType,
1994/// if non-empty, will be a pointer to ToType that may or may not have
1995/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001996///
Mike Stump11289f42009-09-09 15:08:12 +00001997static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001998BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001999 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002000 ASTContext &Context,
2001 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002002 assert((FromPtr->getTypeClass() == Type::Pointer ||
2003 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2004 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
John McCall31168b02011-06-15 23:02:42 +00002006 /// Conversions to 'id' subsume cv-qualifier conversions.
2007 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002008 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
2010 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002011 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002012 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002013 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002014
John McCall31168b02011-06-15 23:02:42 +00002015 if (StripObjCLifetime)
2016 Quals.removeObjCLifetime();
2017
Mike Stump11289f42009-09-09 15:08:12 +00002018 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002019 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002020 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002021 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002022 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002023
2024 // Build a pointer to ToPointee. It has the right qualifiers
2025 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002026 if (isa<ObjCObjectPointerType>(ToType))
2027 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002028 return Context.getPointerType(ToPointee);
2029 }
2030
2031 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002032 QualType QualifiedCanonToPointee
2033 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002035 if (isa<ObjCObjectPointerType>(ToType))
2036 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2037 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039
Mike Stump11289f42009-09-09 15:08:12 +00002040static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002041 bool InOverloadResolution,
2042 ASTContext &Context) {
2043 // Handle value-dependent integral null pointer constants correctly.
2044 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2045 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002046 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002047 return !InOverloadResolution;
2048
Douglas Gregor56751b52009-09-25 04:25:58 +00002049 return Expr->isNullPointerConstant(Context,
2050 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2051 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002052}
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002054/// IsPointerConversion - Determines whether the conversion of the
2055/// expression From, which has the (possibly adjusted) type FromType,
2056/// can be converted to the type ToType via a pointer conversion (C++
2057/// 4.10). If so, returns true and places the converted type (that
2058/// might differ from ToType in its cv-qualifiers at some level) into
2059/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002060///
Douglas Gregora29dc052008-11-27 01:19:21 +00002061/// This routine also supports conversions to and from block pointers
2062/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2063/// pointers to interfaces. FIXME: Once we've determined the
2064/// appropriate overloading rules for Objective-C, we may want to
2065/// split the Objective-C checks into a different routine; however,
2066/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002067/// conversions, so for now they live here. IncompatibleObjC will be
2068/// set if the conversion is an allowed Objective-C conversion that
2069/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002070bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002071 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002072 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002073 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002074 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002075 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2076 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002077 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002078
Mike Stump11289f42009-09-09 15:08:12 +00002079 // Conversion from a null pointer constant to any Objective-C pointer type.
2080 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002082 ConvertedType = ToType;
2083 return true;
2084 }
2085
Douglas Gregor231d1c62008-11-27 00:15:41 +00002086 // Blocks: Block pointers can be converted to void*.
2087 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002088 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002089 ConvertedType = ToType;
2090 return true;
2091 }
2092 // Blocks: A null pointer constant can be converted to a block
2093 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002094 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002095 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002096 ConvertedType = ToType;
2097 return true;
2098 }
2099
Sebastian Redl576fd422009-05-10 18:38:11 +00002100 // If the left-hand-side is nullptr_t, the right side can be a null
2101 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002102 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002103 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002104 ConvertedType = ToType;
2105 return true;
2106 }
2107
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002108 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 if (!ToTypePtr)
2110 return false;
2111
2112 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002113 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002114 ConvertedType = ToType;
2115 return true;
2116 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002117
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002119 // , including objective-c pointers.
2120 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002121 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002123 ConvertedType = BuildSimilarlyQualifiedPointerType(
2124 FromType->getAs<ObjCObjectPointerType>(),
2125 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002126 ToType, Context);
2127 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002128 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002129 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002130 if (!FromTypePtr)
2131 return false;
2132
2133 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002134
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002136 // pointer conversion, so don't do all of the work below.
2137 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2138 return false;
2139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002140 // An rvalue of type "pointer to cv T," where T is an object type,
2141 // can be converted to an rvalue of type "pointer to cv void" (C++
2142 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002143 if (FromPointeeType->isIncompleteOrObjectType() &&
2144 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002146 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002147 ToType, Context,
2148 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002149 return true;
2150 }
2151
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002152 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002153 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002154 ToPointeeType->isVoidType()) {
2155 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2156 ToPointeeType,
2157 ToType, Context);
2158 return true;
2159 }
2160
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002161 // When we're overloading in C, we allow a special kind of pointer
2162 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002163 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002164 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002166 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002167 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002168 return true;
2169 }
2170
Douglas Gregor5c407d92008-10-23 00:40:37 +00002171 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002172 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002173 // An rvalue of type "pointer to cv D," where D is a class type,
2174 // can be converted to an rvalue of type "pointer to cv B," where
2175 // B is a base class (clause 10) of D. If B is an inaccessible
2176 // (clause 11) or ambiguous (10.2) base class of D, a program that
2177 // necessitates this conversion is ill-formed. The result of the
2178 // conversion is a pointer to the base class sub-object of the
2179 // derived class object. The null pointer value is converted to
2180 // the null pointer value of the destination type.
2181 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002182 // Note that we do not check for ambiguity or inaccessibility
2183 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002184 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002185 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002186 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002187 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002189 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002190 ToType, Context);
2191 return true;
2192 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002193
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002194 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2195 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2197 ToPointeeType,
2198 ToType, Context);
2199 return true;
2200 }
2201
Douglas Gregora119f102008-12-19 19:13:09 +00002202 return false;
2203}
Douglas Gregoraec25842011-04-26 23:16:46 +00002204
2205/// \brief Adopt the given qualifiers for the given type.
2206static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2207 Qualifiers TQs = T.getQualifiers();
2208
2209 // Check whether qualifiers already match.
2210 if (TQs == Qs)
2211 return T;
2212
2213 if (Qs.compatiblyIncludes(TQs))
2214 return Context.getQualifiedType(T, Qs);
2215
2216 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2217}
Douglas Gregora119f102008-12-19 19:13:09 +00002218
2219/// isObjCPointerConversion - Determines whether this is an
2220/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2221/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002222bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002223 QualType& ConvertedType,
2224 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002225 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002226 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227
Douglas Gregoraec25842011-04-26 23:16:46 +00002228 // The set of qualifiers on the type we're converting from.
2229 Qualifiers FromQualifiers = FromType.getQualifiers();
2230
Steve Naroff7cae42b2009-07-10 23:34:53 +00002231 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002232 const ObjCObjectPointerType* ToObjCPtr =
2233 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002234 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002235 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002236
Steve Naroff7cae42b2009-07-10 23:34:53 +00002237 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002238 // If the pointee types are the same (ignoring qualifications),
2239 // then this is not a pointer conversion.
2240 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2241 FromObjCPtr->getPointeeType()))
2242 return false;
2243
Douglas Gregorab209d82015-07-07 03:58:42 +00002244 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002245 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002246 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2247 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002249 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2250 FromObjCPtr->getPointeeType()))
2251 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002253 ToObjCPtr->getPointeeType(),
2254 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002256 return true;
2257 }
2258
2259 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2260 // Okay: this is some kind of implicit downcast of Objective-C
2261 // interfaces, which is permitted. However, we're going to
2262 // complain about it.
2263 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002264 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002265 ToObjCPtr->getPointeeType(),
2266 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002268 return true;
2269 }
Mike Stump11289f42009-09-09 15:08:12 +00002270 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002271 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002272 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002273 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002274 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002275 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002276 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002277 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002278 // to a block pointer type.
2279 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002280 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002281 return true;
2282 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002283 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002286 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002287 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002288 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002289 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002290 return true;
2291 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002292 else
Douglas Gregora119f102008-12-19 19:13:09 +00002293 return false;
2294
Douglas Gregor033f56d2008-12-23 00:53:59 +00002295 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002296 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002297 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002298 else if (const BlockPointerType *FromBlockPtr =
2299 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002300 FromPointeeType = FromBlockPtr->getPointeeType();
2301 else
Douglas Gregora119f102008-12-19 19:13:09 +00002302 return false;
2303
Douglas Gregora119f102008-12-19 19:13:09 +00002304 // If we have pointers to pointers, recursively check whether this
2305 // is an Objective-C conversion.
2306 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2307 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2308 IncompatibleObjC)) {
2309 // We always complain about this conversion.
2310 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002311 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002312 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002313 return true;
2314 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002315 // Allow conversion of pointee being objective-c pointer to another one;
2316 // as in I* to id.
2317 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2318 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2319 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2320 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002321
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002322 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002323 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002324 return true;
2325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326
Douglas Gregor033f56d2008-12-23 00:53:59 +00002327 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002328 // differences in the argument and result types are in Objective-C
2329 // pointer conversions. If so, we permit the conversion (but
2330 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002331 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002332 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002333 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002334 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002335 if (FromFunctionType && ToFunctionType) {
2336 // If the function types are exactly the same, this isn't an
2337 // Objective-C pointer conversion.
2338 if (Context.getCanonicalType(FromPointeeType)
2339 == Context.getCanonicalType(ToPointeeType))
2340 return false;
2341
2342 // Perform the quick checks that will tell us whether these
2343 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002344 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002345 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2346 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2347 return false;
2348
2349 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002350 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2351 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002352 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002353 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2354 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002355 ConvertedType, IncompatibleObjC)) {
2356 // Okay, we have an Objective-C pointer conversion.
2357 HasObjCConversion = true;
2358 } else {
2359 // Function types are too different. Abort.
2360 return false;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregora119f102008-12-19 19:13:09 +00002363 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002365 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002366 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2367 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002368 if (Context.getCanonicalType(FromArgType)
2369 == Context.getCanonicalType(ToArgType)) {
2370 // Okay, the types match exactly. Nothing to do.
2371 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2372 ConvertedType, IncompatibleObjC)) {
2373 // Okay, we have an Objective-C pointer conversion.
2374 HasObjCConversion = true;
2375 } else {
2376 // Argument types are too different. Abort.
2377 return false;
2378 }
2379 }
2380
2381 if (HasObjCConversion) {
2382 // We had an Objective-C conversion. Allow this pointer
2383 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002384 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002385 IncompatibleObjC = true;
2386 return true;
2387 }
2388 }
2389
Sebastian Redl72b597d2009-01-25 19:43:20 +00002390 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002391}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392
John McCall31168b02011-06-15 23:02:42 +00002393/// \brief Determine whether this is an Objective-C writeback conversion,
2394/// used for parameter passing when performing automatic reference counting.
2395///
2396/// \param FromType The type we're converting form.
2397///
2398/// \param ToType The type we're converting to.
2399///
2400/// \param ConvertedType The type that will be produced after applying
2401/// this conversion.
2402bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2403 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002404 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002405 Context.hasSameUnqualifiedType(FromType, ToType))
2406 return false;
2407
2408 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2409 QualType ToPointee;
2410 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2411 ToPointee = ToPointer->getPointeeType();
2412 else
2413 return false;
2414
2415 Qualifiers ToQuals = ToPointee.getQualifiers();
2416 if (!ToPointee->isObjCLifetimeType() ||
2417 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002418 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002419 return false;
2420
2421 // Argument must be a pointer to __strong to __weak.
2422 QualType FromPointee;
2423 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2424 FromPointee = FromPointer->getPointeeType();
2425 else
2426 return false;
2427
2428 Qualifiers FromQuals = FromPointee.getQualifiers();
2429 if (!FromPointee->isObjCLifetimeType() ||
2430 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2431 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2432 return false;
2433
2434 // Make sure that we have compatible qualifiers.
2435 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2436 if (!ToQuals.compatiblyIncludes(FromQuals))
2437 return false;
2438
2439 // Remove qualifiers from the pointee type we're converting from; they
2440 // aren't used in the compatibility check belong, and we'll be adding back
2441 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2442 FromPointee = FromPointee.getUnqualifiedType();
2443
2444 // The unqualified form of the pointee types must be compatible.
2445 ToPointee = ToPointee.getUnqualifiedType();
2446 bool IncompatibleObjC;
2447 if (Context.typesAreCompatible(FromPointee, ToPointee))
2448 FromPointee = ToPointee;
2449 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2450 IncompatibleObjC))
2451 return false;
2452
2453 /// \brief Construct the type we're converting to, which is a pointer to
2454 /// __autoreleasing pointee.
2455 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2456 ConvertedType = Context.getPointerType(FromPointee);
2457 return true;
2458}
2459
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002460bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2461 QualType& ConvertedType) {
2462 QualType ToPointeeType;
2463 if (const BlockPointerType *ToBlockPtr =
2464 ToType->getAs<BlockPointerType>())
2465 ToPointeeType = ToBlockPtr->getPointeeType();
2466 else
2467 return false;
2468
2469 QualType FromPointeeType;
2470 if (const BlockPointerType *FromBlockPtr =
2471 FromType->getAs<BlockPointerType>())
2472 FromPointeeType = FromBlockPtr->getPointeeType();
2473 else
2474 return false;
2475 // We have pointer to blocks, check whether the only
2476 // differences in the argument and result types are in Objective-C
2477 // pointer conversions. If so, we permit the conversion.
2478
2479 const FunctionProtoType *FromFunctionType
2480 = FromPointeeType->getAs<FunctionProtoType>();
2481 const FunctionProtoType *ToFunctionType
2482 = ToPointeeType->getAs<FunctionProtoType>();
2483
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002484 if (!FromFunctionType || !ToFunctionType)
2485 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002486
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002487 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002488 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002489
2490 // Perform the quick checks that will tell us whether these
2491 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002492 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002493 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2494 return false;
2495
2496 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2497 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2498 if (FromEInfo != ToEInfo)
2499 return false;
2500
2501 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002502 if (Context.hasSameType(FromFunctionType->getReturnType(),
2503 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002504 // Okay, the types match exactly. Nothing to do.
2505 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002506 QualType RHS = FromFunctionType->getReturnType();
2507 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002508 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002509 !RHS.hasQualifiers() && LHS.hasQualifiers())
2510 LHS = LHS.getUnqualifiedType();
2511
2512 if (Context.hasSameType(RHS,LHS)) {
2513 // OK exact match.
2514 } else if (isObjCPointerConversion(RHS, LHS,
2515 ConvertedType, IncompatibleObjC)) {
2516 if (IncompatibleObjC)
2517 return false;
2518 // Okay, we have an Objective-C pointer conversion.
2519 }
2520 else
2521 return false;
2522 }
2523
2524 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002525 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002526 ArgIdx != NumArgs; ++ArgIdx) {
2527 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002528 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2529 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002530 if (Context.hasSameType(FromArgType, ToArgType)) {
2531 // Okay, the types match exactly. Nothing to do.
2532 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2533 ConvertedType, IncompatibleObjC)) {
2534 if (IncompatibleObjC)
2535 return false;
2536 // Okay, we have an Objective-C pointer conversion.
2537 } else
2538 // Argument types are too different. Abort.
2539 return false;
2540 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002541 if (LangOpts.ObjCAutoRefCount &&
2542 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2543 ToFunctionType))
2544 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002545
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002546 ConvertedType = ToType;
2547 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002548}
2549
Richard Trieucaff2472011-11-23 22:32:32 +00002550enum {
2551 ft_default,
2552 ft_different_class,
2553 ft_parameter_arity,
2554 ft_parameter_mismatch,
2555 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002556 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002557};
2558
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002559/// Attempts to get the FunctionProtoType from a Type. Handles
2560/// MemberFunctionPointers properly.
2561static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2562 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2563 return FPT;
2564
2565 if (auto *MPT = FromType->getAs<MemberPointerType>())
2566 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2567
2568 return nullptr;
2569}
2570
Richard Trieucaff2472011-11-23 22:32:32 +00002571/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2572/// function types. Catches different number of parameter, mismatch in
2573/// parameter types, and different return types.
2574void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2575 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002576 // If either type is not valid, include no extra info.
2577 if (FromType.isNull() || ToType.isNull()) {
2578 PDiag << ft_default;
2579 return;
2580 }
2581
Richard Trieucaff2472011-11-23 22:32:32 +00002582 // Get the function type from the pointers.
2583 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2584 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2585 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002586 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002587 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2588 << QualType(FromMember->getClass(), 0);
2589 return;
2590 }
2591 FromType = FromMember->getPointeeType();
2592 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002593 }
2594
Richard Trieu96ed5b62011-12-13 23:19:45 +00002595 if (FromType->isPointerType())
2596 FromType = FromType->getPointeeType();
2597 if (ToType->isPointerType())
2598 ToType = ToType->getPointeeType();
2599
2600 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002601 FromType = FromType.getNonReferenceType();
2602 ToType = ToType.getNonReferenceType();
2603
Richard Trieucaff2472011-11-23 22:32:32 +00002604 // Don't print extra info for non-specialized template functions.
2605 if (FromType->isInstantiationDependentType() &&
2606 !FromType->getAs<TemplateSpecializationType>()) {
2607 PDiag << ft_default;
2608 return;
2609 }
2610
Richard Trieu96ed5b62011-12-13 23:19:45 +00002611 // No extra info for same types.
2612 if (Context.hasSameType(FromType, ToType)) {
2613 PDiag << ft_default;
2614 return;
2615 }
2616
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002617 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2618 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002619
2620 // Both types need to be function types.
2621 if (!FromFunction || !ToFunction) {
2622 PDiag << ft_default;
2623 return;
2624 }
2625
Alp Toker9cacbab2014-01-20 20:26:09 +00002626 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2627 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2628 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002629 return;
2630 }
2631
2632 // Handle different parameter types.
2633 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002634 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002635 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002636 << ToFunction->getParamType(ArgPos)
2637 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002638 return;
2639 }
2640
2641 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002642 if (!Context.hasSameType(FromFunction->getReturnType(),
2643 ToFunction->getReturnType())) {
2644 PDiag << ft_return_type << ToFunction->getReturnType()
2645 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002646 return;
2647 }
2648
2649 unsigned FromQuals = FromFunction->getTypeQuals(),
2650 ToQuals = ToFunction->getTypeQuals();
2651 if (FromQuals != ToQuals) {
2652 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2653 return;
2654 }
2655
2656 // Unable to find a difference, so add no extra info.
2657 PDiag << ft_default;
2658}
2659
Alp Toker9cacbab2014-01-20 20:26:09 +00002660/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002661/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002662/// they have same number of arguments. If the parameters are different,
2663/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002664bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2665 const FunctionProtoType *NewType,
2666 unsigned *ArgPos) {
2667 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2668 N = NewType->param_type_begin(),
2669 E = OldType->param_type_end();
2670 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002671 if (!Context.hasSameType(O->getUnqualifiedType(),
2672 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002673 if (ArgPos)
2674 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002675 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002676 }
2677 }
2678 return true;
2679}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002680
Douglas Gregor39c16d42008-10-24 04:54:22 +00002681/// CheckPointerConversion - Check the pointer conversion from the
2682/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002683/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002684/// conversions for which IsPointerConversion has already returned
2685/// true. It returns true and produces a diagnostic if there was an
2686/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002687bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002688 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002689 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002690 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002691 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002692 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002693
John McCall8cb679e2010-11-15 09:13:47 +00002694 Kind = CK_BitCast;
2695
David Blaikie1c7c8f72012-08-08 17:33:31 +00002696 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002697 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002698 Expr::NPCK_ZeroExpression) {
2699 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2700 DiagRuntimeBehavior(From->getExprLoc(), From,
2701 PDiag(diag::warn_impcast_bool_to_null_pointer)
2702 << ToType << From->getSourceRange());
2703 else if (!isUnevaluatedContext())
2704 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2705 << ToType << From->getSourceRange();
2706 }
John McCall9320b872011-09-09 05:25:32 +00002707 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2708 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002709 QualType FromPointeeType = FromPtrType->getPointeeType(),
2710 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002711
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002712 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2713 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002714 // We must have a derived-to-base conversion. Check an
2715 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002716 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2717 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002718 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002719 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002720 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002722 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002723 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002724 }
David Majnemer6bf02822015-10-31 08:42:14 +00002725
2726 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() &&
2727 ToPointeeType->isVoidType()) {
2728 assert(getLangOpts().MSVCCompat &&
2729 "this should only be possible with MSVCCompat!");
2730 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2731 << From->getSourceRange();
2732 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002733 }
John McCall9320b872011-09-09 05:25:32 +00002734 } else if (const ObjCObjectPointerType *ToPtrType =
2735 ToType->getAs<ObjCObjectPointerType>()) {
2736 if (const ObjCObjectPointerType *FromPtrType =
2737 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002738 // Objective-C++ conversions are always okay.
2739 // FIXME: We should have a different class of conversions for the
2740 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002741 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002742 return false;
John McCall9320b872011-09-09 05:25:32 +00002743 } else if (FromType->isBlockPointerType()) {
2744 Kind = CK_BlockPointerToObjCPointerCast;
2745 } else {
2746 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002747 }
John McCall9320b872011-09-09 05:25:32 +00002748 } else if (ToType->isBlockPointerType()) {
2749 if (!FromType->isBlockPointerType())
2750 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002751 }
John McCall8cb679e2010-11-15 09:13:47 +00002752
2753 // We shouldn't fall into this case unless it's valid for other
2754 // reasons.
2755 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2756 Kind = CK_NullToPointer;
2757
Douglas Gregor39c16d42008-10-24 04:54:22 +00002758 return false;
2759}
2760
Sebastian Redl72b597d2009-01-25 19:43:20 +00002761/// IsMemberPointerConversion - Determines whether the conversion of the
2762/// expression From, which has the (possibly adjusted) type FromType, can be
2763/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2764/// If so, returns true and places the converted type (that might differ from
2765/// ToType in its cv-qualifiers at some level) into ConvertedType.
2766bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002768 bool InOverloadResolution,
2769 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002770 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002771 if (!ToTypePtr)
2772 return false;
2773
2774 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002775 if (From->isNullPointerConstant(Context,
2776 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2777 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002778 ConvertedType = ToType;
2779 return true;
2780 }
2781
2782 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002783 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002784 if (!FromTypePtr)
2785 return false;
2786
2787 // A pointer to member of B can be converted to a pointer to member of D,
2788 // where D is derived from B (C++ 4.11p2).
2789 QualType FromClass(FromTypePtr->getClass(), 0);
2790 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002792 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002793 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002794 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2795 ToClass.getTypePtr());
2796 return true;
2797 }
2798
2799 return false;
2800}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
Sebastian Redl72b597d2009-01-25 19:43:20 +00002802/// CheckMemberPointerConversion - Check the member pointer conversion from the
2803/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002804/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002805/// for which IsMemberPointerConversion has already returned true. It returns
2806/// true and produces a diagnostic if there was an error, or returns false
2807/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002808bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002809 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002810 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002811 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002812 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002813 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002814 if (!FromPtrType) {
2815 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002817 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002818 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002819 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002820 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002821 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002822
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002823 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002824 assert(ToPtrType && "No member pointer cast has a target type "
2825 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002826
Sebastian Redled8f2002009-01-28 18:33:18 +00002827 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2828 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002829
Sebastian Redled8f2002009-01-28 18:33:18 +00002830 // FIXME: What about dependent types?
2831 assert(FromClass->isRecordType() && "Pointer into non-class.");
2832 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002833
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002834 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002835 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002836 bool DerivationOkay =
2837 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002838 assert(DerivationOkay &&
2839 "Should not have been called if derivation isn't OK.");
2840 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002841
Sebastian Redled8f2002009-01-28 18:33:18 +00002842 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2843 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002844 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2845 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2846 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2847 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002848 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002849
Douglas Gregor89ee6822009-02-28 01:32:25 +00002850 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002851 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2852 << FromClass << ToClass << QualType(VBase, 0)
2853 << From->getSourceRange();
2854 return true;
2855 }
2856
John McCall5b0829a2010-02-10 09:31:12 +00002857 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002858 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2859 Paths.front(),
2860 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002861
Anders Carlssond7923c62009-08-22 23:33:40 +00002862 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002863 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002864 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002865 return false;
2866}
2867
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002868/// Determine whether the lifetime conversion between the two given
2869/// qualifiers sets is nontrivial.
2870static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2871 Qualifiers ToQuals) {
2872 // Converting anything to const __unsafe_unretained is trivial.
2873 if (ToQuals.hasConst() &&
2874 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2875 return false;
2876
2877 return true;
2878}
2879
Douglas Gregor9a657932008-10-21 23:43:52 +00002880/// IsQualificationConversion - Determines whether the conversion from
2881/// an rvalue of type FromType to ToType is a qualification conversion
2882/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002883///
2884/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2885/// when the qualification conversion involves a change in the Objective-C
2886/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002887bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002888Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002889 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002890 FromType = Context.getCanonicalType(FromType);
2891 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002892 ObjCLifetimeConversion = false;
2893
Douglas Gregor9a657932008-10-21 23:43:52 +00002894 // If FromType and ToType are the same type, this is not a
2895 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002896 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002897 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002898
Douglas Gregor9a657932008-10-21 23:43:52 +00002899 // (C++ 4.4p4):
2900 // A conversion can add cv-qualifiers at levels other than the first
2901 // in multi-level pointers, subject to the following rules: [...]
2902 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002903 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002904 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002905 // Within each iteration of the loop, we check the qualifiers to
2906 // determine if this still looks like a qualification
2907 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002908 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002909 // until there are no more pointers or pointers-to-members left to
2910 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002911 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002912
Douglas Gregor90609aa2011-04-25 18:40:17 +00002913 Qualifiers FromQuals = FromType.getQualifiers();
2914 Qualifiers ToQuals = ToType.getQualifiers();
2915
John McCall31168b02011-06-15 23:02:42 +00002916 // Objective-C ARC:
2917 // Check Objective-C lifetime conversions.
2918 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2919 UnwrappedAnyPointer) {
2920 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002921 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2922 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002923 FromQuals.removeObjCLifetime();
2924 ToQuals.removeObjCLifetime();
2925 } else {
2926 // Qualification conversions cannot cast between different
2927 // Objective-C lifetime qualifiers.
2928 return false;
2929 }
2930 }
2931
Douglas Gregorf30053d2011-05-08 06:09:53 +00002932 // Allow addition/removal of GC attributes but not changing GC attributes.
2933 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2934 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2935 FromQuals.removeObjCGCAttr();
2936 ToQuals.removeObjCGCAttr();
2937 }
2938
Douglas Gregor9a657932008-10-21 23:43:52 +00002939 // -- for every j > 0, if const is in cv 1,j then const is in cv
2940 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002941 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002942 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregor9a657932008-10-21 23:43:52 +00002944 // -- if the cv 1,j and cv 2,j are different, then const is in
2945 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002946 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002947 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002948 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Douglas Gregor9a657932008-10-21 23:43:52 +00002950 // Keep track of whether all prior cv-qualifiers in the "to" type
2951 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002952 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002953 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002954 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002955
2956 // We are left with FromType and ToType being the pointee types
2957 // after unwrapping the original FromType and ToType the same number
2958 // of types. If we unwrapped any pointers, and if FromType and
2959 // ToType have the same unqualified type (since we checked
2960 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002961 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002962}
2963
Douglas Gregorc79862f2012-04-12 17:51:55 +00002964/// \brief - Determine whether this is a conversion from a scalar type to an
2965/// atomic type.
2966///
2967/// If successful, updates \c SCS's second and third steps in the conversion
2968/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002969static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2970 bool InOverloadResolution,
2971 StandardConversionSequence &SCS,
2972 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002973 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2974 if (!ToAtomic)
2975 return false;
2976
2977 StandardConversionSequence InnerSCS;
2978 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2979 InOverloadResolution, InnerSCS,
2980 CStyle, /*AllowObjCWritebackConversion=*/false))
2981 return false;
2982
2983 SCS.Second = InnerSCS.Second;
2984 SCS.setToType(1, InnerSCS.getToType(1));
2985 SCS.Third = InnerSCS.Third;
2986 SCS.QualificationIncludesObjCLifetime
2987 = InnerSCS.QualificationIncludesObjCLifetime;
2988 SCS.setToType(2, InnerSCS.getToType(2));
2989 return true;
2990}
2991
Sebastian Redle5417162012-03-27 18:33:03 +00002992static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2993 CXXConstructorDecl *Constructor,
2994 QualType Type) {
2995 const FunctionProtoType *CtorType =
2996 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002997 if (CtorType->getNumParams() > 0) {
2998 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002999 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3000 return true;
3001 }
3002 return false;
3003}
3004
Sebastian Redl82ace982012-02-11 23:51:08 +00003005static OverloadingResult
3006IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3007 CXXRecordDecl *To,
3008 UserDefinedConversionSequence &User,
3009 OverloadCandidateSet &CandidateSet,
3010 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003011 DeclContext::lookup_result R = S.LookupConstructors(To);
3012 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003013 Con != ConEnd; ++Con) {
3014 NamedDecl *D = *Con;
3015 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3016
3017 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003018 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003019 FunctionTemplateDecl *ConstructorTmpl
3020 = dyn_cast<FunctionTemplateDecl>(D);
3021 if (ConstructorTmpl)
3022 Constructor
3023 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3024 else
3025 Constructor = cast<CXXConstructorDecl>(D);
3026
3027 bool Usable = !Constructor->isInvalidDecl() &&
3028 S.isInitListConstructor(Constructor) &&
3029 (AllowExplicit || !Constructor->isExplicit());
3030 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003031 // If the first argument is (a reference to) the target type,
3032 // suppress conversions.
3033 bool SuppressUserConversions =
3034 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003035 if (ConstructorTmpl)
3036 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003037 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003038 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003039 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003040 else
3041 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003042 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003043 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003044 }
3045 }
3046
3047 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3048
3049 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003050 switch (auto Result =
3051 CandidateSet.BestViableFunction(S, From->getLocStart(),
3052 Best, true)) {
3053 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003054 case OR_Success: {
3055 // Record the standard conversion we used and the conversion function.
3056 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003057 QualType ThisType = Constructor->getThisType(S.Context);
3058 // Initializer lists don't have conversions as such.
3059 User.Before.setAsIdentityConversion();
3060 User.HadMultipleCandidates = HadMultipleCandidates;
3061 User.ConversionFunction = Constructor;
3062 User.FoundConversionFunction = Best->FoundDecl;
3063 User.After.setAsIdentityConversion();
3064 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3065 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003066 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003067 }
3068
3069 case OR_No_Viable_Function:
3070 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003071 case OR_Ambiguous:
3072 return OR_Ambiguous;
3073 }
3074
3075 llvm_unreachable("Invalid OverloadResult!");
3076}
3077
Douglas Gregor576e98c2009-01-30 23:27:23 +00003078/// Determines whether there is a user-defined conversion sequence
3079/// (C++ [over.ics.user]) that converts expression From to the type
3080/// ToType. If such a conversion exists, User will contain the
3081/// user-defined conversion sequence that performs such a conversion
3082/// and this routine will return true. Otherwise, this routine returns
3083/// false and User is unspecified.
3084///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003085/// \param AllowExplicit true if the conversion should consider C++0x
3086/// "explicit" conversion functions as well as non-explicit conversion
3087/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003088///
3089/// \param AllowObjCConversionOnExplicit true if the conversion should
3090/// allow an extra Objective-C pointer conversion on uses of explicit
3091/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003092static OverloadingResult
3093IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003094 UserDefinedConversionSequence &User,
3095 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003096 bool AllowExplicit,
3097 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003098 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003099
Douglas Gregor5ab11652010-04-17 22:01:05 +00003100 // Whether we will only visit constructors.
3101 bool ConstructorsOnly = false;
3102
3103 // If the type we are conversion to is a class type, enumerate its
3104 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003105 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003106 // C++ [over.match.ctor]p1:
3107 // When objects of class type are direct-initialized (8.5), or
3108 // copy-initialized from an expression of the same or a
3109 // derived class type (8.5), overload resolution selects the
3110 // constructor. [...] For copy-initialization, the candidate
3111 // functions are all the converting constructors (12.3.1) of
3112 // that class. The argument list is the expression-list within
3113 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003114 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003115 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003116 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003117 ConstructorsOnly = true;
3118
Richard Smithdb0ac552015-12-18 22:40:25 +00003119 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003120 // We're not going to find any constructors.
3121 } else if (CXXRecordDecl *ToRecordDecl
3122 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003123
3124 Expr **Args = &From;
3125 unsigned NumArgs = 1;
3126 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003127 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003128 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003129 OverloadingResult Result = IsInitializerListConstructorConversion(
3130 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3131 if (Result != OR_No_Viable_Function)
3132 return Result;
3133 // Never mind.
3134 CandidateSet.clear();
3135
3136 // If we're list-initializing, we pass the individual elements as
3137 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003138 Args = InitList->getInits();
3139 NumArgs = InitList->getNumInits();
3140 ListInitializing = true;
3141 }
3142
David Blaikieff7d47a2012-12-19 00:45:41 +00003143 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3144 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003145 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003146 NamedDecl *D = *Con;
3147 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3148
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003149 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003151 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003152 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003153 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003154 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003155 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3156 else
John McCalla0296f72010-03-19 07:35:19 +00003157 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003159 bool Usable = !Constructor->isInvalidDecl();
3160 if (ListInitializing)
3161 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3162 else
3163 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3164 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003165 bool SuppressUserConversions = !ConstructorsOnly;
3166 if (SuppressUserConversions && ListInitializing) {
3167 SuppressUserConversions = false;
3168 if (NumArgs == 1) {
3169 // If the first argument is (a reference to) the target type,
3170 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003171 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3172 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003173 }
3174 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003175 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003176 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003177 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003178 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003179 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003180 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003181 // Allow one user-defined conversion when user specifies a
3182 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003183 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003184 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003185 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003186 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003187 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003188 }
3189 }
3190
Douglas Gregor5ab11652010-04-17 22:01:05 +00003191 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003192 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003193 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003194 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003195 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003196 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003197 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003198 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3199 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003200 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3201 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003202 DeclAccessPair FoundDecl = I.getPair();
3203 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003204 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3205 if (isa<UsingShadowDecl>(D))
3206 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3207
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003208 CXXConversionDecl *Conv;
3209 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003210 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3211 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003212 else
John McCallda4458e2010-03-31 01:36:47 +00003213 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003214
3215 if (AllowExplicit || !Conv->isExplicit()) {
3216 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003217 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3218 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003219 CandidateSet,
3220 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003221 else
John McCall5c32be02010-08-24 20:38:10 +00003222 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003223 From, ToType, CandidateSet,
3224 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003225 }
3226 }
3227 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003228 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003229
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003230 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3231
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003232 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003233 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3234 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003235 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003236 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003237 // Record the standard conversion we used and the conversion function.
3238 if (CXXConstructorDecl *Constructor
3239 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3240 // C++ [over.ics.user]p1:
3241 // If the user-defined conversion is specified by a
3242 // constructor (12.3.1), the initial standard conversion
3243 // sequence converts the source type to the type required by
3244 // the argument of the constructor.
3245 //
3246 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003247 if (isa<InitListExpr>(From)) {
3248 // Initializer lists don't have conversions as such.
3249 User.Before.setAsIdentityConversion();
3250 } else {
3251 if (Best->Conversions[0].isEllipsis())
3252 User.EllipsisConversion = true;
3253 else {
3254 User.Before = Best->Conversions[0].Standard;
3255 User.EllipsisConversion = false;
3256 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003257 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003258 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003259 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003260 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003261 User.After.setAsIdentityConversion();
3262 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3263 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003264 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003265 }
3266 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003267 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3268 // C++ [over.ics.user]p1:
3269 //
3270 // [...] If the user-defined conversion is specified by a
3271 // conversion function (12.3.2), the initial standard
3272 // conversion sequence converts the source type to the
3273 // implicit object parameter of the conversion function.
3274 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003275 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003276 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003277 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003278 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003279
John McCall5c32be02010-08-24 20:38:10 +00003280 // C++ [over.ics.user]p2:
3281 // The second standard conversion sequence converts the
3282 // result of the user-defined conversion to the target type
3283 // for the sequence. Since an implicit conversion sequence
3284 // is an initialization, the special rules for
3285 // initialization by user-defined conversion apply when
3286 // selecting the best user-defined conversion for a
3287 // user-defined conversion sequence (see 13.3.3 and
3288 // 13.3.3.1).
3289 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003290 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003291 }
David Blaikie8a40f702012-01-17 06:56:22 +00003292 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003293
John McCall5c32be02010-08-24 20:38:10 +00003294 case OR_No_Viable_Function:
3295 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296
John McCall5c32be02010-08-24 20:38:10 +00003297 case OR_Ambiguous:
3298 return OR_Ambiguous;
3299 }
3300
David Blaikie8a40f702012-01-17 06:56:22 +00003301 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003302}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003304bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003305Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003306 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003307 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3308 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003309 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003310 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003311 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003312 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003313 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3314 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003315 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003316 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003317 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003318 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003319 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003320 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003321 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003322 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003323 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003325}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003326
Douglas Gregor2837aa22012-02-22 17:32:19 +00003327/// \brief Compare the user-defined conversion functions or constructors
3328/// of two user-defined conversion sequences to determine whether any ordering
3329/// is possible.
3330static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003331compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003332 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003333 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003334 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003335
Douglas Gregor2837aa22012-02-22 17:32:19 +00003336 // Objective-C++:
3337 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003338 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003339 // respectively, always prefer the conversion to a function pointer,
3340 // because the function pointer is more lightweight and is more likely
3341 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003342 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003343 if (!Conv1)
3344 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003345
Douglas Gregor2837aa22012-02-22 17:32:19 +00003346 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3347 if (!Conv2)
3348 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003349
Douglas Gregor2837aa22012-02-22 17:32:19 +00003350 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3351 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3352 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3353 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003354 return Block1 ? ImplicitConversionSequence::Worse
3355 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003356 }
3357
3358 return ImplicitConversionSequence::Indistinguishable;
3359}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003360
3361static bool hasDeprecatedStringLiteralToCharPtrConversion(
3362 const ImplicitConversionSequence &ICS) {
3363 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3364 (ICS.isUserDefined() &&
3365 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3366}
3367
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003368/// CompareImplicitConversionSequences - Compare two implicit
3369/// conversion sequences to determine whether one is better than the
3370/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003371static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003372CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003373 const ImplicitConversionSequence& ICS1,
3374 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003375{
3376 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3377 // conversion sequences (as defined in 13.3.3.1)
3378 // -- a standard conversion sequence (13.3.3.1.1) is a better
3379 // conversion sequence than a user-defined conversion sequence or
3380 // an ellipsis conversion sequence, and
3381 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3382 // conversion sequence than an ellipsis conversion sequence
3383 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003384 //
John McCall0d1da222010-01-12 00:44:57 +00003385 // C++0x [over.best.ics]p10:
3386 // For the purpose of ranking implicit conversion sequences as
3387 // described in 13.3.3.2, the ambiguous conversion sequence is
3388 // treated as a user-defined sequence that is indistinguishable
3389 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003390
3391 // String literal to 'char *' conversion has been deprecated in C++03. It has
3392 // been removed from C++11. We still accept this conversion, if it happens at
3393 // the best viable function. Otherwise, this conversion is considered worse
3394 // than ellipsis conversion. Consider this as an extension; this is not in the
3395 // standard. For example:
3396 //
3397 // int &f(...); // #1
3398 // void f(char*); // #2
3399 // void g() { int &r = f("foo"); }
3400 //
3401 // In C++03, we pick #2 as the best viable function.
3402 // In C++11, we pick #1 as the best viable function, because ellipsis
3403 // conversion is better than string-literal to char* conversion (since there
3404 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3405 // convert arguments, #2 would be the best viable function in C++11.
3406 // If the best viable function has this conversion, a warning will be issued
3407 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3408
3409 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3410 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3411 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3412 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3413 ? ImplicitConversionSequence::Worse
3414 : ImplicitConversionSequence::Better;
3415
Douglas Gregor5ab11652010-04-17 22:01:05 +00003416 if (ICS1.getKindRank() < ICS2.getKindRank())
3417 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003418 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003419 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003420
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003421 // The following checks require both conversion sequences to be of
3422 // the same kind.
3423 if (ICS1.getKind() != ICS2.getKind())
3424 return ImplicitConversionSequence::Indistinguishable;
3425
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003426 ImplicitConversionSequence::CompareKind Result =
3427 ImplicitConversionSequence::Indistinguishable;
3428
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003429 // Two implicit conversion sequences of the same form are
3430 // indistinguishable conversion sequences unless one of the
3431 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003432
3433 // List-initialization sequence L1 is a better conversion sequence than
3434 // list-initialization sequence L2 if:
3435 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3436 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003437 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003438 // and N1 is smaller than N2.,
3439 // even if one of the other rules in this paragraph would otherwise apply.
3440 if (!ICS1.isBad()) {
3441 if (ICS1.isStdInitializerListElement() &&
3442 !ICS2.isStdInitializerListElement())
3443 return ImplicitConversionSequence::Better;
3444 if (!ICS1.isStdInitializerListElement() &&
3445 ICS2.isStdInitializerListElement())
3446 return ImplicitConversionSequence::Worse;
3447 }
3448
John McCall0d1da222010-01-12 00:44:57 +00003449 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003450 // Standard conversion sequence S1 is a better conversion sequence than
3451 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003452 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003453 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003454 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003455 // User-defined conversion sequence U1 is a better conversion
3456 // sequence than another user-defined conversion sequence U2 if
3457 // they contain the same user-defined conversion function or
3458 // constructor and if the second standard conversion sequence of
3459 // U1 is better than the second standard conversion sequence of
3460 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003461 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003462 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003463 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003464 ICS1.UserDefined.After,
3465 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003466 else
3467 Result = compareConversionFunctions(S,
3468 ICS1.UserDefined.ConversionFunction,
3469 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470 }
3471
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003472 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003473}
3474
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003475static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3476 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3477 Qualifiers Quals;
3478 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003482 return Context.hasSameUnqualifiedType(T1, T2);
3483}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003485// Per 13.3.3.2p3, compare the given standard conversion sequences to
3486// determine if one is a proper subset of the other.
3487static ImplicitConversionSequence::CompareKind
3488compareStandardConversionSubsets(ASTContext &Context,
3489 const StandardConversionSequence& SCS1,
3490 const StandardConversionSequence& SCS2) {
3491 ImplicitConversionSequence::CompareKind Result
3492 = ImplicitConversionSequence::Indistinguishable;
3493
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003495 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003496 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3497 return ImplicitConversionSequence::Better;
3498 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3499 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003501 if (SCS1.Second != SCS2.Second) {
3502 if (SCS1.Second == ICK_Identity)
3503 Result = ImplicitConversionSequence::Better;
3504 else if (SCS2.Second == ICK_Identity)
3505 Result = ImplicitConversionSequence::Worse;
3506 else
3507 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003508 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003509 return ImplicitConversionSequence::Indistinguishable;
3510
3511 if (SCS1.Third == SCS2.Third) {
3512 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3513 : ImplicitConversionSequence::Indistinguishable;
3514 }
3515
3516 if (SCS1.Third == ICK_Identity)
3517 return Result == ImplicitConversionSequence::Worse
3518 ? ImplicitConversionSequence::Indistinguishable
3519 : ImplicitConversionSequence::Better;
3520
3521 if (SCS2.Third == ICK_Identity)
3522 return Result == ImplicitConversionSequence::Better
3523 ? ImplicitConversionSequence::Indistinguishable
3524 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003526 return ImplicitConversionSequence::Indistinguishable;
3527}
3528
Douglas Gregore696ebb2011-01-26 14:52:12 +00003529/// \brief Determine whether one of the given reference bindings is better
3530/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003531static bool
3532isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3533 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003534 // C++0x [over.ics.rank]p3b4:
3535 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3536 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003538 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003540 // reference*.
3541 //
3542 // FIXME: Rvalue references. We're going rogue with the above edits,
3543 // because the semantics in the current C++0x working paper (N3225 at the
3544 // time of this writing) break the standard definition of std::forward
3545 // and std::reference_wrapper when dealing with references to functions.
3546 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003547 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3548 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3549 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregore696ebb2011-01-26 14:52:12 +00003551 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3552 SCS2.IsLvalueReference) ||
3553 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003554 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003555}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003557/// CompareStandardConversionSequences - Compare two standard
3558/// conversion sequences to determine whether one is better than the
3559/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003560static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003561CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003562 const StandardConversionSequence& SCS1,
3563 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003564{
3565 // Standard conversion sequence S1 is a better conversion sequence
3566 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3567
3568 // -- S1 is a proper subsequence of S2 (comparing the conversion
3569 // sequences in the canonical form defined by 13.3.3.1.1,
3570 // excluding any Lvalue Transformation; the identity conversion
3571 // sequence is considered to be a subsequence of any
3572 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003573 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003574 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003575 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003576
3577 // -- the rank of S1 is better than the rank of S2 (by the rules
3578 // defined below), or, if not that,
3579 ImplicitConversionRank Rank1 = SCS1.getRank();
3580 ImplicitConversionRank Rank2 = SCS2.getRank();
3581 if (Rank1 < Rank2)
3582 return ImplicitConversionSequence::Better;
3583 else if (Rank2 < Rank1)
3584 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003585
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003586 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3587 // are indistinguishable unless one of the following rules
3588 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003589
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003590 // A conversion that is not a conversion of a pointer, or
3591 // pointer to member, to bool is better than another conversion
3592 // that is such a conversion.
3593 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3594 return SCS2.isPointerConversionToBool()
3595 ? ImplicitConversionSequence::Better
3596 : ImplicitConversionSequence::Worse;
3597
Douglas Gregor5c407d92008-10-23 00:40:37 +00003598 // C++ [over.ics.rank]p4b2:
3599 //
3600 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003601 // conversion of B* to A* is better than conversion of B* to
3602 // void*, and conversion of A* to void* is better than conversion
3603 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003604 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003605 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003606 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003607 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003608 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3609 // Exactly one of the conversion sequences is a conversion to
3610 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003611 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3612 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003613 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3614 // Neither conversion sequence converts to a void pointer; compare
3615 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003616 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003617 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003618 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003619 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3620 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003621 // Both conversion sequences are conversions to void
3622 // pointers. Compare the source types to determine if there's an
3623 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003624 QualType FromType1 = SCS1.getFromType();
3625 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003626
3627 // Adjust the types we're converting from via the array-to-pointer
3628 // conversion, if we need to.
3629 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003630 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003631 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003632 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003633
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003634 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3635 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003636
Richard Smith0f59cb32015-12-18 21:45:41 +00003637 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003638 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003639 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003640 return ImplicitConversionSequence::Worse;
3641
3642 // Objective-C++: If one interface is more specific than the
3643 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003644 const ObjCObjectPointerType* FromObjCPtr1
3645 = FromType1->getAs<ObjCObjectPointerType>();
3646 const ObjCObjectPointerType* FromObjCPtr2
3647 = FromType2->getAs<ObjCObjectPointerType>();
3648 if (FromObjCPtr1 && FromObjCPtr2) {
3649 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3650 FromObjCPtr2);
3651 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3652 FromObjCPtr1);
3653 if (AssignLeft != AssignRight) {
3654 return AssignLeft? ImplicitConversionSequence::Better
3655 : ImplicitConversionSequence::Worse;
3656 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003657 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003658 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003659
3660 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3661 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003662 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003663 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003664 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003665
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003666 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003667 // Check for a better reference binding based on the kind of bindings.
3668 if (isBetterReferenceBindingKind(SCS1, SCS2))
3669 return ImplicitConversionSequence::Better;
3670 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3671 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Sebastian Redlb28b4072009-03-22 23:49:27 +00003673 // C++ [over.ics.rank]p3b4:
3674 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3675 // which the references refer are the same type except for
3676 // top-level cv-qualifiers, and the type to which the reference
3677 // initialized by S2 refers is more cv-qualified than the type
3678 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003679 QualType T1 = SCS1.getToType(2);
3680 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003681 T1 = S.Context.getCanonicalType(T1);
3682 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003683 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003684 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3685 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003686 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003687 // Objective-C++ ARC: If the references refer to objects with different
3688 // lifetimes, prefer bindings that don't change lifetime.
3689 if (SCS1.ObjCLifetimeConversionBinding !=
3690 SCS2.ObjCLifetimeConversionBinding) {
3691 return SCS1.ObjCLifetimeConversionBinding
3692 ? ImplicitConversionSequence::Worse
3693 : ImplicitConversionSequence::Better;
3694 }
3695
Chandler Carruth8e543b32010-12-12 08:17:55 +00003696 // If the type is an array type, promote the element qualifiers to the
3697 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003698 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003699 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003700 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003701 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003702 if (T2.isMoreQualifiedThan(T1))
3703 return ImplicitConversionSequence::Better;
3704 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003705 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003706 }
3707 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003708
Francois Pichet08d2fa02011-09-18 21:37:37 +00003709 // In Microsoft mode, prefer an integral conversion to a
3710 // floating-to-integral conversion if the integral conversion
3711 // is between types of the same size.
3712 // For example:
3713 // void f(float);
3714 // void f(int);
3715 // int main {
3716 // long a;
3717 // f(a);
3718 // }
3719 // Here, MSVC will call f(int) instead of generating a compile error
3720 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003721 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3722 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003723 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003724 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003725 return ImplicitConversionSequence::Better;
3726
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003727 return ImplicitConversionSequence::Indistinguishable;
3728}
3729
3730/// CompareQualificationConversions - Compares two standard conversion
3731/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003732/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003733static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003734CompareQualificationConversions(Sema &S,
3735 const StandardConversionSequence& SCS1,
3736 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003737 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003738 // -- S1 and S2 differ only in their qualification conversion and
3739 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3740 // cv-qualification signature of type T1 is a proper subset of
3741 // the cv-qualification signature of type T2, and S1 is not the
3742 // deprecated string literal array-to-pointer conversion (4.2).
3743 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3744 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3745 return ImplicitConversionSequence::Indistinguishable;
3746
3747 // FIXME: the example in the standard doesn't use a qualification
3748 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003749 QualType T1 = SCS1.getToType(2);
3750 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003751 T1 = S.Context.getCanonicalType(T1);
3752 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003753 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003754 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3755 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003756
3757 // If the types are the same, we won't learn anything by unwrapped
3758 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003759 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003760 return ImplicitConversionSequence::Indistinguishable;
3761
Chandler Carruth607f38e2009-12-29 07:16:59 +00003762 // If the type is an array type, promote the element qualifiers to the type
3763 // for comparison.
3764 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003765 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003766 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003767 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003768
Mike Stump11289f42009-09-09 15:08:12 +00003769 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003770 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003771
3772 // Objective-C++ ARC:
3773 // Prefer qualification conversions not involving a change in lifetime
3774 // to qualification conversions that do not change lifetime.
3775 if (SCS1.QualificationIncludesObjCLifetime !=
3776 SCS2.QualificationIncludesObjCLifetime) {
3777 Result = SCS1.QualificationIncludesObjCLifetime
3778 ? ImplicitConversionSequence::Worse
3779 : ImplicitConversionSequence::Better;
3780 }
3781
John McCall5c32be02010-08-24 20:38:10 +00003782 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003783 // Within each iteration of the loop, we check the qualifiers to
3784 // determine if this still looks like a qualification
3785 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003786 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003787 // until there are no more pointers or pointers-to-members left
3788 // to unwrap. This essentially mimics what
3789 // IsQualificationConversion does, but here we're checking for a
3790 // strict subset of qualifiers.
3791 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3792 // The qualifiers are the same, so this doesn't tell us anything
3793 // about how the sequences rank.
3794 ;
3795 else if (T2.isMoreQualifiedThan(T1)) {
3796 // T1 has fewer qualifiers, so it could be the better sequence.
3797 if (Result == ImplicitConversionSequence::Worse)
3798 // Neither has qualifiers that are a subset of the other's
3799 // qualifiers.
3800 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003801
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003802 Result = ImplicitConversionSequence::Better;
3803 } else if (T1.isMoreQualifiedThan(T2)) {
3804 // T2 has fewer qualifiers, so it could be the better sequence.
3805 if (Result == ImplicitConversionSequence::Better)
3806 // Neither has qualifiers that are a subset of the other's
3807 // qualifiers.
3808 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003810 Result = ImplicitConversionSequence::Worse;
3811 } else {
3812 // Qualifiers are disjoint.
3813 return ImplicitConversionSequence::Indistinguishable;
3814 }
3815
3816 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003817 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003818 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003819 }
3820
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003821 // Check that the winning standard conversion sequence isn't using
3822 // the deprecated string literal array to pointer conversion.
3823 switch (Result) {
3824 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003825 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003826 Result = ImplicitConversionSequence::Indistinguishable;
3827 break;
3828
3829 case ImplicitConversionSequence::Indistinguishable:
3830 break;
3831
3832 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003833 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003834 Result = ImplicitConversionSequence::Indistinguishable;
3835 break;
3836 }
3837
3838 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003839}
3840
Douglas Gregor5c407d92008-10-23 00:40:37 +00003841/// CompareDerivedToBaseConversions - Compares two standard conversion
3842/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003843/// various kinds of derived-to-base conversions (C++
3844/// [over.ics.rank]p4b3). As part of these checks, we also look at
3845/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003846static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003847CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003848 const StandardConversionSequence& SCS1,
3849 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003850 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003851 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003852 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003853 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003854
3855 // Adjust the types we're converting from via the array-to-pointer
3856 // conversion, if we need to.
3857 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003858 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003859 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003860 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003861
3862 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003863 FromType1 = S.Context.getCanonicalType(FromType1);
3864 ToType1 = S.Context.getCanonicalType(ToType1);
3865 FromType2 = S.Context.getCanonicalType(FromType2);
3866 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003867
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003868 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003869 //
3870 // If class B is derived directly or indirectly from class A and
3871 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003872 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003873 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003874 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003875 SCS2.Second == ICK_Pointer_Conversion &&
3876 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3877 FromType1->isPointerType() && FromType2->isPointerType() &&
3878 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003879 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003880 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003881 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003882 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003883 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003884 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003885 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003886 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003887
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003888 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003889 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003890 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003891 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003892 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003893 return ImplicitConversionSequence::Worse;
3894 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003895
3896 // -- conversion of B* to A* is better than conversion of C* to A*,
3897 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003898 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003899 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003900 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003901 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003902 }
3903 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3904 SCS2.Second == ICK_Pointer_Conversion) {
3905 const ObjCObjectPointerType *FromPtr1
3906 = FromType1->getAs<ObjCObjectPointerType>();
3907 const ObjCObjectPointerType *FromPtr2
3908 = FromType2->getAs<ObjCObjectPointerType>();
3909 const ObjCObjectPointerType *ToPtr1
3910 = ToType1->getAs<ObjCObjectPointerType>();
3911 const ObjCObjectPointerType *ToPtr2
3912 = ToType2->getAs<ObjCObjectPointerType>();
3913
3914 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3915 // Apply the same conversion ranking rules for Objective-C pointer types
3916 // that we do for C++ pointers to class types. However, we employ the
3917 // Objective-C pseudo-subtyping relationship used for assignment of
3918 // Objective-C pointer types.
3919 bool FromAssignLeft
3920 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3921 bool FromAssignRight
3922 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3923 bool ToAssignLeft
3924 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3925 bool ToAssignRight
3926 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3927
3928 // A conversion to an a non-id object pointer type or qualified 'id'
3929 // type is better than a conversion to 'id'.
3930 if (ToPtr1->isObjCIdType() &&
3931 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3932 return ImplicitConversionSequence::Worse;
3933 if (ToPtr2->isObjCIdType() &&
3934 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3935 return ImplicitConversionSequence::Better;
3936
3937 // A conversion to a non-id object pointer type is better than a
3938 // conversion to a qualified 'id' type
3939 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3940 return ImplicitConversionSequence::Worse;
3941 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3942 return ImplicitConversionSequence::Better;
3943
3944 // A conversion to an a non-Class object pointer type or qualified 'Class'
3945 // type is better than a conversion to 'Class'.
3946 if (ToPtr1->isObjCClassType() &&
3947 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3948 return ImplicitConversionSequence::Worse;
3949 if (ToPtr2->isObjCClassType() &&
3950 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3951 return ImplicitConversionSequence::Better;
3952
3953 // A conversion to a non-Class object pointer type is better than a
3954 // conversion to a qualified 'Class' type.
3955 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3956 return ImplicitConversionSequence::Worse;
3957 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3958 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003959
Douglas Gregor058d3de2011-01-31 18:51:41 +00003960 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3961 if (S.Context.hasSameType(FromType1, FromType2) &&
3962 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3963 (ToAssignLeft != ToAssignRight))
3964 return ToAssignLeft? ImplicitConversionSequence::Worse
3965 : ImplicitConversionSequence::Better;
3966
3967 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3968 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3969 (FromAssignLeft != FromAssignRight))
3970 return FromAssignLeft? ImplicitConversionSequence::Better
3971 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003972 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003973 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003974
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003975 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003976 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3977 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3978 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003980 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003982 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003984 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003986 ToType2->getAs<MemberPointerType>();
3987 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3988 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3989 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3990 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3991 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3992 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3993 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3994 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003995 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003996 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003997 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003998 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00003999 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004000 return ImplicitConversionSequence::Better;
4001 }
4002 // conversion of B::* to C::* is better than conversion of A::* to C::*
4003 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004004 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004005 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004006 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004007 return ImplicitConversionSequence::Worse;
4008 }
4009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
Douglas Gregor5ab11652010-04-17 22:01:05 +00004011 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004012 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004013 // -- binding of an expression of type C to a reference of type
4014 // B& is better than binding an expression of type C to a
4015 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004016 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4017 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004018 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004019 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004020 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004021 return ImplicitConversionSequence::Worse;
4022 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004023
Douglas Gregor2fe98832008-11-03 19:09:14 +00004024 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004025 // -- binding of an expression of type B to a reference of type
4026 // A& is better than binding an expression of type C to a
4027 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004028 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4029 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004030 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004031 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004032 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004033 return ImplicitConversionSequence::Worse;
4034 }
4035 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004036
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037 return ImplicitConversionSequence::Indistinguishable;
4038}
4039
Douglas Gregor45bb4832013-03-26 23:36:30 +00004040/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4041/// C++ class.
4042static bool isTypeValid(QualType T) {
4043 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4044 return !Record->isInvalidDecl();
4045
4046 return true;
4047}
4048
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004049/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4050/// determine whether they are reference-related,
4051/// reference-compatible, reference-compatible with added
4052/// qualification, or incompatible, for use in C++ initialization by
4053/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4054/// type, and the first type (T1) is the pointee type of the reference
4055/// type being initialized.
4056Sema::ReferenceCompareResult
4057Sema::CompareReferenceRelationship(SourceLocation Loc,
4058 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004059 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004060 bool &ObjCConversion,
4061 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004062 assert(!OrigT1->isReferenceType() &&
4063 "T1 must be the pointee type of the reference type");
4064 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4065
4066 QualType T1 = Context.getCanonicalType(OrigT1);
4067 QualType T2 = Context.getCanonicalType(OrigT2);
4068 Qualifiers T1Quals, T2Quals;
4069 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4070 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4071
4072 // C++ [dcl.init.ref]p4:
4073 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4074 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4075 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004076 DerivedToBase = false;
4077 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004078 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004079 if (UnqualT1 == UnqualT2) {
4080 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004081 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004082 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004083 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004084 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004085 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4086 UnqualT2->isObjCObjectOrInterfaceType() &&
4087 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4088 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004089 else
4090 return Ref_Incompatible;
4091
4092 // At this point, we know that T1 and T2 are reference-related (at
4093 // least).
4094
4095 // If the type is an array type, promote the element qualifiers to the type
4096 // for comparison.
4097 if (isa<ArrayType>(T1) && T1Quals)
4098 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4099 if (isa<ArrayType>(T2) && T2Quals)
4100 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4101
4102 // C++ [dcl.init.ref]p4:
4103 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4104 // reference-related to T2 and cv1 is the same cv-qualification
4105 // as, or greater cv-qualification than, cv2. For purposes of
4106 // overload resolution, cases for which cv1 is greater
4107 // cv-qualification than cv2 are identified as
4108 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004109 //
4110 // Note that we also require equivalence of Objective-C GC and address-space
4111 // qualifiers when performing these computations, so that e.g., an int in
4112 // address space 1 is not reference-compatible with an int in address
4113 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004114 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4115 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004116 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4117 ObjCLifetimeConversion = true;
4118
John McCall31168b02011-06-15 23:02:42 +00004119 T1Quals.removeObjCLifetime();
4120 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004121 }
4122
Douglas Gregord517d552011-04-28 17:56:11 +00004123 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004124 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004125 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004126 return Ref_Compatible_With_Added_Qualification;
4127 else
4128 return Ref_Related;
4129}
4130
Douglas Gregor836a7e82010-08-11 02:15:33 +00004131/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004132/// with DeclType. Return true if something definite is found.
4133static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004134FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4135 QualType DeclType, SourceLocation DeclLoc,
4136 Expr *Init, QualType T2, bool AllowRvalues,
4137 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004138 assert(T2->isRecordType() && "Can only find conversions of record types.");
4139 CXXRecordDecl *T2RecordDecl
4140 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4141
Richard Smith100b24a2014-04-17 01:52:14 +00004142 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004143 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4144 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004145 NamedDecl *D = *I;
4146 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4147 if (isa<UsingShadowDecl>(D))
4148 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4149
4150 FunctionTemplateDecl *ConvTemplate
4151 = dyn_cast<FunctionTemplateDecl>(D);
4152 CXXConversionDecl *Conv;
4153 if (ConvTemplate)
4154 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4155 else
4156 Conv = cast<CXXConversionDecl>(D);
4157
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004159 // explicit conversions, skip it.
4160 if (!AllowExplicit && Conv->isExplicit())
4161 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
Douglas Gregor836a7e82010-08-11 02:15:33 +00004163 if (AllowRvalues) {
4164 bool DerivedToBase = false;
4165 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004166 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004167
4168 // If we are initializing an rvalue reference, don't permit conversion
4169 // functions that return lvalues.
4170 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4171 const ReferenceType *RefType
4172 = Conv->getConversionType()->getAs<LValueReferenceType>();
4173 if (RefType && !RefType->getPointeeType()->isFunctionType())
4174 continue;
4175 }
4176
Douglas Gregor836a7e82010-08-11 02:15:33 +00004177 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004178 S.CompareReferenceRelationship(
4179 DeclLoc,
4180 Conv->getConversionType().getNonReferenceType()
4181 .getUnqualifiedType(),
4182 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004183 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004184 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004185 continue;
4186 } else {
4187 // If the conversion function doesn't return a reference type,
4188 // it can't be considered for this conversion. An rvalue reference
4189 // is only acceptable if its referencee is a function type.
4190
4191 const ReferenceType *RefType =
4192 Conv->getConversionType()->getAs<ReferenceType>();
4193 if (!RefType ||
4194 (!RefType->isLValueReferenceType() &&
4195 !RefType->getPointeeType()->isFunctionType()))
4196 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198
Douglas Gregor836a7e82010-08-11 02:15:33 +00004199 if (ConvTemplate)
4200 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004201 Init, DeclType, CandidateSet,
4202 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004203 else
4204 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004205 DeclType, CandidateSet,
4206 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004207 }
4208
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004209 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4210
Sebastian Redld92badf2010-06-30 18:13:39 +00004211 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004212 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004213 case OR_Success:
4214 // C++ [over.ics.ref]p1:
4215 //
4216 // [...] If the parameter binds directly to the result of
4217 // applying a conversion function to the argument
4218 // expression, the implicit conversion sequence is a
4219 // user-defined conversion sequence (13.3.3.1.2), with the
4220 // second standard conversion sequence either an identity
4221 // conversion or, if the conversion function returns an
4222 // entity of a type that is a derived class of the parameter
4223 // type, a derived-to-base Conversion.
4224 if (!Best->FinalConversion.DirectBinding)
4225 return false;
4226
4227 ICS.setUserDefined();
4228 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4229 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004230 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004231 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004232 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 ICS.UserDefined.EllipsisConversion = false;
4234 assert(ICS.UserDefined.After.ReferenceBinding &&
4235 ICS.UserDefined.After.DirectBinding &&
4236 "Expected a direct reference binding!");
4237 return true;
4238
4239 case OR_Ambiguous:
4240 ICS.setAmbiguous();
4241 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4242 Cand != CandidateSet.end(); ++Cand)
4243 if (Cand->Viable)
4244 ICS.Ambiguous.addConversion(Cand->Function);
4245 return true;
4246
4247 case OR_No_Viable_Function:
4248 case OR_Deleted:
4249 // There was no suitable conversion, or we found a deleted
4250 // conversion; continue with other checks.
4251 return false;
4252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
David Blaikie8a40f702012-01-17 06:56:22 +00004254 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004255}
4256
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004257/// \brief Compute an implicit conversion sequence for reference
4258/// initialization.
4259static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004260TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261 SourceLocation DeclLoc,
4262 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004263 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004264 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4265
4266 // Most paths end in a failed conversion.
4267 ImplicitConversionSequence ICS;
4268 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4269
4270 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4271 QualType T2 = Init->getType();
4272
4273 // If the initializer is the address of an overloaded function, try
4274 // to resolve the overloaded function. If all goes well, T2 is the
4275 // type of the resulting function.
4276 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4277 DeclAccessPair Found;
4278 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4279 false, Found))
4280 T2 = Fn->getType();
4281 }
4282
4283 // Compute some basic properties of the types and the initializer.
4284 bool isRValRef = DeclType->isRValueReferenceType();
4285 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004286 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004287 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004288 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004289 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004290 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004291 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004292
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004293
Sebastian Redld92badf2010-06-30 18:13:39 +00004294 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004295 // A reference to type "cv1 T1" is initialized by an expression
4296 // of type "cv2 T2" as follows:
4297
Sebastian Redld92badf2010-06-30 18:13:39 +00004298 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004299 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004300 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4301 // reference-compatible with "cv2 T2," or
4302 //
4303 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4304 if (InitCategory.isLValue() &&
4305 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004306 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004307 // When a parameter of reference type binds directly (8.5.3)
4308 // to an argument expression, the implicit conversion sequence
4309 // is the identity conversion, unless the argument expression
4310 // has a type that is a derived class of the parameter type,
4311 // in which case the implicit conversion sequence is a
4312 // derived-to-base Conversion (13.3.3.1).
4313 ICS.setStandard();
4314 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004315 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4316 : ObjCConversion? ICK_Compatible_Conversion
4317 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004318 ICS.Standard.Third = ICK_Identity;
4319 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4320 ICS.Standard.setToType(0, T2);
4321 ICS.Standard.setToType(1, T1);
4322 ICS.Standard.setToType(2, T1);
4323 ICS.Standard.ReferenceBinding = true;
4324 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004325 ICS.Standard.IsLvalueReference = !isRValRef;
4326 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4327 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004328 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004329 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004330 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004331 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004332
Sebastian Redld92badf2010-06-30 18:13:39 +00004333 // Nothing more to do: the inaccessibility/ambiguity check for
4334 // derived-to-base conversions is suppressed when we're
4335 // computing the implicit conversion sequence (C++
4336 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004337 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004338 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004339
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 // -- has a class type (i.e., T2 is a class type), where T1 is
4341 // not reference-related to T2, and can be implicitly
4342 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4343 // is reference-compatible with "cv3 T3" 92) (this
4344 // conversion is selected by enumerating the applicable
4345 // conversion functions (13.3.1.6) and choosing the best
4346 // one through overload resolution (13.3)),
4347 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004348 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004349 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004350 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4351 Init, T2, /*AllowRvalues=*/false,
4352 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004353 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004354 }
4355 }
4356
Sebastian Redld92badf2010-06-30 18:13:39 +00004357 // -- Otherwise, the reference shall be an lvalue reference to a
4358 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004359 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004360 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004361 return ICS;
4362
Douglas Gregorf143cd52011-01-24 16:14:37 +00004363 // -- If the initializer expression
4364 //
4365 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004366 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004367 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4368 (InitCategory.isXValue() ||
4369 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4370 (InitCategory.isLValue() && T2->isFunctionType()))) {
4371 ICS.setStandard();
4372 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004374 : ObjCConversion? ICK_Compatible_Conversion
4375 : ICK_Identity;
4376 ICS.Standard.Third = ICK_Identity;
4377 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4378 ICS.Standard.setToType(0, T2);
4379 ICS.Standard.setToType(1, T1);
4380 ICS.Standard.setToType(2, T1);
4381 ICS.Standard.ReferenceBinding = true;
4382 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4383 // binding unless we're binding to a class prvalue.
4384 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4385 // allow the use of rvalue references in C++98/03 for the benefit of
4386 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004388 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004389 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004390 ICS.Standard.IsLvalueReference = !isRValRef;
4391 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004393 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004394 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004395 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004396 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregorf143cd52011-01-24 16:14:37 +00004400 // -- has a class type (i.e., T2 is a class type), where T1 is not
4401 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402 // an xvalue, class prvalue, or function lvalue of type
4403 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004404 // "cv3 T3",
4405 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004407 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004409 // class subobject).
4410 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004411 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004412 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4413 Init, T2, /*AllowRvalues=*/true,
4414 AllowExplicit)) {
4415 // In the second case, if the reference is an rvalue reference
4416 // and the second standard conversion sequence of the
4417 // user-defined conversion sequence includes an lvalue-to-rvalue
4418 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004420 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4421 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4422
Douglas Gregor95273c32011-01-21 16:36:05 +00004423 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Richard Smith19172c42014-07-14 02:28:44 +00004426 // A temporary of function type cannot be created; don't even try.
4427 if (T1->isFunctionType())
4428 return ICS;
4429
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004430 // -- Otherwise, a temporary of type "cv1 T1" is created and
4431 // initialized from the initializer expression using the
4432 // rules for a non-reference copy initialization (8.5). The
4433 // reference is then bound to the temporary. If T1 is
4434 // reference-related to T2, cv1 must be the same
4435 // cv-qualification as, or greater cv-qualification than,
4436 // cv2; otherwise, the program is ill-formed.
4437 if (RefRelationship == Sema::Ref_Related) {
4438 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4439 // we would be reference-compatible or reference-compatible with
4440 // added qualification. But that wasn't the case, so the reference
4441 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004442 //
4443 // Note that we only want to check address spaces and cvr-qualifiers here.
4444 // ObjC GC and lifetime qualifiers aren't important.
4445 Qualifiers T1Quals = T1.getQualifiers();
4446 Qualifiers T2Quals = T2.getQualifiers();
4447 T1Quals.removeObjCGCAttr();
4448 T1Quals.removeObjCLifetime();
4449 T2Quals.removeObjCGCAttr();
4450 T2Quals.removeObjCLifetime();
4451 if (!T1Quals.compatiblyIncludes(T2Quals))
4452 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004453 }
4454
4455 // If at least one of the types is a class type, the types are not
4456 // related, and we aren't allowed any user conversions, the
4457 // reference binding fails. This case is important for breaking
4458 // recursion, since TryImplicitConversion below will attempt to
4459 // create a temporary through the use of a copy constructor.
4460 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4461 (T1->isRecordType() || T2->isRecordType()))
4462 return ICS;
4463
Douglas Gregorcba72b12011-01-21 05:18:22 +00004464 // If T1 is reference-related to T2 and the reference is an rvalue
4465 // reference, the initializer expression shall not be an lvalue.
4466 if (RefRelationship >= Sema::Ref_Related &&
4467 isRValRef && Init->Classify(S.Context).isLValue())
4468 return ICS;
4469
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004470 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004471 // When a parameter of reference type is not bound directly to
4472 // an argument expression, the conversion sequence is the one
4473 // required to convert the argument expression to the
4474 // underlying type of the reference according to
4475 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4476 // to copy-initializing a temporary of the underlying type with
4477 // the argument expression. Any difference in top-level
4478 // cv-qualification is subsumed by the initialization itself
4479 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004480 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4481 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004482 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004483 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004484 /*AllowObjCWritebackConversion=*/false,
4485 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004486
4487 // Of course, that's still a reference binding.
4488 if (ICS.isStandard()) {
4489 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004490 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004491 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004492 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004493 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004494 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004495 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004496 const ReferenceType *LValRefType =
4497 ICS.UserDefined.ConversionFunction->getReturnType()
4498 ->getAs<LValueReferenceType>();
4499
4500 // C++ [over.ics.ref]p3:
4501 // Except for an implicit object parameter, for which see 13.3.1, a
4502 // standard conversion sequence cannot be formed if it requires [...]
4503 // binding an rvalue reference to an lvalue other than a function
4504 // lvalue.
4505 // Note that the function case is not possible here.
4506 if (DeclType->isRValueReferenceType() && LValRefType) {
4507 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4508 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4509 // reference to an rvalue!
4510 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4511 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004512 }
Richard Smith19172c42014-07-14 02:28:44 +00004513
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004514 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004515 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004516 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004517 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4518 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004519 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4520 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004521 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004522
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004523 return ICS;
4524}
4525
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004526static ImplicitConversionSequence
4527TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4528 bool SuppressUserConversions,
4529 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004530 bool AllowObjCWritebackConversion,
4531 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004532
4533/// TryListConversion - Try to copy-initialize a value of type ToType from the
4534/// initializer list From.
4535static ImplicitConversionSequence
4536TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4537 bool SuppressUserConversions,
4538 bool InOverloadResolution,
4539 bool AllowObjCWritebackConversion) {
4540 // C++11 [over.ics.list]p1:
4541 // When an argument is an initializer list, it is not an expression and
4542 // special rules apply for converting it to a parameter type.
4543
4544 ImplicitConversionSequence Result;
4545 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4546
Sebastian Redl09edce02012-01-23 22:09:39 +00004547 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004548 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004549 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004550 return Result;
4551
Larisse Voufo19d08672015-01-27 18:47:05 +00004552 // Per DR1467:
4553 // If the parameter type is a class X and the initializer list has a single
4554 // element of type cv U, where U is X or a class derived from X, the
4555 // implicit conversion sequence is the one required to convert the element
4556 // to the parameter type.
4557 //
4558 // Otherwise, if the parameter type is a character array [... ]
4559 // and the initializer list has a single element that is an
4560 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4561 // implicit conversion sequence is the identity conversion.
4562 if (From->getNumInits() == 1) {
4563 if (ToType->isRecordType()) {
4564 QualType InitType = From->getInit(0)->getType();
4565 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004566 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004567 return TryCopyInitialization(S, From->getInit(0), ToType,
4568 SuppressUserConversions,
4569 InOverloadResolution,
4570 AllowObjCWritebackConversion);
4571 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004572 // FIXME: Check the other conditions here: array of character type,
4573 // initializer is a string literal.
4574 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004575 InitializedEntity Entity =
4576 InitializedEntity::InitializeParameter(S.Context, ToType,
4577 /*Consumed=*/false);
4578 if (S.CanPerformCopyInitialization(Entity, From)) {
4579 Result.setStandard();
4580 Result.Standard.setAsIdentityConversion();
4581 Result.Standard.setFromType(ToType);
4582 Result.Standard.setAllToTypes(ToType);
4583 return Result;
4584 }
4585 }
4586 }
4587
4588 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004589 // C++11 [over.ics.list]p2:
4590 // If the parameter type is std::initializer_list<X> or "array of X" and
4591 // all the elements can be implicitly converted to X, the implicit
4592 // conversion sequence is the worst conversion necessary to convert an
4593 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004594 //
4595 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004596 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004597 // list has exactly N elements or if it has fewer than N elements and X is
4598 // default-constructible, and if all the elements of the initializer list
4599 // can be implicitly converted to X, the implicit conversion sequence is
4600 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004601 //
4602 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004603 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004604 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004605 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004606 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004607 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004608 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004609 if (!X.isNull()) {
4610 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4611 Expr *Init = From->getInit(i);
4612 ImplicitConversionSequence ICS =
4613 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4614 InOverloadResolution,
4615 AllowObjCWritebackConversion);
4616 // If a single element isn't convertible, fail.
4617 if (ICS.isBad()) {
4618 Result = ICS;
4619 break;
4620 }
4621 // Otherwise, look for the worst conversion.
4622 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004623 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4624 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004625 ImplicitConversionSequence::Worse)
4626 Result = ICS;
4627 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004628
4629 // For an empty list, we won't have computed any conversion sequence.
4630 // Introduce the identity conversion sequence.
4631 if (From->getNumInits() == 0) {
4632 Result.setStandard();
4633 Result.Standard.setAsIdentityConversion();
4634 Result.Standard.setFromType(ToType);
4635 Result.Standard.setAllToTypes(ToType);
4636 }
4637
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004638 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004639 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004640 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004641
Larisse Voufo19d08672015-01-27 18:47:05 +00004642 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004643 // C++11 [over.ics.list]p3:
4644 // Otherwise, if the parameter is a non-aggregate class X and overload
4645 // resolution chooses a single best constructor [...] the implicit
4646 // conversion sequence is a user-defined conversion sequence. If multiple
4647 // constructors are viable but none is better than the others, the
4648 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004649 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4650 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004651 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4652 /*AllowExplicit=*/false,
4653 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004654 AllowObjCWritebackConversion,
4655 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004656 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004657
Larisse Voufo19d08672015-01-27 18:47:05 +00004658 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004659 // C++11 [over.ics.list]p4:
4660 // Otherwise, if the parameter has an aggregate type which can be
4661 // initialized from the initializer list [...] the implicit conversion
4662 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004663 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004664 // Type is an aggregate, argument is an init list. At this point it comes
4665 // down to checking whether the initialization works.
4666 // FIXME: Find out whether this parameter is consumed or not.
4667 InitializedEntity Entity =
4668 InitializedEntity::InitializeParameter(S.Context, ToType,
4669 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004670 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004671 Result.setUserDefined();
4672 Result.UserDefined.Before.setAsIdentityConversion();
4673 // Initializer lists don't have a type.
4674 Result.UserDefined.Before.setFromType(QualType());
4675 Result.UserDefined.Before.setAllToTypes(QualType());
4676
4677 Result.UserDefined.After.setAsIdentityConversion();
4678 Result.UserDefined.After.setFromType(ToType);
4679 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004680 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004681 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004682 return Result;
4683 }
4684
Larisse Voufo19d08672015-01-27 18:47:05 +00004685 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004686 // C++11 [over.ics.list]p5:
4687 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004688 if (ToType->isReferenceType()) {
4689 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4690 // mention initializer lists in any way. So we go by what list-
4691 // initialization would do and try to extrapolate from that.
4692
4693 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4694
4695 // If the initializer list has a single element that is reference-related
4696 // to the parameter type, we initialize the reference from that.
4697 if (From->getNumInits() == 1) {
4698 Expr *Init = From->getInit(0);
4699
4700 QualType T2 = Init->getType();
4701
4702 // If the initializer is the address of an overloaded function, try
4703 // to resolve the overloaded function. If all goes well, T2 is the
4704 // type of the resulting function.
4705 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4706 DeclAccessPair Found;
4707 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4708 Init, ToType, false, Found))
4709 T2 = Fn->getType();
4710 }
4711
4712 // Compute some basic properties of the types and the initializer.
4713 bool dummy1 = false;
4714 bool dummy2 = false;
4715 bool dummy3 = false;
4716 Sema::ReferenceCompareResult RefRelationship
4717 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4718 dummy2, dummy3);
4719
Richard Smith4d2bbd72013-09-06 01:22:42 +00004720 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004721 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4722 SuppressUserConversions,
4723 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004724 }
Sebastian Redldf888642011-12-03 14:54:30 +00004725 }
4726
4727 // Otherwise, we bind the reference to a temporary created from the
4728 // initializer list.
4729 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4730 InOverloadResolution,
4731 AllowObjCWritebackConversion);
4732 if (Result.isFailure())
4733 return Result;
4734 assert(!Result.isEllipsis() &&
4735 "Sub-initialization cannot result in ellipsis conversion.");
4736
4737 // Can we even bind to a temporary?
4738 if (ToType->isRValueReferenceType() ||
4739 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4740 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4741 Result.UserDefined.After;
4742 SCS.ReferenceBinding = true;
4743 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4744 SCS.BindsToRvalue = true;
4745 SCS.BindsToFunctionLvalue = false;
4746 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4747 SCS.ObjCLifetimeConversionBinding = false;
4748 } else
4749 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4750 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004751 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004752 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004753
Larisse Voufo19d08672015-01-27 18:47:05 +00004754 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004755 // C++11 [over.ics.list]p6:
4756 // Otherwise, if the parameter type is not a class:
4757 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004758 // - if the initializer list has one element that is not itself an
4759 // initializer list, the implicit conversion sequence is the one
4760 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004761 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004762 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004763 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4764 SuppressUserConversions,
4765 InOverloadResolution,
4766 AllowObjCWritebackConversion);
4767 // - if the initializer list has no elements, the implicit conversion
4768 // sequence is the identity conversion.
4769 else if (NumInits == 0) {
4770 Result.setStandard();
4771 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004772 Result.Standard.setFromType(ToType);
4773 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004774 }
4775 return Result;
4776 }
4777
Larisse Voufo19d08672015-01-27 18:47:05 +00004778 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004779 // C++11 [over.ics.list]p7:
4780 // In all cases other than those enumerated above, no conversion is possible
4781 return Result;
4782}
4783
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004784/// TryCopyInitialization - Try to copy-initialize a value of type
4785/// ToType from the expression From. Return the implicit conversion
4786/// sequence required to pass this argument, which may be a bad
4787/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004788/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004789/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004790static ImplicitConversionSequence
4791TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004793 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004794 bool AllowObjCWritebackConversion,
4795 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004796 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4797 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4798 InOverloadResolution,AllowObjCWritebackConversion);
4799
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004800 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004801 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004802 /*FIXME:*/From->getLocStart(),
4803 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004804 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004805
John McCall5c32be02010-08-24 20:38:10 +00004806 return TryImplicitConversion(S, From, ToType,
4807 SuppressUserConversions,
4808 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004809 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004810 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004811 AllowObjCWritebackConversion,
4812 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004813}
4814
Anna Zaks1b068122011-07-28 19:46:48 +00004815static bool TryCopyInitialization(const CanQualType FromQTy,
4816 const CanQualType ToQTy,
4817 Sema &S,
4818 SourceLocation Loc,
4819 ExprValueKind FromVK) {
4820 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4821 ImplicitConversionSequence ICS =
4822 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4823
4824 return !ICS.isBad();
4825}
4826
Douglas Gregor436424c2008-11-18 23:14:02 +00004827/// TryObjectArgumentInitialization - Try to initialize the object
4828/// parameter of the given member function (@c Method) from the
4829/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004830static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004831TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004832 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004833 CXXMethodDecl *Method,
4834 CXXRecordDecl *ActingContext) {
4835 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004836 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4837 // const volatile object.
4838 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4839 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004840 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004841
4842 // Set up the conversion sequence as a "bad" conversion, to allow us
4843 // to exit early.
4844 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004845
4846 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004847 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 FromType = PT->getPointeeType();
4849
Douglas Gregor02824322011-01-26 19:30:28 +00004850 // When we had a pointer, it's implicitly dereferenced, so we
4851 // better have an lvalue.
4852 assert(FromClassification.isLValue());
4853 }
4854
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004856
Douglas Gregor02824322011-01-26 19:30:28 +00004857 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004859 // parameter is
4860 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004861 // - "lvalue reference to cv X" for functions declared without a
4862 // ref-qualifier or with the & ref-qualifier
4863 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004864 // ref-qualifier
4865 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004867 // cv-qualification on the member function declaration.
4868 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004870 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004871 // (C++ [over.match.funcs]p5). We perform a simplified version of
4872 // reference binding here, that allows class rvalues to bind to
4873 // non-constant references.
4874
Douglas Gregor02824322011-01-26 19:30:28 +00004875 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004876 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004878 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004879 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004880 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004881 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004882 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004883 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004884
4885 // Check that we have either the same type or a derived type. It
4886 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004887 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004888 ImplicitConversionKind SecondKind;
4889 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4890 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004891 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004892 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004893 else {
John McCall65eb8792010-02-25 01:37:24 +00004894 ICS.setBad(BadConversionSequence::unrelated_class,
4895 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004896 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004897 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004898
Douglas Gregor02824322011-01-26 19:30:28 +00004899 // Check the ref-qualifier.
4900 switch (Method->getRefQualifier()) {
4901 case RQ_None:
4902 // Do nothing; we don't care about lvalueness or rvalueness.
4903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904
Douglas Gregor02824322011-01-26 19:30:28 +00004905 case RQ_LValue:
4906 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4907 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004909 ImplicitParamType);
4910 return ICS;
4911 }
4912 break;
4913
4914 case RQ_RValue:
4915 if (!FromClassification.isRValue()) {
4916 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004918 ImplicitParamType);
4919 return ICS;
4920 }
4921 break;
4922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923
Douglas Gregor436424c2008-11-18 23:14:02 +00004924 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004925 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004926 ICS.Standard.setAsIdentityConversion();
4927 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004928 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004929 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004930 ICS.Standard.ReferenceBinding = true;
4931 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004933 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004934 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4935 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4936 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004937 return ICS;
4938}
4939
4940/// PerformObjectArgumentInitialization - Perform initialization of
4941/// the implicit object parameter for the given Method with the given
4942/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004943ExprResult
4944Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004946 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004947 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004948 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004949 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004950 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004951
Douglas Gregor02824322011-01-26 19:30:28 +00004952 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004953 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004954 FromRecordType = PT->getPointeeType();
4955 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004956 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004957 } else {
4958 FromRecordType = From->getType();
4959 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004960 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004961 }
4962
John McCall6e9f8f62009-12-03 04:06:58 +00004963 // Note that we always use the true parent context when performing
4964 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004965 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004966 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4967 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004968 if (ICS.isBad()) {
4969 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4970 Qualifiers FromQs = FromRecordType.getQualifiers();
4971 Qualifiers ToQs = DestType.getQualifiers();
4972 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4973 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004974 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004975 diag::err_member_function_call_bad_cvr)
4976 << Method->getDeclName() << FromRecordType << (CVR - 1)
4977 << From->getSourceRange();
4978 Diag(Method->getLocation(), diag::note_previous_decl)
4979 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004980 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004981 }
4982 }
4983
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004984 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004985 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004986 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004987 }
Mike Stump11289f42009-09-09 15:08:12 +00004988
John Wiegley01296292011-04-08 18:41:53 +00004989 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4990 ExprResult FromRes =
4991 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4992 if (FromRes.isInvalid())
4993 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004994 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004995 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004996
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004997 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004998 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004999 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005000 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005001}
5002
Douglas Gregor5fb53972009-01-14 15:45:31 +00005003/// TryContextuallyConvertToBool - Attempt to contextually convert the
5004/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005005static ImplicitConversionSequence
5006TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005007 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005008 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005009 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005010 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005011 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005012 /*AllowObjCWritebackConversion=*/false,
5013 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005014}
5015
5016/// PerformContextuallyConvertToBool - Perform a contextual conversion
5017/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005018ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005019 if (checkPlaceholderForOverload(*this, From))
5020 return ExprError();
5021
John McCall5c32be02010-08-24 20:38:10 +00005022 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005023 if (!ICS.isBad())
5024 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
Fariborz Jahanian76197412009-11-18 18:26:29 +00005026 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005027 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005028 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005029 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005030 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005031}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032
Richard Smithf8379a02012-01-18 23:55:52 +00005033/// Check that the specified conversion is permitted in a converted constant
5034/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5035/// is acceptable.
5036static bool CheckConvertedConstantConversions(Sema &S,
5037 StandardConversionSequence &SCS) {
5038 // Since we know that the target type is an integral or unscoped enumeration
5039 // type, most conversion kinds are impossible. All possible First and Third
5040 // conversions are fine.
5041 switch (SCS.Second) {
5042 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005043 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005044 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005045 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005046 return true;
5047
5048 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005049 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005050 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5051 // conversion, so we allow it in a converted constant expression.
5052 //
5053 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5054 // a lot of popular code. We should at least add a warning for this
5055 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005056 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5057 SCS.getToType(2)->isBooleanType();
5058
Richard Smith410cc892014-11-26 03:26:53 +00005059 case ICK_Pointer_Conversion:
5060 case ICK_Pointer_Member:
5061 // C++1z: null pointer conversions and null member pointer conversions are
5062 // only permitted if the source type is std::nullptr_t.
5063 return SCS.getFromType()->isNullPtrType();
5064
5065 case ICK_Floating_Promotion:
5066 case ICK_Complex_Promotion:
5067 case ICK_Floating_Conversion:
5068 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005069 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005070 case ICK_Compatible_Conversion:
5071 case ICK_Derived_To_Base:
5072 case ICK_Vector_Conversion:
5073 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005074 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005075 case ICK_Block_Pointer_Conversion:
5076 case ICK_TransparentUnionConversion:
5077 case ICK_Writeback_Conversion:
5078 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005079 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005080 return false;
5081
5082 case ICK_Lvalue_To_Rvalue:
5083 case ICK_Array_To_Pointer:
5084 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005085 llvm_unreachable("found a first conversion kind in Second");
5086
Richard Smithf8379a02012-01-18 23:55:52 +00005087 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005088 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005089
5090 case ICK_Num_Conversion_Kinds:
5091 break;
5092 }
5093
5094 llvm_unreachable("unknown conversion kind");
5095}
5096
5097/// CheckConvertedConstantExpression - Check that the expression From is a
5098/// converted constant expression of type T, perform the conversion and produce
5099/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005100static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5101 QualType T, APValue &Value,
5102 Sema::CCEKind CCE,
5103 bool RequireInt) {
5104 assert(S.getLangOpts().CPlusPlus11 &&
5105 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005106
Richard Smith410cc892014-11-26 03:26:53 +00005107 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005108 return ExprError();
5109
Richard Smith410cc892014-11-26 03:26:53 +00005110 // C++1z [expr.const]p3:
5111 // A converted constant expression of type T is an expression,
5112 // implicitly converted to type T, where the converted
5113 // expression is a constant expression and the implicit conversion
5114 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005115 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005116 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005117 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005118 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005119 /*AllowObjcWritebackConversion=*/false,
5120 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005121 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005122 switch (ICS.getKind()) {
5123 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005124 SCS = &ICS.Standard;
5125 break;
5126 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005127 // We are converting to a non-class type, so the Before sequence
5128 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005129 SCS = &ICS.UserDefined.After;
5130 break;
5131 case ImplicitConversionSequence::AmbiguousConversion:
5132 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005133 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5134 return S.Diag(From->getLocStart(),
5135 diag::err_typecheck_converted_constant_expression)
5136 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005137 return ExprError();
5138
5139 case ImplicitConversionSequence::EllipsisConversion:
5140 llvm_unreachable("ellipsis conversion in converted constant expression");
5141 }
5142
Richard Smith410cc892014-11-26 03:26:53 +00005143 // Check that we would only use permitted conversions.
5144 if (!CheckConvertedConstantConversions(S, *SCS)) {
5145 return S.Diag(From->getLocStart(),
5146 diag::err_typecheck_converted_constant_expression_disallowed)
5147 << From->getType() << From->getSourceRange() << T;
5148 }
5149 // [...] and where the reference binding (if any) binds directly.
5150 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5151 return S.Diag(From->getLocStart(),
5152 diag::err_typecheck_converted_constant_expression_indirect)
5153 << From->getType() << From->getSourceRange() << T;
5154 }
5155
5156 ExprResult Result =
5157 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005158 if (Result.isInvalid())
5159 return Result;
5160
5161 // Check for a narrowing implicit conversion.
5162 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005163 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005164 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005165 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005166 case NK_Variable_Narrowing:
5167 // Implicit conversion to a narrower type, and the value is not a constant
5168 // expression. We'll diagnose this in a moment.
5169 case NK_Not_Narrowing:
5170 break;
5171
5172 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005173 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005174 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005175 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005176 break;
5177
5178 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005179 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005180 << CCE << /*Constant*/0 << From->getType() << T;
5181 break;
5182 }
5183
5184 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005185 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005186 Expr::EvalResult Eval;
5187 Eval.Diag = &Notes;
5188
Richard Smith410cc892014-11-26 03:26:53 +00005189 if ((T->isReferenceType()
5190 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5191 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5192 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005193 // The expression can't be folded, so we can't keep it at this position in
5194 // the AST.
5195 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005196 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005197 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005198
5199 if (Notes.empty()) {
5200 // It's a constant expression.
5201 return Result;
5202 }
Richard Smithf8379a02012-01-18 23:55:52 +00005203 }
5204
5205 // It's not a constant expression. Produce an appropriate diagnostic.
5206 if (Notes.size() == 1 &&
5207 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005208 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005209 else {
Richard Smith410cc892014-11-26 03:26:53 +00005210 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005211 << CCE << From->getSourceRange();
5212 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005213 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005214 }
Richard Smith410cc892014-11-26 03:26:53 +00005215 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005216}
5217
Richard Smith410cc892014-11-26 03:26:53 +00005218ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5219 APValue &Value, CCEKind CCE) {
5220 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5221}
5222
5223ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5224 llvm::APSInt &Value,
5225 CCEKind CCE) {
5226 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5227
5228 APValue V;
5229 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5230 if (!R.isInvalid())
5231 Value = V.getInt();
5232 return R;
5233}
5234
5235
John McCallfec112d2011-09-09 06:11:02 +00005236/// dropPointerConversions - If the given standard conversion sequence
5237/// involves any pointer conversions, remove them. This may change
5238/// the result type of the conversion sequence.
5239static void dropPointerConversion(StandardConversionSequence &SCS) {
5240 if (SCS.Second == ICK_Pointer_Conversion) {
5241 SCS.Second = ICK_Identity;
5242 SCS.Third = ICK_Identity;
5243 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5244 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005245}
John McCall5c32be02010-08-24 20:38:10 +00005246
John McCallfec112d2011-09-09 06:11:02 +00005247/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5248/// convert the expression From to an Objective-C pointer type.
5249static ImplicitConversionSequence
5250TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5251 // Do an implicit conversion to 'id'.
5252 QualType Ty = S.Context.getObjCIdType();
5253 ImplicitConversionSequence ICS
5254 = TryImplicitConversion(S, From, Ty,
5255 // FIXME: Are these flags correct?
5256 /*SuppressUserConversions=*/false,
5257 /*AllowExplicit=*/true,
5258 /*InOverloadResolution=*/false,
5259 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005260 /*AllowObjCWritebackConversion=*/false,
5261 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005262
5263 // Strip off any final conversions to 'id'.
5264 switch (ICS.getKind()) {
5265 case ImplicitConversionSequence::BadConversion:
5266 case ImplicitConversionSequence::AmbiguousConversion:
5267 case ImplicitConversionSequence::EllipsisConversion:
5268 break;
5269
5270 case ImplicitConversionSequence::UserDefinedConversion:
5271 dropPointerConversion(ICS.UserDefined.After);
5272 break;
5273
5274 case ImplicitConversionSequence::StandardConversion:
5275 dropPointerConversion(ICS.Standard);
5276 break;
5277 }
5278
5279 return ICS;
5280}
5281
5282/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5283/// conversion of the expression From to an Objective-C pointer type.
5284ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005285 if (checkPlaceholderForOverload(*this, From))
5286 return ExprError();
5287
John McCall8b07ec22010-05-15 11:32:37 +00005288 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005289 ImplicitConversionSequence ICS =
5290 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005291 if (!ICS.isBad())
5292 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005293 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005294}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005295
Richard Smith8dd34252012-02-04 07:07:42 +00005296/// Determine whether the provided type is an integral type, or an enumeration
5297/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005298bool Sema::ICEConvertDiagnoser::match(QualType T) {
5299 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5300 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005301}
5302
Larisse Voufo236bec22013-06-10 06:50:24 +00005303static ExprResult
5304diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5305 Sema::ContextualImplicitConverter &Converter,
5306 QualType T, UnresolvedSetImpl &ViableConversions) {
5307
5308 if (Converter.Suppress)
5309 return ExprError();
5310
5311 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5313 CXXConversionDecl *Conv =
5314 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5315 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5316 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5317 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005318 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005319}
5320
5321static bool
5322diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5323 Sema::ContextualImplicitConverter &Converter,
5324 QualType T, bool HadMultipleCandidates,
5325 UnresolvedSetImpl &ExplicitConversions) {
5326 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5327 DeclAccessPair Found = ExplicitConversions[0];
5328 CXXConversionDecl *Conversion =
5329 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5330
5331 // The user probably meant to invoke the given explicit
5332 // conversion; use it.
5333 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5334 std::string TypeStr;
5335 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5336
5337 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5338 << FixItHint::CreateInsertion(From->getLocStart(),
5339 "static_cast<" + TypeStr + ">(")
5340 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005341 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005342 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5343
5344 // If we aren't in a SFINAE context, build a call to the
5345 // explicit conversion function.
5346 if (SemaRef.isSFINAEContext())
5347 return true;
5348
Craig Topperc3ec1492014-05-26 06:22:03 +00005349 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005350 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5351 HadMultipleCandidates);
5352 if (Result.isInvalid())
5353 return true;
5354 // Record usage of conversion in an implicit cast.
5355 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005356 CK_UserDefinedConversion, Result.get(),
5357 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005358 }
5359 return false;
5360}
5361
5362static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5363 Sema::ContextualImplicitConverter &Converter,
5364 QualType T, bool HadMultipleCandidates,
5365 DeclAccessPair &Found) {
5366 CXXConversionDecl *Conversion =
5367 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005368 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005369
5370 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5371 if (!Converter.SuppressConversion) {
5372 if (SemaRef.isSFINAEContext())
5373 return true;
5374
5375 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5376 << From->getSourceRange();
5377 }
5378
5379 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5380 HadMultipleCandidates);
5381 if (Result.isInvalid())
5382 return true;
5383 // Record usage of conversion in an implicit cast.
5384 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005385 CK_UserDefinedConversion, Result.get(),
5386 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005387 return false;
5388}
5389
5390static ExprResult finishContextualImplicitConversion(
5391 Sema &SemaRef, SourceLocation Loc, Expr *From,
5392 Sema::ContextualImplicitConverter &Converter) {
5393 if (!Converter.match(From->getType()) && !Converter.Suppress)
5394 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5395 << From->getSourceRange();
5396
5397 return SemaRef.DefaultLvalueConversion(From);
5398}
5399
5400static void
5401collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5402 UnresolvedSetImpl &ViableConversions,
5403 OverloadCandidateSet &CandidateSet) {
5404 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5405 DeclAccessPair FoundDecl = ViableConversions[I];
5406 NamedDecl *D = FoundDecl.getDecl();
5407 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5408 if (isa<UsingShadowDecl>(D))
5409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5410
5411 CXXConversionDecl *Conv;
5412 FunctionTemplateDecl *ConvTemplate;
5413 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5414 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5415 else
5416 Conv = cast<CXXConversionDecl>(D);
5417
5418 if (ConvTemplate)
5419 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005420 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5421 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005422 else
5423 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005424 ToType, CandidateSet,
5425 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 }
5427}
5428
Richard Smithccc11812013-05-21 19:05:48 +00005429/// \brief Attempt to convert the given expression to a type which is accepted
5430/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005431///
Richard Smithccc11812013-05-21 19:05:48 +00005432/// This routine will attempt to convert an expression of class type to a
5433/// type accepted by the specified converter. In C++11 and before, the class
5434/// must have a single non-explicit conversion function converting to a matching
5435/// type. In C++1y, there can be multiple such conversion functions, but only
5436/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005437///
Douglas Gregor4799d032010-06-30 00:20:43 +00005438/// \param Loc The source location of the construct that requires the
5439/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005440///
James Dennett18348b62012-06-22 08:52:37 +00005441/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005442///
Richard Smithccc11812013-05-21 19:05:48 +00005443/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005444///
Douglas Gregor4799d032010-06-30 00:20:43 +00005445/// \returns The expression, converted to an integral or enumeration type if
5446/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005447ExprResult Sema::PerformContextualImplicitConversion(
5448 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005449 // We can't perform any more checking for type-dependent expressions.
5450 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005451 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005452
Eli Friedman1da70392012-01-26 00:26:18 +00005453 // Process placeholders immediately.
5454 if (From->hasPlaceholderType()) {
5455 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005456 if (result.isInvalid())
5457 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005458 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005459 }
5460
Richard Smithccc11812013-05-21 19:05:48 +00005461 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005462 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005463 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005464 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005465
5466 // FIXME: Check for missing '()' if T is a function type?
5467
Richard Smithccc11812013-05-21 19:05:48 +00005468 // We can only perform contextual implicit conversions on objects of class
5469 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005470 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005471 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005472 if (!Converter.Suppress)
5473 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005474 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005476
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005477 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005478 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005479 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005480 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005481
5482 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005483 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005484
Craig Toppere14c0f82014-03-12 04:55:44 +00005485 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005486 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005487 }
Richard Smithccc11812013-05-21 19:05:48 +00005488 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005489
Richard Smithdb0ac552015-12-18 22:40:25 +00005490 if (Converter.Suppress ? !isCompleteType(Loc, T)
5491 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005492 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005494 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005495 UnresolvedSet<4>
5496 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005497 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005498 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005499 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Larisse Voufo236bec22013-06-10 06:50:24 +00005501 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005502 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005503
Larisse Voufo236bec22013-06-10 06:50:24 +00005504 // To check that there is only one target type, in C++1y:
5505 QualType ToType;
5506 bool HasUniqueTargetType = true;
5507
5508 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005509 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005510 NamedDecl *D = (*I)->getUnderlyingDecl();
5511 CXXConversionDecl *Conversion;
5512 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5513 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005514 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005515 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5516 else
5517 continue; // C++11 does not consider conversion operator templates(?).
5518 } else
5519 Conversion = cast<CXXConversionDecl>(D);
5520
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005521 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005522 "Conversion operator templates are considered potentially "
5523 "viable in C++1y");
5524
5525 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5526 if (Converter.match(CurToType) || ConvTemplate) {
5527
5528 if (Conversion->isExplicit()) {
5529 // FIXME: For C++1y, do we need this restriction?
5530 // cf. diagnoseNoViableConversion()
5531 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005532 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005533 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005534 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005535 if (ToType.isNull())
5536 ToType = CurToType.getUnqualifiedType();
5537 else if (HasUniqueTargetType &&
5538 (CurToType.getUnqualifiedType() != ToType))
5539 HasUniqueTargetType = false;
5540 }
5541 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005542 }
Richard Smith8dd34252012-02-04 07:07:42 +00005543 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005546 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005547 // C++1y [conv]p6:
5548 // ... An expression e of class type E appearing in such a context
5549 // is said to be contextually implicitly converted to a specified
5550 // type T and is well-formed if and only if e can be implicitly
5551 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005552 // for conversion functions whose return type is cv T or reference to
5553 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005554 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Larisse Voufo236bec22013-06-10 06:50:24 +00005556 // If no unique T is found:
5557 if (ToType.isNull()) {
5558 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5559 HadMultipleCandidates,
5560 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005561 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005562 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Larisse Voufo236bec22013-06-10 06:50:24 +00005565 // If more than one unique Ts are found:
5566 if (!HasUniqueTargetType)
5567 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5568 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569
Larisse Voufo236bec22013-06-10 06:50:24 +00005570 // If one unique T is found:
5571 // First, build a candidate set from the previously recorded
5572 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005573 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005574 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5575 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Larisse Voufo236bec22013-06-10 06:50:24 +00005577 // Then, perform overload resolution over the candidate set.
5578 OverloadCandidateSet::iterator Best;
5579 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5580 case OR_Success: {
5581 // Apply this conversion.
5582 DeclAccessPair Found =
5583 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5584 if (recordConversion(*this, Loc, From, Converter, T,
5585 HadMultipleCandidates, Found))
5586 return ExprError();
5587 break;
5588 }
5589 case OR_Ambiguous:
5590 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5591 ViableConversions);
5592 case OR_No_Viable_Function:
5593 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5594 HadMultipleCandidates,
5595 ExplicitConversions))
5596 return ExprError();
5597 // fall through 'OR_Deleted' case.
5598 case OR_Deleted:
5599 // We'll complain below about a non-integral condition type.
5600 break;
5601 }
5602 } else {
5603 switch (ViableConversions.size()) {
5604 case 0: {
5605 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5606 HadMultipleCandidates,
5607 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005608 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Larisse Voufo236bec22013-06-10 06:50:24 +00005610 // We'll complain below about a non-integral condition type.
5611 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005612 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005613 case 1: {
5614 // Apply this conversion.
5615 DeclAccessPair Found = ViableConversions[0];
5616 if (recordConversion(*this, Loc, From, Converter, T,
5617 HadMultipleCandidates, Found))
5618 return ExprError();
5619 break;
5620 }
5621 default:
5622 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5623 ViableConversions);
5624 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Larisse Voufo236bec22013-06-10 06:50:24 +00005627 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005628}
5629
Richard Smith100b24a2014-04-17 01:52:14 +00005630/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5631/// an acceptable non-member overloaded operator for a call whose
5632/// arguments have types T1 (and, if non-empty, T2). This routine
5633/// implements the check in C++ [over.match.oper]p3b2 concerning
5634/// enumeration types.
5635static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5636 FunctionDecl *Fn,
5637 ArrayRef<Expr *> Args) {
5638 QualType T1 = Args[0]->getType();
5639 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5640
5641 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5642 return true;
5643
5644 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5645 return true;
5646
5647 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5648 if (Proto->getNumParams() < 1)
5649 return false;
5650
5651 if (T1->isEnumeralType()) {
5652 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5653 if (Context.hasSameUnqualifiedType(T1, ArgType))
5654 return true;
5655 }
5656
5657 if (Proto->getNumParams() < 2)
5658 return false;
5659
5660 if (!T2.isNull() && T2->isEnumeralType()) {
5661 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5662 if (Context.hasSameUnqualifiedType(T2, ArgType))
5663 return true;
5664 }
5665
5666 return false;
5667}
5668
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005669/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005670/// candidate functions, using the given function call arguments. If
5671/// @p SuppressUserConversions, then don't allow user-defined
5672/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005673///
James Dennett2a4d13c2012-06-15 07:13:21 +00005674/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005675/// based on an incomplete set of function arguments. This feature is used by
5676/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005677void
5678Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005679 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005680 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005681 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005682 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005683 bool PartialOverloading,
5684 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005685 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005686 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005687 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005688 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005689 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005690
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005692 if (!isa<CXXConstructorDecl>(Method)) {
5693 // If we get here, it's because we're calling a member function
5694 // that is named without a member access expression (e.g.,
5695 // "this->f") that was either written explicitly or created
5696 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005697 // function, e.g., X::f(). We use an empty type for the implied
5698 // object argument (C++ [over.call.func]p3), and the acting context
5699 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005700 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005702 Args, CandidateSet, SuppressUserConversions,
5703 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005704 return;
5705 }
5706 // We treat a constructor like a non-member function, since its object
5707 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005708 }
5709
Douglas Gregorff7028a2009-11-13 23:59:09 +00005710 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005711 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005712
Richard Smith100b24a2014-04-17 01:52:14 +00005713 // C++ [over.match.oper]p3:
5714 // if no operand has a class type, only those non-member functions in the
5715 // lookup set that have a first parameter of type T1 or "reference to
5716 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5717 // is a right operand) a second parameter of type T2 or "reference to
5718 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5719 // candidate functions.
5720 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5721 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5722 return;
5723
Richard Smith8b86f2d2013-11-04 01:48:18 +00005724 // C++11 [class.copy]p11: [DR1402]
5725 // A defaulted move constructor that is defined as deleted is ignored by
5726 // overload resolution.
5727 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5728 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5729 Constructor->isMoveConstructor())
5730 return;
5731
Douglas Gregor27381f32009-11-23 12:27:39 +00005732 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005733 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005734
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005735 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005736 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005737 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005738 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005739 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005740 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005741 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005742 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005743
John McCall578a1f82014-12-14 01:46:53 +00005744 if (Constructor) {
5745 // C++ [class.copy]p3:
5746 // A member function template is never instantiated to perform the copy
5747 // of a class object to an object of its class type.
5748 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005749 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005750 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005751 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5752 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005753 Candidate.Viable = false;
5754 Candidate.FailureKind = ovl_fail_illegal_constructor;
5755 return;
5756 }
5757 }
5758
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005759 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005760
5761 // (C++ 13.3.2p2): A candidate function having fewer than m
5762 // parameters is viable only if it has an ellipsis in its parameter
5763 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005764 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005765 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005766 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005767 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005768 return;
5769 }
5770
5771 // (C++ 13.3.2p2): A candidate function having more than m parameters
5772 // is viable only if the (m+1)st parameter has a default argument
5773 // (8.3.6). For the purposes of overload resolution, the
5774 // parameter list is truncated on the right, so that there are
5775 // exactly m parameters.
5776 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005777 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005778 // Not enough arguments.
5779 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005780 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005781 return;
5782 }
5783
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005784 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005785 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005786 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005787 // Skip the check for callers that are implicit members, because in this
5788 // case we may not yet know what the member's target is; the target is
5789 // inferred for the member automatically, based on the bases and fields of
5790 // the class.
5791 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005792 Candidate.Viable = false;
5793 Candidate.FailureKind = ovl_fail_bad_target;
5794 return;
5795 }
5796
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005797 // Determine the implicit conversion sequences for each of the
5798 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005799 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005800 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005801 // (C++ 13.3.2p3): for F to be a viable function, there shall
5802 // exist for each argument an implicit conversion sequence
5803 // (13.3.3.1) that converts that argument to the corresponding
5804 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005805 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005806 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005807 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005808 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005809 /*InOverloadResolution=*/true,
5810 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005811 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005812 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005813 if (Candidate.Conversions[ArgIdx].isBad()) {
5814 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005815 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005816 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005817 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005818 } else {
5819 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5820 // argument for which there is no corresponding parameter is
5821 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005822 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005823 }
5824 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825
5826 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5827 Candidate.Viable = false;
5828 Candidate.FailureKind = ovl_fail_enable_if;
5829 Candidate.DeductionFailure.Data = FailedAttr;
5830 return;
5831 }
5832}
5833
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005834ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005835 bool IsInstance) {
5836 SmallVector<ObjCMethodDecl*, 4> Methods;
5837 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5838 return nullptr;
5839
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005840 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5841 bool Match = true;
5842 ObjCMethodDecl *Method = Methods[b];
5843 unsigned NumNamedArgs = Sel.getNumArgs();
5844 // Method might have more arguments than selector indicates. This is due
5845 // to addition of c-style arguments in method.
5846 if (Method->param_size() > NumNamedArgs)
5847 NumNamedArgs = Method->param_size();
5848 if (Args.size() < NumNamedArgs)
5849 continue;
5850
5851 for (unsigned i = 0; i < NumNamedArgs; i++) {
5852 // We can't do any type-checking on a type-dependent argument.
5853 if (Args[i]->isTypeDependent()) {
5854 Match = false;
5855 break;
5856 }
5857
5858 ParmVarDecl *param = Method->parameters()[i];
5859 Expr *argExpr = Args[i];
5860 assert(argExpr && "SelectBestMethod(): missing expression");
5861
5862 // Strip the unbridged-cast placeholder expression off unless it's
5863 // a consumed argument.
5864 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5865 !param->hasAttr<CFConsumedAttr>())
5866 argExpr = stripARCUnbridgedCast(argExpr);
5867
5868 // If the parameter is __unknown_anytype, move on to the next method.
5869 if (param->getType() == Context.UnknownAnyTy) {
5870 Match = false;
5871 break;
5872 }
George Burgess IV45461812015-10-11 20:13:20 +00005873
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005874 ImplicitConversionSequence ConversionState
5875 = TryCopyInitialization(*this, argExpr, param->getType(),
5876 /*SuppressUserConversions*/false,
5877 /*InOverloadResolution=*/true,
5878 /*AllowObjCWritebackConversion=*/
5879 getLangOpts().ObjCAutoRefCount,
5880 /*AllowExplicit*/false);
5881 if (ConversionState.isBad()) {
5882 Match = false;
5883 break;
5884 }
5885 }
5886 // Promote additional arguments to variadic methods.
5887 if (Match && Method->isVariadic()) {
5888 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5889 if (Args[i]->isTypeDependent()) {
5890 Match = false;
5891 break;
5892 }
5893 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5894 nullptr);
5895 if (Arg.isInvalid()) {
5896 Match = false;
5897 break;
5898 }
5899 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005900 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005901 // Check for extra arguments to non-variadic methods.
5902 if (Args.size() != NumNamedArgs)
5903 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005904 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5905 // Special case when selectors have no argument. In this case, select
5906 // one with the most general result type of 'id'.
5907 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5908 QualType ReturnT = Methods[b]->getReturnType();
5909 if (ReturnT->isObjCIdType())
5910 return Methods[b];
5911 }
5912 }
5913 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005914
5915 if (Match)
5916 return Method;
5917 }
5918 return nullptr;
5919}
5920
George Burgess IV2a6150d2015-10-16 01:17:38 +00005921// specific_attr_iterator iterates over enable_if attributes in reverse, and
5922// enable_if is order-sensitive. As a result, we need to reverse things
5923// sometimes. Size of 4 elements is arbitrary.
5924static SmallVector<EnableIfAttr *, 4>
5925getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5926 SmallVector<EnableIfAttr *, 4> Result;
5927 if (!Function->hasAttrs())
5928 return Result;
5929
5930 const auto &FuncAttrs = Function->getAttrs();
5931 for (Attr *Attr : FuncAttrs)
5932 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5933 Result.push_back(EnableIf);
5934
5935 std::reverse(Result.begin(), Result.end());
5936 return Result;
5937}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005938
5939EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5940 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005941 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5942 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005943 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005944
5945 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005946 SmallVector<Expr *, 16> ConvertedArgs;
5947 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005948 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005949
5950 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005951 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5952 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005953 !cast<CXXMethodDecl>(Function)->isStatic() &&
5954 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005955 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5956 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005957 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005958 Method, Method);
5959 if (R.isInvalid()) {
5960 InitializationFailed = true;
5961 break;
5962 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005963 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005964 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005965 } else {
5966 ExprResult R =
5967 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5968 Context,
5969 Function->getParamDecl(i)),
5970 SourceLocation(),
5971 Args[i]);
5972 if (R.isInvalid()) {
5973 InitializationFailed = true;
5974 break;
5975 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005976 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005977 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005978 }
5979 }
5980
5981 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005982 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005983
Nick Lewyckye283c552015-08-25 22:33:16 +00005984 // Push default arguments if needed.
5985 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5986 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5987 ParmVarDecl *P = Function->getParamDecl(i);
5988 ExprResult R = PerformCopyInitialization(
5989 InitializedEntity::InitializeParameter(Context,
5990 Function->getParamDecl(i)),
5991 SourceLocation(),
5992 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5993 : P->getDefaultArg());
5994 if (R.isInvalid()) {
5995 InitializationFailed = true;
5996 break;
5997 }
5998 ContainsValueDependentExpr |= R.get()->isValueDependent();
5999 ConvertedArgs.push_back(R.get());
6000 }
6001
6002 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006003 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006004 }
6005
George Burgess IV2a6150d2015-10-16 01:17:38 +00006006 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006007 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006008 if (EIA->getCond()->isValueDependent()) {
6009 // Don't even try now, we'll examine it after instantiation.
6010 continue;
6011 }
6012
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006013 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006014 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6015 if (!ContainsValueDependentExpr)
6016 return EIA;
6017 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006018 return EIA;
6019 }
6020 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006021 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006022}
6023
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006024/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006025/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006026void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006027 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006028 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006029 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006030 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006031 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006032 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006033 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6034 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006035 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006036 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006037 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006038 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006039 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006040 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006041 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006042 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006043 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006044 } else {
John McCalla0296f72010-03-19 07:35:19 +00006045 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006046 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6047 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006048 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006049 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006050 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006051 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006052 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006053 CandidateSet, SuppressUserConversions,
6054 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006055 else
John McCalla0296f72010-03-19 07:35:19 +00006056 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006057 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006058 CandidateSet, SuppressUserConversions,
6059 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006060 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006061 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006062}
6063
John McCallf0f1cf02009-11-17 07:50:12 +00006064/// AddMethodCandidate - Adds a named decl (which is some kind of
6065/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006066void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006067 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006068 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006069 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006070 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006071 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006072 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006073 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006074
6075 if (isa<UsingShadowDecl>(Decl))
6076 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077
John McCallf0f1cf02009-11-17 07:50:12 +00006078 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6079 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6080 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006081 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006082 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006083 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006084 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006085 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006086 } else {
John McCalla0296f72010-03-19 07:35:19 +00006087 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006088 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006089 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006090 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006091 }
6092}
6093
Douglas Gregor436424c2008-11-18 23:14:02 +00006094/// AddMethodCandidate - Adds the given C++ member function to the set
6095/// of candidate functions, using the given function call arguments
6096/// and the object argument (@c Object). For example, in a call
6097/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6098/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6099/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006100/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006101void
John McCalla0296f72010-03-19 07:35:19 +00006102Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006103 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006104 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006105 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006106 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006107 bool SuppressUserConversions,
6108 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006109 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006110 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006111 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006112 assert(!isa<CXXConstructorDecl>(Method) &&
6113 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006114
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006115 if (!CandidateSet.isNewCandidate(Method))
6116 return;
6117
Richard Smith8b86f2d2013-11-04 01:48:18 +00006118 // C++11 [class.copy]p23: [DR1402]
6119 // A defaulted move assignment operator that is defined as deleted is
6120 // ignored by overload resolution.
6121 if (Method->isDefaulted() && Method->isDeleted() &&
6122 Method->isMoveAssignmentOperator())
6123 return;
6124
Douglas Gregor27381f32009-11-23 12:27:39 +00006125 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006126 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006127
Douglas Gregor436424c2008-11-18 23:14:02 +00006128 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006129 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006130 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006131 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006132 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006133 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006134 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006135
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006136 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006137
6138 // (C++ 13.3.2p2): A candidate function having fewer than m
6139 // parameters is viable only if it has an ellipsis in its parameter
6140 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006141 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6142 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006144 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006145 return;
6146 }
6147
6148 // (C++ 13.3.2p2): A candidate function having more than m parameters
6149 // is viable only if the (m+1)st parameter has a default argument
6150 // (8.3.6). For the purposes of overload resolution, the
6151 // parameter list is truncated on the right, so that there are
6152 // exactly m parameters.
6153 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006154 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006155 // Not enough arguments.
6156 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006157 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006158 return;
6159 }
6160
6161 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006162
John McCall6e9f8f62009-12-03 04:06:58 +00006163 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006164 // The implicit object argument is ignored.
6165 Candidate.IgnoreObjectArgument = true;
6166 else {
6167 // Determine the implicit conversion sequence for the object
6168 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006169 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6170 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6171 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006172 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006173 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006174 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006175 return;
6176 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006177 }
6178
Eli Bendersky291a57e2014-09-25 23:59:08 +00006179 // (CUDA B.1): Check for invalid calls between targets.
6180 if (getLangOpts().CUDA)
6181 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6182 if (CheckCUDATarget(Caller, Method)) {
6183 Candidate.Viable = false;
6184 Candidate.FailureKind = ovl_fail_bad_target;
6185 return;
6186 }
6187
Douglas Gregor436424c2008-11-18 23:14:02 +00006188 // Determine the implicit conversion sequences for each of the
6189 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006190 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006191 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006192 // (C++ 13.3.2p3): for F to be a viable function, there shall
6193 // exist for each argument an implicit conversion sequence
6194 // (13.3.3.1) that converts that argument to the corresponding
6195 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006196 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006197 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006198 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006199 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006200 /*InOverloadResolution=*/true,
6201 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006202 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006203 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006204 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006205 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006206 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006207 }
6208 } else {
6209 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6210 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006211 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006212 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006213 }
6214 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006215
6216 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6217 Candidate.Viable = false;
6218 Candidate.FailureKind = ovl_fail_enable_if;
6219 Candidate.DeductionFailure.Data = FailedAttr;
6220 return;
6221 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006222}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223
Douglas Gregor97628d62009-08-21 00:16:32 +00006224/// \brief Add a C++ member function template as a candidate to the candidate
6225/// set, using template argument deduction to produce an appropriate member
6226/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006227void
Douglas Gregor97628d62009-08-21 00:16:32 +00006228Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006229 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006230 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006231 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006232 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006233 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006234 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006235 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006236 bool SuppressUserConversions,
6237 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006238 if (!CandidateSet.isNewCandidate(MethodTmpl))
6239 return;
6240
Douglas Gregor97628d62009-08-21 00:16:32 +00006241 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006242 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006243 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006244 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006245 // candidate functions in the usual way.113) A given name can refer to one
6246 // or more function templates and also to a set of overloaded non-template
6247 // functions. In such a case, the candidate functions generated from each
6248 // function template are combined with the set of non-template candidate
6249 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006250 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006251 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006252 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006253 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006254 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006255 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006256 Candidate.FoundDecl = FoundDecl;
6257 Candidate.Function = MethodTmpl->getTemplatedDecl();
6258 Candidate.Viable = false;
6259 Candidate.FailureKind = ovl_fail_bad_deduction;
6260 Candidate.IsSurrogate = false;
6261 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006262 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006264 Info);
6265 return;
6266 }
Mike Stump11289f42009-09-09 15:08:12 +00006267
Douglas Gregor97628d62009-08-21 00:16:32 +00006268 // Add the function template specialization produced by template argument
6269 // deduction as a candidate.
6270 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006271 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006272 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006273 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006274 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006275 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006276}
6277
Douglas Gregor05155d82009-08-21 23:19:43 +00006278/// \brief Add a C++ function template specialization as a candidate
6279/// in the candidate set, using template argument deduction to produce
6280/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006281void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006282Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006283 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006284 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006285 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006286 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006287 bool SuppressUserConversions,
6288 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006289 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6290 return;
6291
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006292 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006293 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006294 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006295 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006296 // candidate functions in the usual way.113) A given name can refer to one
6297 // or more function templates and also to a set of overloaded non-template
6298 // functions. In such a case, the candidate functions generated from each
6299 // function template are combined with the set of non-template candidate
6300 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006301 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006302 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006303 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006304 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006305 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006306 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006307 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006308 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6309 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006310 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006311 Candidate.IsSurrogate = false;
6312 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006313 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006314 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006315 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006316 return;
6317 }
Mike Stump11289f42009-09-09 15:08:12 +00006318
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006319 // Add the function template specialization produced by template argument
6320 // deduction as a candidate.
6321 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006322 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006323 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006324}
Mike Stump11289f42009-09-09 15:08:12 +00006325
Douglas Gregor4b60a152013-11-07 22:34:54 +00006326/// Determine whether this is an allowable conversion from the result
6327/// of an explicit conversion operator to the expected type, per C++
6328/// [over.match.conv]p1 and [over.match.ref]p1.
6329///
6330/// \param ConvType The return type of the conversion function.
6331///
6332/// \param ToType The type we are converting to.
6333///
6334/// \param AllowObjCPointerConversion Allow a conversion from one
6335/// Objective-C pointer to another.
6336///
6337/// \returns true if the conversion is allowable, false otherwise.
6338static bool isAllowableExplicitConversion(Sema &S,
6339 QualType ConvType, QualType ToType,
6340 bool AllowObjCPointerConversion) {
6341 QualType ToNonRefType = ToType.getNonReferenceType();
6342
6343 // Easy case: the types are the same.
6344 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6345 return true;
6346
6347 // Allow qualification conversions.
6348 bool ObjCLifetimeConversion;
6349 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6350 ObjCLifetimeConversion))
6351 return true;
6352
6353 // If we're not allowed to consider Objective-C pointer conversions,
6354 // we're done.
6355 if (!AllowObjCPointerConversion)
6356 return false;
6357
6358 // Is this an Objective-C pointer conversion?
6359 bool IncompatibleObjC = false;
6360 QualType ConvertedType;
6361 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6362 IncompatibleObjC);
6363}
6364
Douglas Gregora1f013e2008-11-07 22:36:19 +00006365/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006366/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006367/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006368/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006369/// (which may or may not be the same type as the type that the
6370/// conversion function produces).
6371void
6372Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006373 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006374 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006375 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006376 OverloadCandidateSet& CandidateSet,
6377 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006378 assert(!Conversion->getDescribedFunctionTemplate() &&
6379 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006380 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006381 if (!CandidateSet.isNewCandidate(Conversion))
6382 return;
6383
Richard Smith2a7d4812013-05-04 07:00:32 +00006384 // If the conversion function has an undeduced return type, trigger its
6385 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006386 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006387 if (DeduceReturnType(Conversion, From->getExprLoc()))
6388 return;
6389 ConvType = Conversion->getConversionType().getNonReferenceType();
6390 }
6391
Richard Smith089c3162013-09-21 21:55:46 +00006392 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6393 // operator is only a candidate if its return type is the target type or
6394 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006395 if (Conversion->isExplicit() &&
6396 !isAllowableExplicitConversion(*this, ConvType, ToType,
6397 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006398 return;
6399
Douglas Gregor27381f32009-11-23 12:27:39 +00006400 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006401 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006402
Douglas Gregora1f013e2008-11-07 22:36:19 +00006403 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006404 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006405 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006406 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006407 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006408 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006409 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006410 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006411 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006412 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006413 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006414
Douglas Gregor6affc782010-08-19 15:37:02 +00006415 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006416 // For conversion functions, the function is considered to be a member of
6417 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006418 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006419 //
6420 // Determine the implicit conversion sequence for the implicit
6421 // object parameter.
6422 QualType ImplicitParamType = From->getType();
6423 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6424 ImplicitParamType = FromPtrType->getPointeeType();
6425 CXXRecordDecl *ConversionContext
6426 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427
Richard Smith0f59cb32015-12-18 21:45:41 +00006428 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6429 *this, CandidateSet.getLocation(), From->getType(),
6430 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
John McCall0d1da222010-01-12 00:44:57 +00006432 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006433 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006434 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006435 return;
6436 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006437
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006438 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006439 // derived to base as such conversions are given Conversion Rank. They only
6440 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6441 QualType FromCanon
6442 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6443 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006444 if (FromCanon == ToCanon ||
6445 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006446 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006447 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006448 return;
6449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006450
Douglas Gregora1f013e2008-11-07 22:36:19 +00006451 // To determine what the conversion from the result of calling the
6452 // conversion function to the type we're eventually trying to
6453 // convert to (ToType), we need to synthesize a call to the
6454 // conversion function and attempt copy initialization from it. This
6455 // makes sure that we get the right semantics with respect to
6456 // lvalues/rvalues and the type. Fortunately, we can allocate this
6457 // call on the stack and we don't need its arguments to be
6458 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006459 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006460 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006461 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6462 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006463 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006464 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006465
Richard Smith48d24642011-07-13 22:53:21 +00006466 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006467 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006468 Candidate.Viable = false;
6469 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6470 return;
6471 }
6472
Richard Smith48d24642011-07-13 22:53:21 +00006473 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006474
Mike Stump11289f42009-09-09 15:08:12 +00006475 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006476 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6477 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006478 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006479 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006480 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006481 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006482 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006483 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006484 /*InOverloadResolution=*/false,
6485 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006486
John McCall0d1da222010-01-12 00:44:57 +00006487 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006488 case ImplicitConversionSequence::StandardConversion:
6489 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006491 // C++ [over.ics.user]p3:
6492 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006494 // shall have exact match rank.
6495 if (Conversion->getPrimaryTemplate() &&
6496 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6497 Candidate.Viable = false;
6498 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006499 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006501
Douglas Gregorcba72b12011-01-21 05:18:22 +00006502 // C++0x [dcl.init.ref]p5:
6503 // In the second case, if the reference is an rvalue reference and
6504 // the second standard conversion sequence of the user-defined
6505 // conversion sequence includes an lvalue-to-rvalue conversion, the
6506 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006508 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6509 Candidate.Viable = false;
6510 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006511 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006512 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006513 break;
6514
6515 case ImplicitConversionSequence::BadConversion:
6516 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006517 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006518 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006519
6520 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006521 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006522 "Can only end up with a standard conversion sequence or failure");
6523 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006524
Craig Topper5fc8fc22014-08-27 06:28:36 +00006525 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006526 Candidate.Viable = false;
6527 Candidate.FailureKind = ovl_fail_enable_if;
6528 Candidate.DeductionFailure.Data = FailedAttr;
6529 return;
6530 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006531}
6532
Douglas Gregor05155d82009-08-21 23:19:43 +00006533/// \brief Adds a conversion function template specialization
6534/// candidate to the overload set, using template argument deduction
6535/// to deduce the template arguments of the conversion function
6536/// template from the type that we are converting to (C++
6537/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006538void
Douglas Gregor05155d82009-08-21 23:19:43 +00006539Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006540 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006541 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006542 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006543 OverloadCandidateSet &CandidateSet,
6544 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006545 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6546 "Only conversion function templates permitted here");
6547
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006548 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6549 return;
6550
Craig Toppere6706e42012-09-19 02:26:47 +00006551 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006552 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006553 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006554 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006555 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006556 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006557 Candidate.FoundDecl = FoundDecl;
6558 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6559 Candidate.Viable = false;
6560 Candidate.FailureKind = ovl_fail_bad_deduction;
6561 Candidate.IsSurrogate = false;
6562 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006563 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006565 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006566 return;
6567 }
Mike Stump11289f42009-09-09 15:08:12 +00006568
Douglas Gregor05155d82009-08-21 23:19:43 +00006569 // Add the conversion function template specialization produced by
6570 // template argument deduction as a candidate.
6571 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006572 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006573 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006574}
6575
Douglas Gregorab7897a2008-11-19 22:57:39 +00006576/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6577/// converts the given @c Object to a function pointer via the
6578/// conversion function @c Conversion, and then attempts to call it
6579/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6580/// the type of function that we'll eventually be calling.
6581void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006582 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006583 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006584 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006585 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006586 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006587 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006588 if (!CandidateSet.isNewCandidate(Conversion))
6589 return;
6590
Douglas Gregor27381f32009-11-23 12:27:39 +00006591 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006592 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006593
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006594 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006595 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006596 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006597 Candidate.Surrogate = Conversion;
6598 Candidate.Viable = true;
6599 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006600 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006601 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006602
6603 // Determine the implicit conversion sequence for the implicit
6604 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006605 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6606 *this, CandidateSet.getLocation(), Object->getType(),
6607 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006608 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006609 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006610 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006611 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006612 return;
6613 }
6614
6615 // The first conversion is actually a user-defined conversion whose
6616 // first conversion is ObjectInit's standard conversion (which is
6617 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006618 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006619 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006620 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006621 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006622 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006623 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006624 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006625 = Candidate.Conversions[0].UserDefined.Before;
6626 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6627
Mike Stump11289f42009-09-09 15:08:12 +00006628 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006629 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006630
6631 // (C++ 13.3.2p2): A candidate function having fewer than m
6632 // parameters is viable only if it has an ellipsis in its parameter
6633 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006634 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006635 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006636 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006637 return;
6638 }
6639
6640 // Function types don't have any default arguments, so just check if
6641 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006642 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006643 // Not enough arguments.
6644 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006645 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006646 return;
6647 }
6648
6649 // Determine the implicit conversion sequences for each of the
6650 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006651 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006652 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006653 // (C++ 13.3.2p3): for F to be a viable function, there shall
6654 // exist for each argument an implicit conversion sequence
6655 // (13.3.3.1) that converts that argument to the corresponding
6656 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006657 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006658 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006659 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006660 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006661 /*InOverloadResolution=*/false,
6662 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006663 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006664 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006665 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006666 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006667 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006668 }
6669 } else {
6670 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6671 // argument for which there is no corresponding parameter is
6672 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006673 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006674 }
6675 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006676
Craig Topper5fc8fc22014-08-27 06:28:36 +00006677 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006678 Candidate.Viable = false;
6679 Candidate.FailureKind = ovl_fail_enable_if;
6680 Candidate.DeductionFailure.Data = FailedAttr;
6681 return;
6682 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006683}
6684
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006685/// \brief Add overload candidates for overloaded operators that are
6686/// member functions.
6687///
6688/// Add the overloaded operator candidates that are member functions
6689/// for the operator Op that was used in an operator expression such
6690/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6691/// CandidateSet will store the added overload candidates. (C++
6692/// [over.match.oper]).
6693void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6694 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006695 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006696 OverloadCandidateSet& CandidateSet,
6697 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006698 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6699
6700 // C++ [over.match.oper]p3:
6701 // For a unary operator @ with an operand of a type whose
6702 // cv-unqualified version is T1, and for a binary operator @ with
6703 // a left operand of a type whose cv-unqualified version is T1 and
6704 // a right operand of a type whose cv-unqualified version is T2,
6705 // three sets of candidate functions, designated member
6706 // candidates, non-member candidates and built-in candidates, are
6707 // constructed as follows:
6708 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006709
Richard Smith0feaf0c2013-04-20 12:41:22 +00006710 // -- If T1 is a complete class type or a class currently being
6711 // defined, the set of member candidates is the result of the
6712 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6713 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006714 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006715 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006716 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006717 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006718 // If the type is neither complete nor being defined, bail out now.
6719 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006720 return;
Mike Stump11289f42009-09-09 15:08:12 +00006721
John McCall27b18f82009-11-17 02:14:36 +00006722 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6723 LookupQualifiedName(Operators, T1Rec->getDecl());
6724 Operators.suppressDiagnostics();
6725
Mike Stump11289f42009-09-09 15:08:12 +00006726 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006727 OperEnd = Operators.end();
6728 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006729 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006730 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006731 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006732 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006733 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006734 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006735 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006736}
6737
Douglas Gregora11693b2008-11-12 17:17:38 +00006738/// AddBuiltinCandidate - Add a candidate for a built-in
6739/// operator. ResultTy and ParamTys are the result and parameter types
6740/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006741/// arguments being passed to the candidate. IsAssignmentOperator
6742/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006743/// operator. NumContextualBoolArguments is the number of arguments
6744/// (at the beginning of the argument list) that will be contextually
6745/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006746void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006747 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006748 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006749 bool IsAssignmentOperator,
6750 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006751 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006752 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006753
Douglas Gregora11693b2008-11-12 17:17:38 +00006754 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006755 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006756 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6757 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006758 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006759 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006760 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006761 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006762 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6763
6764 // Determine the implicit conversion sequences for each of the
6765 // arguments.
6766 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006767 Candidate.ExplicitCallArguments = Args.size();
6768 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006769 // C++ [over.match.oper]p4:
6770 // For the built-in assignment operators, conversions of the
6771 // left operand are restricted as follows:
6772 // -- no temporaries are introduced to hold the left operand, and
6773 // -- no user-defined conversions are applied to the left
6774 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006775 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006776 //
6777 // We block these conversions by turning off user-defined
6778 // conversions, since that is the only way that initialization of
6779 // a reference to a non-class type can occur from something that
6780 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006781 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006782 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006783 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006784 Candidate.Conversions[ArgIdx]
6785 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006786 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006787 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006788 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006789 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006790 /*InOverloadResolution=*/false,
6791 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006792 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006793 }
John McCall0d1da222010-01-12 00:44:57 +00006794 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006795 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006796 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006797 break;
6798 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006799 }
6800}
6801
Craig Toppercd7b0332013-07-01 06:29:40 +00006802namespace {
6803
Douglas Gregora11693b2008-11-12 17:17:38 +00006804/// BuiltinCandidateTypeSet - A set of types that will be used for the
6805/// candidate operator functions for built-in operators (C++
6806/// [over.built]). The types are separated into pointer types and
6807/// enumeration types.
6808class BuiltinCandidateTypeSet {
6809 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006810 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006811
6812 /// PointerTypes - The set of pointer types that will be used in the
6813 /// built-in candidates.
6814 TypeSet PointerTypes;
6815
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006816 /// MemberPointerTypes - The set of member pointer types that will be
6817 /// used in the built-in candidates.
6818 TypeSet MemberPointerTypes;
6819
Douglas Gregora11693b2008-11-12 17:17:38 +00006820 /// EnumerationTypes - The set of enumeration types that will be
6821 /// used in the built-in candidates.
6822 TypeSet EnumerationTypes;
6823
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006824 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006825 /// candidates.
6826 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006827
6828 /// \brief A flag indicating non-record types are viable candidates
6829 bool HasNonRecordTypes;
6830
6831 /// \brief A flag indicating whether either arithmetic or enumeration types
6832 /// were present in the candidate set.
6833 bool HasArithmeticOrEnumeralTypes;
6834
Douglas Gregor80af3132011-05-21 23:15:46 +00006835 /// \brief A flag indicating whether the nullptr type was present in the
6836 /// candidate set.
6837 bool HasNullPtrType;
6838
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006839 /// Sema - The semantic analysis instance where we are building the
6840 /// candidate type set.
6841 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006842
Douglas Gregora11693b2008-11-12 17:17:38 +00006843 /// Context - The AST context in which we will build the type sets.
6844 ASTContext &Context;
6845
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006846 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6847 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006848 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006849
6850public:
6851 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006852 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006853
Mike Stump11289f42009-09-09 15:08:12 +00006854 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006855 : HasNonRecordTypes(false),
6856 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006857 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006858 SemaRef(SemaRef),
6859 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006860
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006862 SourceLocation Loc,
6863 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006864 bool AllowExplicitConversions,
6865 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006866
6867 /// pointer_begin - First pointer type found;
6868 iterator pointer_begin() { return PointerTypes.begin(); }
6869
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006870 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006871 iterator pointer_end() { return PointerTypes.end(); }
6872
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006873 /// member_pointer_begin - First member pointer type found;
6874 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6875
6876 /// member_pointer_end - Past the last member pointer type found;
6877 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6878
Douglas Gregora11693b2008-11-12 17:17:38 +00006879 /// enumeration_begin - First enumeration type found;
6880 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6881
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006882 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006883 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006885 iterator vector_begin() { return VectorTypes.begin(); }
6886 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006887
6888 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6889 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006890 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006891};
6892
Craig Toppercd7b0332013-07-01 06:29:40 +00006893} // end anonymous namespace
6894
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006895/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006896/// the set of pointer types along with any more-qualified variants of
6897/// that type. For example, if @p Ty is "int const *", this routine
6898/// will add "int const *", "int const volatile *", "int const
6899/// restrict *", and "int const volatile restrict *" to the set of
6900/// pointer types. Returns true if the add of @p Ty itself succeeded,
6901/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006902///
6903/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006904bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006905BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6906 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006907
Douglas Gregora11693b2008-11-12 17:17:38 +00006908 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006909 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006910 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006912 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006913 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006914 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006915 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006916 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6917 PointeeTy = PTy->getPointeeType();
6918 buildObjCPtr = true;
6919 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006920 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006921 }
6922
Sebastian Redl4990a632009-11-18 20:39:26 +00006923 // Don't add qualified variants of arrays. For one, they're not allowed
6924 // (the qualifier would sink to the element type), and for another, the
6925 // only overload situation where it matters is subscript or pointer +- int,
6926 // and those shouldn't have qualifier variants anyway.
6927 if (PointeeTy->isArrayType())
6928 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006929
John McCall8ccfcb52009-09-24 19:53:00 +00006930 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006931 bool hasVolatile = VisibleQuals.hasVolatile();
6932 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
John McCall8ccfcb52009-09-24 19:53:00 +00006934 // Iterate through all strict supersets of BaseCVR.
6935 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6936 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006937 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006938 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006939
6940 // Skip over restrict if no restrict found anywhere in the types, or if
6941 // the type cannot be restrict-qualified.
6942 if ((CVR & Qualifiers::Restrict) &&
6943 (!hasRestrict ||
6944 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6945 continue;
6946
6947 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006948 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006949
6950 // Build qualified pointer type.
6951 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006952 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006953 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006954 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006955 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6956
6957 // Insert qualified pointer type.
6958 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006959 }
6960
6961 return true;
6962}
6963
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006964/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6965/// to the set of pointer types along with any more-qualified variants of
6966/// that type. For example, if @p Ty is "int const *", this routine
6967/// will add "int const *", "int const volatile *", "int const
6968/// restrict *", and "int const volatile restrict *" to the set of
6969/// pointer types. Returns true if the add of @p Ty itself succeeded,
6970/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006971///
6972/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006973bool
6974BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6975 QualType Ty) {
6976 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006977 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006978 return false;
6979
John McCall8ccfcb52009-09-24 19:53:00 +00006980 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6981 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006982
John McCall8ccfcb52009-09-24 19:53:00 +00006983 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006984 // Don't add qualified variants of arrays. For one, they're not allowed
6985 // (the qualifier would sink to the element type), and for another, the
6986 // only overload situation where it matters is subscript or pointer +- int,
6987 // and those shouldn't have qualifier variants anyway.
6988 if (PointeeTy->isArrayType())
6989 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006990 const Type *ClassTy = PointerTy->getClass();
6991
6992 // Iterate through all strict supersets of the pointee type's CVR
6993 // qualifiers.
6994 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6995 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6996 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
John McCall8ccfcb52009-09-24 19:53:00 +00006998 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006999 MemberPointerTypes.insert(
7000 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007001 }
7002
7003 return true;
7004}
7005
Douglas Gregora11693b2008-11-12 17:17:38 +00007006/// AddTypesConvertedFrom - Add each of the types to which the type @p
7007/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007008/// primarily interested in pointer types and enumeration types. We also
7009/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007010/// AllowUserConversions is true if we should look at the conversion
7011/// functions of a class type, and AllowExplicitConversions if we
7012/// should also include the explicit conversion functions of a class
7013/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007014void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007015BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007016 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007017 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007018 bool AllowExplicitConversions,
7019 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007020 // Only deal with canonical types.
7021 Ty = Context.getCanonicalType(Ty);
7022
7023 // Look through reference types; they aren't part of the type of an
7024 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007025 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007026 Ty = RefTy->getPointeeType();
7027
John McCall33ddac02011-01-19 10:06:00 +00007028 // If we're dealing with an array type, decay to the pointer.
7029 if (Ty->isArrayType())
7030 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7031
7032 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007033 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007034
Chandler Carruth00a38332010-12-13 01:44:01 +00007035 // Flag if we ever add a non-record type.
7036 const RecordType *TyRec = Ty->getAs<RecordType>();
7037 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7038
Chandler Carruth00a38332010-12-13 01:44:01 +00007039 // Flag if we encounter an arithmetic type.
7040 HasArithmeticOrEnumeralTypes =
7041 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7042
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007043 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7044 PointerTypes.insert(Ty);
7045 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007046 // Insert our type, and its more-qualified variants, into the set
7047 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007048 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007049 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007050 } else if (Ty->isMemberPointerType()) {
7051 // Member pointers are far easier, since the pointee can't be converted.
7052 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7053 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007054 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007055 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007056 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007057 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007058 // We treat vector types as arithmetic types in many contexts as an
7059 // extension.
7060 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007061 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007062 } else if (Ty->isNullPtrType()) {
7063 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007064 } else if (AllowUserConversions && TyRec) {
7065 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007066 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007067 return;
Mike Stump11289f42009-09-09 15:08:12 +00007068
Chandler Carruth00a38332010-12-13 01:44:01 +00007069 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007070 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007071 if (isa<UsingShadowDecl>(D))
7072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007073
Chandler Carruth00a38332010-12-13 01:44:01 +00007074 // Skip conversion function templates; they don't tell us anything
7075 // about which builtin types we can convert to.
7076 if (isa<FunctionTemplateDecl>(D))
7077 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007078
Chandler Carruth00a38332010-12-13 01:44:01 +00007079 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7080 if (AllowExplicitConversions || !Conv->isExplicit()) {
7081 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7082 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007083 }
7084 }
7085 }
7086}
7087
Douglas Gregor84605ae2009-08-24 13:43:27 +00007088/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7089/// the volatile- and non-volatile-qualified assignment operators for the
7090/// given type to the candidate set.
7091static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7092 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007093 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007094 OverloadCandidateSet &CandidateSet) {
7095 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007096
Douglas Gregor84605ae2009-08-24 13:43:27 +00007097 // T& operator=(T&, T)
7098 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7099 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007100 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007101 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007102
Douglas Gregor84605ae2009-08-24 13:43:27 +00007103 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7104 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007105 ParamTypes[0]
7106 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007107 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007109 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007110 }
7111}
Mike Stump11289f42009-09-09 15:08:12 +00007112
Sebastian Redl1054fae2009-10-25 17:03:50 +00007113/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7114/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007115static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7116 Qualifiers VRQuals;
7117 const RecordType *TyRec;
7118 if (const MemberPointerType *RHSMPType =
7119 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007120 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007121 else
7122 TyRec = ArgExpr->getType()->getAs<RecordType>();
7123 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007124 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007125 VRQuals.addVolatile();
7126 VRQuals.addRestrict();
7127 return VRQuals;
7128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007129
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007130 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007131 if (!ClassDecl->hasDefinition())
7132 return VRQuals;
7133
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007134 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007135 if (isa<UsingShadowDecl>(D))
7136 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7137 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007138 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7139 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7140 CanTy = ResTypeRef->getPointeeType();
7141 // Need to go down the pointer/mempointer chain and add qualifiers
7142 // as see them.
7143 bool done = false;
7144 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007145 if (CanTy.isRestrictQualified())
7146 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007147 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7148 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007150 CanTy->getAs<MemberPointerType>())
7151 CanTy = ResTypeMPtr->getPointeeType();
7152 else
7153 done = true;
7154 if (CanTy.isVolatileQualified())
7155 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007156 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7157 return VRQuals;
7158 }
7159 }
7160 }
7161 return VRQuals;
7162}
John McCall52872982010-11-13 05:51:15 +00007163
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007164namespace {
John McCall52872982010-11-13 05:51:15 +00007165
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007166/// \brief Helper class to manage the addition of builtin operator overload
7167/// candidates. It provides shared state and utility methods used throughout
7168/// the process, as well as a helper method to add each group of builtin
7169/// operator overloads from the standard to a candidate set.
7170class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007171 // Common instance state available to all overload candidate addition methods.
7172 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007173 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007174 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007175 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007176 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007177 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178
Chandler Carruthc6586e52010-12-12 10:35:00 +00007179 // Define some constants used to index and iterate over the arithemetic types
7180 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007181 // The "promoted arithmetic types" are the arithmetic
7182 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007183 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007184 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007185 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007186 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007187 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007188 LastPromotedArithmeticType = 11;
7189 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007190
Chandler Carruthc6586e52010-12-12 10:35:00 +00007191 /// \brief Get the canonical type for a given arithmetic type index.
7192 CanQualType getArithmeticType(unsigned index) {
7193 assert(index < NumArithmeticTypes);
7194 static CanQualType ASTContext::* const
7195 ArithmeticTypes[NumArithmeticTypes] = {
7196 // Start of promoted types.
7197 &ASTContext::FloatTy,
7198 &ASTContext::DoubleTy,
7199 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007200
Chandler Carruthc6586e52010-12-12 10:35:00 +00007201 // Start of integral types.
7202 &ASTContext::IntTy,
7203 &ASTContext::LongTy,
7204 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007205 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007206 &ASTContext::UnsignedIntTy,
7207 &ASTContext::UnsignedLongTy,
7208 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007209 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007210 // End of promoted types.
7211
7212 &ASTContext::BoolTy,
7213 &ASTContext::CharTy,
7214 &ASTContext::WCharTy,
7215 &ASTContext::Char16Ty,
7216 &ASTContext::Char32Ty,
7217 &ASTContext::SignedCharTy,
7218 &ASTContext::ShortTy,
7219 &ASTContext::UnsignedCharTy,
7220 &ASTContext::UnsignedShortTy,
7221 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007222 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007223 };
7224 return S.Context.*ArithmeticTypes[index];
7225 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007226
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007227 /// \brief Gets the canonical type resulting from the usual arithemetic
7228 /// converions for the given arithmetic types.
7229 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7230 // Accelerator table for performing the usual arithmetic conversions.
7231 // The rules are basically:
7232 // - if either is floating-point, use the wider floating-point
7233 // - if same signedness, use the higher rank
7234 // - if same size, use unsigned of the higher rank
7235 // - use the larger type
7236 // These rules, together with the axiom that higher ranks are
7237 // never smaller, are sufficient to precompute all of these results
7238 // *except* when dealing with signed types of higher rank.
7239 // (we could precompute SLL x UI for all known platforms, but it's
7240 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007241 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007242 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007243 Dep=-1,
7244 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007245 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007246 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007247 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007248/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7249/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7250/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7251/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7252/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7253/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7254/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7255/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7256/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7257/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7258/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007259 };
7260
7261 assert(L < LastPromotedArithmeticType);
7262 assert(R < LastPromotedArithmeticType);
7263 int Idx = ConversionsTable[L][R];
7264
7265 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007266 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007267
7268 // Slow path: we need to compare widths.
7269 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007270 CanQualType LT = getArithmeticType(L),
7271 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007272 unsigned LW = S.Context.getIntWidth(LT),
7273 RW = S.Context.getIntWidth(RT);
7274
7275 // If they're different widths, use the signed type.
7276 if (LW > RW) return LT;
7277 else if (LW < RW) return RT;
7278
7279 // Otherwise, use the unsigned type of the signed type's rank.
7280 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7281 assert(L == SLL || R == SLL);
7282 return S.Context.UnsignedLongLongTy;
7283 }
7284
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007285 /// \brief Helper method to factor out the common pattern of adding overloads
7286 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007287 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007288 bool HasVolatile,
7289 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007290 QualType ParamTypes[2] = {
7291 S.Context.getLValueReferenceType(CandidateTy),
7292 S.Context.IntTy
7293 };
7294
7295 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007296 if (Args.size() == 1)
7297 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007298 else
Richard Smithe54c3072013-05-05 15:51:06 +00007299 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007300
7301 // Use a heuristic to reduce number of builtin candidates in the set:
7302 // add volatile version only if there are conversions to a volatile type.
7303 if (HasVolatile) {
7304 ParamTypes[0] =
7305 S.Context.getLValueReferenceType(
7306 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007307 if (Args.size() == 1)
7308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007309 else
Richard Smithe54c3072013-05-05 15:51:06 +00007310 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007311 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007312
7313 // Add restrict version only if there are conversions to a restrict type
7314 // and our candidate type is a non-restrict-qualified pointer.
7315 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7316 !CandidateTy.isRestrictQualified()) {
7317 ParamTypes[0]
7318 = S.Context.getLValueReferenceType(
7319 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007320 if (Args.size() == 1)
7321 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007322 else
Richard Smithe54c3072013-05-05 15:51:06 +00007323 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007324
7325 if (HasVolatile) {
7326 ParamTypes[0]
7327 = S.Context.getLValueReferenceType(
7328 S.Context.getCVRQualifiedType(CandidateTy,
7329 (Qualifiers::Volatile |
7330 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007331 if (Args.size() == 1)
7332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007333 else
Richard Smithe54c3072013-05-05 15:51:06 +00007334 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007335 }
7336 }
7337
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007338 }
7339
7340public:
7341 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007342 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007343 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007344 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007345 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007346 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007347 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007348 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007349 HasArithmeticOrEnumeralCandidateType(
7350 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 CandidateTypes(CandidateTypes),
7352 CandidateSet(CandidateSet) {
7353 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007354 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007356 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007357 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007359 assert(getArithmeticType(FirstPromotedArithmeticType)
7360 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007361 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007362 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007363 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 "Invalid last promoted arithmetic type");
7365 }
7366
7367 // C++ [over.built]p3:
7368 //
7369 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7370 // is either volatile or empty, there exist candidate operator
7371 // functions of the form
7372 //
7373 // VQ T& operator++(VQ T&);
7374 // T operator++(VQ T&, int);
7375 //
7376 // C++ [over.built]p4:
7377 //
7378 // For every pair (T, VQ), where T is an arithmetic type other
7379 // than bool, and VQ is either volatile or empty, there exist
7380 // candidate operator functions of the form
7381 //
7382 // VQ T& operator--(VQ T&);
7383 // T operator--(VQ T&, int);
7384 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007385 if (!HasArithmeticOrEnumeralCandidateType)
7386 return;
7387
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007388 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7389 Arith < NumArithmeticTypes; ++Arith) {
7390 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007391 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007392 VisibleTypeConversionsQuals.hasVolatile(),
7393 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007394 }
7395 }
7396
7397 // C++ [over.built]p5:
7398 //
7399 // For every pair (T, VQ), where T is a cv-qualified or
7400 // cv-unqualified object type, and VQ is either volatile or
7401 // empty, there exist candidate operator functions of the form
7402 //
7403 // T*VQ& operator++(T*VQ&);
7404 // T*VQ& operator--(T*VQ&);
7405 // T* operator++(T*VQ&, int);
7406 // T* operator--(T*VQ&, int);
7407 void addPlusPlusMinusMinusPointerOverloads() {
7408 for (BuiltinCandidateTypeSet::iterator
7409 Ptr = CandidateTypes[0].pointer_begin(),
7410 PtrEnd = CandidateTypes[0].pointer_end();
7411 Ptr != PtrEnd; ++Ptr) {
7412 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007413 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007414 continue;
7415
7416 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007417 (!(*Ptr).isVolatileQualified() &&
7418 VisibleTypeConversionsQuals.hasVolatile()),
7419 (!(*Ptr).isRestrictQualified() &&
7420 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007421 }
7422 }
7423
7424 // C++ [over.built]p6:
7425 // For every cv-qualified or cv-unqualified object type T, there
7426 // exist candidate operator functions of the form
7427 //
7428 // T& operator*(T*);
7429 //
7430 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007431 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007432 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 // T& operator*(T*);
7434 void addUnaryStarPointerOverloads() {
7435 for (BuiltinCandidateTypeSet::iterator
7436 Ptr = CandidateTypes[0].pointer_begin(),
7437 PtrEnd = CandidateTypes[0].pointer_end();
7438 Ptr != PtrEnd; ++Ptr) {
7439 QualType ParamTy = *Ptr;
7440 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007441 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7442 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007443
Douglas Gregor02824322011-01-26 19:30:28 +00007444 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7445 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7446 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007447
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007448 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007449 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007450 }
7451 }
7452
7453 // C++ [over.built]p9:
7454 // For every promoted arithmetic type T, there exist candidate
7455 // operator functions of the form
7456 //
7457 // T operator+(T);
7458 // T operator-(T);
7459 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007460 if (!HasArithmeticOrEnumeralCandidateType)
7461 return;
7462
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463 for (unsigned Arith = FirstPromotedArithmeticType;
7464 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007465 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007466 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 }
7468
7469 // Extension: We also add these operators for vector types.
7470 for (BuiltinCandidateTypeSet::iterator
7471 Vec = CandidateTypes[0].vector_begin(),
7472 VecEnd = CandidateTypes[0].vector_end();
7473 Vec != VecEnd; ++Vec) {
7474 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007475 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 }
7477 }
7478
7479 // C++ [over.built]p8:
7480 // For every type T, there exist candidate operator functions of
7481 // the form
7482 //
7483 // T* operator+(T*);
7484 void addUnaryPlusPointerOverloads() {
7485 for (BuiltinCandidateTypeSet::iterator
7486 Ptr = CandidateTypes[0].pointer_begin(),
7487 PtrEnd = CandidateTypes[0].pointer_end();
7488 Ptr != PtrEnd; ++Ptr) {
7489 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007490 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 }
7492 }
7493
7494 // C++ [over.built]p10:
7495 // For every promoted integral type T, there exist candidate
7496 // operator functions of the form
7497 //
7498 // T operator~(T);
7499 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007500 if (!HasArithmeticOrEnumeralCandidateType)
7501 return;
7502
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007503 for (unsigned Int = FirstPromotedIntegralType;
7504 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007505 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007506 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007507 }
7508
7509 // Extension: We also add this operator for vector types.
7510 for (BuiltinCandidateTypeSet::iterator
7511 Vec = CandidateTypes[0].vector_begin(),
7512 VecEnd = CandidateTypes[0].vector_end();
7513 Vec != VecEnd; ++Vec) {
7514 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007515 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 }
7517 }
7518
7519 // C++ [over.match.oper]p16:
7520 // For every pointer to member type T, there exist candidate operator
7521 // functions of the form
7522 //
7523 // bool operator==(T,T);
7524 // bool operator!=(T,T);
7525 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7526 /// Set of (canonical) types that we've already handled.
7527 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7528
Richard Smithe54c3072013-05-05 15:51:06 +00007529 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007530 for (BuiltinCandidateTypeSet::iterator
7531 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7532 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7533 MemPtr != MemPtrEnd;
7534 ++MemPtr) {
7535 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007536 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 continue;
7538
7539 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007540 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007541 }
7542 }
7543 }
7544
7545 // C++ [over.built]p15:
7546 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007547 // For every T, where T is an enumeration type, a pointer type, or
7548 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 //
7550 // bool operator<(T, T);
7551 // bool operator>(T, T);
7552 // bool operator<=(T, T);
7553 // bool operator>=(T, T);
7554 // bool operator==(T, T);
7555 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007556 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007557 // C++ [over.match.oper]p3:
7558 // [...]the built-in candidates include all of the candidate operator
7559 // functions defined in 13.6 that, compared to the given operator, [...]
7560 // do not have the same parameter-type-list as any non-template non-member
7561 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007562 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007563 // Note that in practice, this only affects enumeration types because there
7564 // aren't any built-in candidates of record type, and a user-defined operator
7565 // must have an operand of record or enumeration type. Also, the only other
7566 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007567 // cannot be overloaded for enumeration types, so this is the only place
7568 // where we must suppress candidates like this.
7569 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7570 UserDefinedBinaryOperators;
7571
Richard Smithe54c3072013-05-05 15:51:06 +00007572 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007573 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7574 CandidateTypes[ArgIdx].enumeration_end()) {
7575 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7576 CEnd = CandidateSet.end();
7577 C != CEnd; ++C) {
7578 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7579 continue;
7580
Eli Friedman14f082b2012-09-18 21:52:24 +00007581 if (C->Function->isFunctionTemplateSpecialization())
7582 continue;
7583
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007584 QualType FirstParamType =
7585 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7586 QualType SecondParamType =
7587 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7588
7589 // Skip if either parameter isn't of enumeral type.
7590 if (!FirstParamType->isEnumeralType() ||
7591 !SecondParamType->isEnumeralType())
7592 continue;
7593
7594 // Add this operator to the set of known user-defined operators.
7595 UserDefinedBinaryOperators.insert(
7596 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7597 S.Context.getCanonicalType(SecondParamType)));
7598 }
7599 }
7600 }
7601
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007602 /// Set of (canonical) types that we've already handled.
7603 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7604
Richard Smithe54c3072013-05-05 15:51:06 +00007605 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007606 for (BuiltinCandidateTypeSet::iterator
7607 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7608 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7609 Ptr != PtrEnd; ++Ptr) {
7610 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007611 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007612 continue;
7613
7614 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007615 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007616 }
7617 for (BuiltinCandidateTypeSet::iterator
7618 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7619 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7620 Enum != EnumEnd; ++Enum) {
7621 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7622
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007623 // Don't add the same builtin candidate twice, or if a user defined
7624 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007625 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007626 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7627 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007628 continue;
7629
7630 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007631 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007633
7634 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7635 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007636 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007637 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007638 NullPtrTy))) {
7639 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007640 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007641 CandidateSet);
7642 }
7643 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007644 }
7645 }
7646
7647 // C++ [over.built]p13:
7648 //
7649 // For every cv-qualified or cv-unqualified object type T
7650 // there exist candidate operator functions of the form
7651 //
7652 // T* operator+(T*, ptrdiff_t);
7653 // T& operator[](T*, ptrdiff_t); [BELOW]
7654 // T* operator-(T*, ptrdiff_t);
7655 // T* operator+(ptrdiff_t, T*);
7656 // T& operator[](ptrdiff_t, T*); [BELOW]
7657 //
7658 // C++ [over.built]p14:
7659 //
7660 // For every T, where T is a pointer to object type, there
7661 // exist candidate operator functions of the form
7662 //
7663 // ptrdiff_t operator-(T, T);
7664 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7665 /// Set of (canonical) types that we've already handled.
7666 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7667
7668 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007669 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007670 S.Context.getPointerDiffType(),
7671 S.Context.getPointerDiffType(),
7672 };
7673 for (BuiltinCandidateTypeSet::iterator
7674 Ptr = CandidateTypes[Arg].pointer_begin(),
7675 PtrEnd = CandidateTypes[Arg].pointer_end();
7676 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007677 QualType PointeeTy = (*Ptr)->getPointeeType();
7678 if (!PointeeTy->isObjectType())
7679 continue;
7680
Eric Christopher9207a522015-08-21 16:24:01 +00007681 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682 if (Arg == 0 || Op == OO_Plus) {
7683 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7684 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007685 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007686 }
7687 if (Op == OO_Minus) {
7688 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007689 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007690 continue;
7691
7692 QualType ParamTypes[2] = { *Ptr, *Ptr };
7693 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007694 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007695 }
7696 }
7697 }
7698 }
7699
7700 // C++ [over.built]p12:
7701 //
7702 // For every pair of promoted arithmetic types L and R, there
7703 // exist candidate operator functions of the form
7704 //
7705 // LR operator*(L, R);
7706 // LR operator/(L, R);
7707 // LR operator+(L, R);
7708 // LR operator-(L, R);
7709 // bool operator<(L, R);
7710 // bool operator>(L, R);
7711 // bool operator<=(L, R);
7712 // bool operator>=(L, R);
7713 // bool operator==(L, R);
7714 // bool operator!=(L, R);
7715 //
7716 // where LR is the result of the usual arithmetic conversions
7717 // between types L and R.
7718 //
7719 // C++ [over.built]p24:
7720 //
7721 // For every pair of promoted arithmetic types L and R, there exist
7722 // candidate operator functions of the form
7723 //
7724 // LR operator?(bool, L, R);
7725 //
7726 // where LR is the result of the usual arithmetic conversions
7727 // between types L and R.
7728 // Our candidates ignore the first parameter.
7729 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007730 if (!HasArithmeticOrEnumeralCandidateType)
7731 return;
7732
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007733 for (unsigned Left = FirstPromotedArithmeticType;
7734 Left < LastPromotedArithmeticType; ++Left) {
7735 for (unsigned Right = FirstPromotedArithmeticType;
7736 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007737 QualType LandR[2] = { getArithmeticType(Left),
7738 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007739 QualType Result =
7740 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007741 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007742 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007743 }
7744 }
7745
7746 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7747 // conditional operator for vector types.
7748 for (BuiltinCandidateTypeSet::iterator
7749 Vec1 = CandidateTypes[0].vector_begin(),
7750 Vec1End = CandidateTypes[0].vector_end();
7751 Vec1 != Vec1End; ++Vec1) {
7752 for (BuiltinCandidateTypeSet::iterator
7753 Vec2 = CandidateTypes[1].vector_begin(),
7754 Vec2End = CandidateTypes[1].vector_end();
7755 Vec2 != Vec2End; ++Vec2) {
7756 QualType LandR[2] = { *Vec1, *Vec2 };
7757 QualType Result = S.Context.BoolTy;
7758 if (!isComparison) {
7759 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7760 Result = *Vec1;
7761 else
7762 Result = *Vec2;
7763 }
7764
Richard Smithe54c3072013-05-05 15:51:06 +00007765 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 }
7767 }
7768 }
7769
7770 // C++ [over.built]p17:
7771 //
7772 // For every pair of promoted integral types L and R, there
7773 // exist candidate operator functions of the form
7774 //
7775 // LR operator%(L, R);
7776 // LR operator&(L, R);
7777 // LR operator^(L, R);
7778 // LR operator|(L, R);
7779 // L operator<<(L, R);
7780 // L operator>>(L, R);
7781 //
7782 // where LR is the result of the usual arithmetic conversions
7783 // between types L and R.
7784 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007785 if (!HasArithmeticOrEnumeralCandidateType)
7786 return;
7787
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007788 for (unsigned Left = FirstPromotedIntegralType;
7789 Left < LastPromotedIntegralType; ++Left) {
7790 for (unsigned Right = FirstPromotedIntegralType;
7791 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007792 QualType LandR[2] = { getArithmeticType(Left),
7793 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007794 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7795 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007796 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007797 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 }
7799 }
7800 }
7801
7802 // C++ [over.built]p20:
7803 //
7804 // For every pair (T, VQ), where T is an enumeration or
7805 // pointer to member type and VQ is either volatile or
7806 // empty, there exist candidate operator functions of the form
7807 //
7808 // VQ T& operator=(VQ T&, T);
7809 void addAssignmentMemberPointerOrEnumeralOverloads() {
7810 /// Set of (canonical) types that we've already handled.
7811 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7812
7813 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7814 for (BuiltinCandidateTypeSet::iterator
7815 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7816 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7817 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007818 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 continue;
7820
Richard Smithe54c3072013-05-05 15:51:06 +00007821 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007822 }
7823
7824 for (BuiltinCandidateTypeSet::iterator
7825 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7826 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7827 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007828 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 continue;
7830
Richard Smithe54c3072013-05-05 15:51:06 +00007831 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007832 }
7833 }
7834 }
7835
7836 // C++ [over.built]p19:
7837 //
7838 // For every pair (T, VQ), where T is any type and VQ is either
7839 // volatile or empty, there exist candidate operator functions
7840 // of the form
7841 //
7842 // T*VQ& operator=(T*VQ&, T*);
7843 //
7844 // C++ [over.built]p21:
7845 //
7846 // For every pair (T, VQ), where T is a cv-qualified or
7847 // cv-unqualified object type and VQ is either volatile or
7848 // empty, there exist candidate operator functions of the form
7849 //
7850 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7851 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7852 void addAssignmentPointerOverloads(bool isEqualOp) {
7853 /// Set of (canonical) types that we've already handled.
7854 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7855
7856 for (BuiltinCandidateTypeSet::iterator
7857 Ptr = CandidateTypes[0].pointer_begin(),
7858 PtrEnd = CandidateTypes[0].pointer_end();
7859 Ptr != PtrEnd; ++Ptr) {
7860 // If this is operator=, keep track of the builtin candidates we added.
7861 if (isEqualOp)
7862 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007863 else if (!(*Ptr)->getPointeeType()->isObjectType())
7864 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007865
7866 // non-volatile version
7867 QualType ParamTypes[2] = {
7868 S.Context.getLValueReferenceType(*Ptr),
7869 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7870 };
Richard Smithe54c3072013-05-05 15:51:06 +00007871 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 /*IsAssigmentOperator=*/ isEqualOp);
7873
Douglas Gregor5bee2582012-06-04 00:15:09 +00007874 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7875 VisibleTypeConversionsQuals.hasVolatile();
7876 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007877 // volatile version
7878 ParamTypes[0] =
7879 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007880 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007881 /*IsAssigmentOperator=*/isEqualOp);
7882 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007883
7884 if (!(*Ptr).isRestrictQualified() &&
7885 VisibleTypeConversionsQuals.hasRestrict()) {
7886 // restrict version
7887 ParamTypes[0]
7888 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007890 /*IsAssigmentOperator=*/isEqualOp);
7891
7892 if (NeedVolatile) {
7893 // volatile restrict version
7894 ParamTypes[0]
7895 = S.Context.getLValueReferenceType(
7896 S.Context.getCVRQualifiedType(*Ptr,
7897 (Qualifiers::Volatile |
7898 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007900 /*IsAssigmentOperator=*/isEqualOp);
7901 }
7902 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007903 }
7904
7905 if (isEqualOp) {
7906 for (BuiltinCandidateTypeSet::iterator
7907 Ptr = CandidateTypes[1].pointer_begin(),
7908 PtrEnd = CandidateTypes[1].pointer_end();
7909 Ptr != PtrEnd; ++Ptr) {
7910 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007911 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 continue;
7913
Chandler Carruth8e543b32010-12-12 08:17:55 +00007914 QualType ParamTypes[2] = {
7915 S.Context.getLValueReferenceType(*Ptr),
7916 *Ptr,
7917 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007918
7919 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007920 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007921 /*IsAssigmentOperator=*/true);
7922
Douglas Gregor5bee2582012-06-04 00:15:09 +00007923 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7924 VisibleTypeConversionsQuals.hasVolatile();
7925 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 // volatile version
7927 ParamTypes[0] =
7928 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007929 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7930 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007931 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007932
7933 if (!(*Ptr).isRestrictQualified() &&
7934 VisibleTypeConversionsQuals.hasRestrict()) {
7935 // restrict version
7936 ParamTypes[0]
7937 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007938 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7939 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007940
7941 if (NeedVolatile) {
7942 // volatile restrict version
7943 ParamTypes[0]
7944 = S.Context.getLValueReferenceType(
7945 S.Context.getCVRQualifiedType(*Ptr,
7946 (Qualifiers::Volatile |
7947 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7949 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007950 }
7951 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007952 }
7953 }
7954 }
7955
7956 // C++ [over.built]p18:
7957 //
7958 // For every triple (L, VQ, R), where L is an arithmetic type,
7959 // VQ is either volatile or empty, and R is a promoted
7960 // arithmetic type, there exist candidate operator functions of
7961 // the form
7962 //
7963 // VQ L& operator=(VQ L&, R);
7964 // VQ L& operator*=(VQ L&, R);
7965 // VQ L& operator/=(VQ L&, R);
7966 // VQ L& operator+=(VQ L&, R);
7967 // VQ L& operator-=(VQ L&, R);
7968 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007969 if (!HasArithmeticOrEnumeralCandidateType)
7970 return;
7971
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007972 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7973 for (unsigned Right = FirstPromotedArithmeticType;
7974 Right < LastPromotedArithmeticType; ++Right) {
7975 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007976 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977
7978 // Add this built-in operator as a candidate (VQ is empty).
7979 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007980 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007981 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007982 /*IsAssigmentOperator=*/isEqualOp);
7983
7984 // Add this built-in operator as a candidate (VQ is 'volatile').
7985 if (VisibleTypeConversionsQuals.hasVolatile()) {
7986 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007987 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007988 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007990 /*IsAssigmentOperator=*/isEqualOp);
7991 }
7992 }
7993 }
7994
7995 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7996 for (BuiltinCandidateTypeSet::iterator
7997 Vec1 = CandidateTypes[0].vector_begin(),
7998 Vec1End = CandidateTypes[0].vector_end();
7999 Vec1 != Vec1End; ++Vec1) {
8000 for (BuiltinCandidateTypeSet::iterator
8001 Vec2 = CandidateTypes[1].vector_begin(),
8002 Vec2End = CandidateTypes[1].vector_end();
8003 Vec2 != Vec2End; ++Vec2) {
8004 QualType ParamTypes[2];
8005 ParamTypes[1] = *Vec2;
8006 // Add this built-in operator as a candidate (VQ is empty).
8007 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008009 /*IsAssigmentOperator=*/isEqualOp);
8010
8011 // Add this built-in operator as a candidate (VQ is 'volatile').
8012 if (VisibleTypeConversionsQuals.hasVolatile()) {
8013 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8014 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008016 /*IsAssigmentOperator=*/isEqualOp);
8017 }
8018 }
8019 }
8020 }
8021
8022 // C++ [over.built]p22:
8023 //
8024 // For every triple (L, VQ, R), where L is an integral type, VQ
8025 // is either volatile or empty, and R is a promoted integral
8026 // type, there exist candidate operator functions of the form
8027 //
8028 // VQ L& operator%=(VQ L&, R);
8029 // VQ L& operator<<=(VQ L&, R);
8030 // VQ L& operator>>=(VQ L&, R);
8031 // VQ L& operator&=(VQ L&, R);
8032 // VQ L& operator^=(VQ L&, R);
8033 // VQ L& operator|=(VQ L&, R);
8034 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008035 if (!HasArithmeticOrEnumeralCandidateType)
8036 return;
8037
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008038 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8039 for (unsigned Right = FirstPromotedIntegralType;
8040 Right < LastPromotedIntegralType; ++Right) {
8041 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008042 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043
8044 // Add this built-in operator as a candidate (VQ is empty).
8045 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008046 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008048 if (VisibleTypeConversionsQuals.hasVolatile()) {
8049 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008050 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8052 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008053 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 }
8055 }
8056 }
8057 }
8058
8059 // C++ [over.operator]p23:
8060 //
8061 // There also exist candidate operator functions of the form
8062 //
8063 // bool operator!(bool);
8064 // bool operator&&(bool, bool);
8065 // bool operator||(bool, bool);
8066 void addExclaimOverload() {
8067 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008068 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 /*IsAssignmentOperator=*/false,
8070 /*NumContextualBoolArguments=*/1);
8071 }
8072 void addAmpAmpOrPipePipeOverload() {
8073 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008074 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008075 /*IsAssignmentOperator=*/false,
8076 /*NumContextualBoolArguments=*/2);
8077 }
8078
8079 // C++ [over.built]p13:
8080 //
8081 // For every cv-qualified or cv-unqualified object type T there
8082 // exist candidate operator functions of the form
8083 //
8084 // T* operator+(T*, ptrdiff_t); [ABOVE]
8085 // T& operator[](T*, ptrdiff_t);
8086 // T* operator-(T*, ptrdiff_t); [ABOVE]
8087 // T* operator+(ptrdiff_t, T*); [ABOVE]
8088 // T& operator[](ptrdiff_t, T*);
8089 void addSubscriptOverloads() {
8090 for (BuiltinCandidateTypeSet::iterator
8091 Ptr = CandidateTypes[0].pointer_begin(),
8092 PtrEnd = CandidateTypes[0].pointer_end();
8093 Ptr != PtrEnd; ++Ptr) {
8094 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8095 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008096 if (!PointeeType->isObjectType())
8097 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008098
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008099 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8100
8101 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008102 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 }
8104
8105 for (BuiltinCandidateTypeSet::iterator
8106 Ptr = CandidateTypes[1].pointer_begin(),
8107 PtrEnd = CandidateTypes[1].pointer_end();
8108 Ptr != PtrEnd; ++Ptr) {
8109 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8110 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008111 if (!PointeeType->isObjectType())
8112 continue;
8113
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008114 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8115
8116 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008117 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118 }
8119 }
8120
8121 // C++ [over.built]p11:
8122 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8123 // C1 is the same type as C2 or is a derived class of C2, T is an object
8124 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8125 // there exist candidate operator functions of the form
8126 //
8127 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8128 //
8129 // where CV12 is the union of CV1 and CV2.
8130 void addArrowStarOverloads() {
8131 for (BuiltinCandidateTypeSet::iterator
8132 Ptr = CandidateTypes[0].pointer_begin(),
8133 PtrEnd = CandidateTypes[0].pointer_end();
8134 Ptr != PtrEnd; ++Ptr) {
8135 QualType C1Ty = (*Ptr);
8136 QualType C1;
8137 QualifierCollector Q1;
8138 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8139 if (!isa<RecordType>(C1))
8140 continue;
8141 // heuristic to reduce number of builtin candidates in the set.
8142 // Add volatile/restrict version only if there are conversions to a
8143 // volatile/restrict type.
8144 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8145 continue;
8146 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8147 continue;
8148 for (BuiltinCandidateTypeSet::iterator
8149 MemPtr = CandidateTypes[1].member_pointer_begin(),
8150 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8151 MemPtr != MemPtrEnd; ++MemPtr) {
8152 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8153 QualType C2 = QualType(mptr->getClass(), 0);
8154 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008155 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008156 break;
8157 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8158 // build CV12 T&
8159 QualType T = mptr->getPointeeType();
8160 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8161 T.isVolatileQualified())
8162 continue;
8163 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8164 T.isRestrictQualified())
8165 continue;
8166 T = Q1.apply(S.Context, T);
8167 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008168 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008169 }
8170 }
8171 }
8172
8173 // Note that we don't consider the first argument, since it has been
8174 // contextually converted to bool long ago. The candidates below are
8175 // therefore added as binary.
8176 //
8177 // C++ [over.built]p25:
8178 // For every type T, where T is a pointer, pointer-to-member, or scoped
8179 // enumeration type, there exist candidate operator functions of the form
8180 //
8181 // T operator?(bool, T, T);
8182 //
8183 void addConditionalOperatorOverloads() {
8184 /// Set of (canonical) types that we've already handled.
8185 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8186
8187 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8188 for (BuiltinCandidateTypeSet::iterator
8189 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8190 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8191 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008192 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008193 continue;
8194
8195 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008196 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008197 }
8198
8199 for (BuiltinCandidateTypeSet::iterator
8200 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8201 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8202 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008203 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008204 continue;
8205
8206 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008207 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 }
8209
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008210 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 for (BuiltinCandidateTypeSet::iterator
8212 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8213 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8214 Enum != EnumEnd; ++Enum) {
8215 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8216 continue;
8217
David Blaikie82e95a32014-11-19 07:49:47 +00008218 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008219 continue;
8220
8221 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008222 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008223 }
8224 }
8225 }
8226 }
8227};
8228
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008229} // end anonymous namespace
8230
8231/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8232/// operator overloads to the candidate set (C++ [over.built]), based
8233/// on the operator @p Op and the arguments given. For example, if the
8234/// operator is a binary '+', this routine might add "int
8235/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008236void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8237 SourceLocation OpLoc,
8238 ArrayRef<Expr *> Args,
8239 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008240 // Find all of the types that the arguments can convert to, but only
8241 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008242 // that make use of these types. Also record whether we encounter non-record
8243 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008244 Qualifiers VisibleTypeConversionsQuals;
8245 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008246 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008247 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008248
8249 bool HasNonRecordCandidateType = false;
8250 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008251 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008252 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008253 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008254 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8255 OpLoc,
8256 true,
8257 (Op == OO_Exclaim ||
8258 Op == OO_AmpAmp ||
8259 Op == OO_PipePipe),
8260 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008261 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8262 CandidateTypes[ArgIdx].hasNonRecordTypes();
8263 HasArithmeticOrEnumeralCandidateType =
8264 HasArithmeticOrEnumeralCandidateType ||
8265 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008266 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008267
Chandler Carruth00a38332010-12-13 01:44:01 +00008268 // Exit early when no non-record types have been added to the candidate set
8269 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008270 //
8271 // We can't exit early for !, ||, or &&, since there we have always have
8272 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008273 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008274 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008275 return;
8276
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008278 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008279 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008280 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 CandidateTypes, CandidateSet);
8282
8283 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008284 switch (Op) {
8285 case OO_None:
8286 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008287 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008288
Chandler Carruth5184de02010-12-12 08:51:33 +00008289 case OO_New:
8290 case OO_Delete:
8291 case OO_Array_New:
8292 case OO_Array_Delete:
8293 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008294 llvm_unreachable(
8295 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008296
8297 case OO_Comma:
8298 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008299 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008300 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008301 // -- For the operator ',', the unary operator '&', the
8302 // operator '->', or the operator 'co_await', the
8303 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008304 break;
8305
8306 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008307 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008308 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008309 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008310
8311 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008312 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008313 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008314 } else {
8315 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8316 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8317 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008318 break;
8319
Chandler Carruth5184de02010-12-12 08:51:33 +00008320 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008321 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008322 OpBuilder.addUnaryStarPointerOverloads();
8323 else
8324 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8325 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008326
Chandler Carruth5184de02010-12-12 08:51:33 +00008327 case OO_Slash:
8328 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008329 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008330
8331 case OO_PlusPlus:
8332 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008333 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8334 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008335 break;
8336
Douglas Gregor84605ae2009-08-24 13:43:27 +00008337 case OO_EqualEqual:
8338 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008339 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008340 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008341
Douglas Gregora11693b2008-11-12 17:17:38 +00008342 case OO_Less:
8343 case OO_Greater:
8344 case OO_LessEqual:
8345 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008346 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008347 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8348 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008349
Douglas Gregora11693b2008-11-12 17:17:38 +00008350 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008351 case OO_Caret:
8352 case OO_Pipe:
8353 case OO_LessLess:
8354 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008355 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008356 break;
8357
Chandler Carruth5184de02010-12-12 08:51:33 +00008358 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008359 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008360 // C++ [over.match.oper]p3:
8361 // -- For the operator ',', the unary operator '&', or the
8362 // operator '->', the built-in candidates set is empty.
8363 break;
8364
8365 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8366 break;
8367
8368 case OO_Tilde:
8369 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8370 break;
8371
Douglas Gregora11693b2008-11-12 17:17:38 +00008372 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008373 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008374 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008375
8376 case OO_PlusEqual:
8377 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008378 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008379 // Fall through.
8380
8381 case OO_StarEqual:
8382 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008383 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008384 break;
8385
8386 case OO_PercentEqual:
8387 case OO_LessLessEqual:
8388 case OO_GreaterGreaterEqual:
8389 case OO_AmpEqual:
8390 case OO_CaretEqual:
8391 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008392 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008393 break;
8394
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008395 case OO_Exclaim:
8396 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008397 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008398
Douglas Gregora11693b2008-11-12 17:17:38 +00008399 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008400 case OO_PipePipe:
8401 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008402 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008403
8404 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008405 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008406 break;
8407
8408 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008409 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008410 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008411
8412 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008413 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008414 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8415 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008416 }
8417}
8418
Douglas Gregore254f902009-02-04 00:32:51 +00008419/// \brief Add function candidates found via argument-dependent lookup
8420/// to the set of overloading candidates.
8421///
8422/// This routine performs argument-dependent name lookup based on the
8423/// given function name (which may also be an operator name) and adds
8424/// all of the overload candidates found by ADL to the overload
8425/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008426void
Douglas Gregore254f902009-02-04 00:32:51 +00008427Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008428 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008429 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008430 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008431 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008432 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008433 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008434
John McCall91f61fc2010-01-26 06:04:06 +00008435 // FIXME: This approach for uniquing ADL results (and removing
8436 // redundant candidates from the set) relies on pointer-equality,
8437 // which means we need to key off the canonical decl. However,
8438 // always going back to the canonical decl might not get us the
8439 // right set of default arguments. What default arguments are
8440 // we supposed to consider on ADL candidates, anyway?
8441
Douglas Gregorcabea402009-09-22 15:41:20 +00008442 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008443 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008444
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008445 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008446 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8447 CandEnd = CandidateSet.end();
8448 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008449 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008450 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008451 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008452 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008453 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008454
8455 // For each of the ADL candidates we found, add it to the overload
8456 // set.
John McCall8fe68082010-01-26 07:16:45 +00008457 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008458 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008459 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008460 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008461 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008462
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008463 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8464 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008465 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008466 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008467 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008468 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008469 }
Douglas Gregore254f902009-02-04 00:32:51 +00008470}
8471
George Burgess IV2a6150d2015-10-16 01:17:38 +00008472// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8473// Cand2 for overloading. This function assumes that all of the enable_if attrs
8474// on Cand1 and Cand2 have conditions that evaluate to true.
8475//
8476// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8477// Cand1's first N enable_if attributes have precisely the same conditions as
8478// Cand2's first N enable_if attributes (where N = the number of enable_if
8479// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8480static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8481 const FunctionDecl *Cand2) {
8482
8483 // FIXME: The next several lines are just
8484 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8485 // instead of reverse order which is how they're stored in the AST.
8486 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8487 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8488
8489 // Candidate 1 is better if it has strictly more attributes and
8490 // the common sequence is identical.
8491 if (Cand1Attrs.size() <= Cand2Attrs.size())
8492 return false;
8493
8494 auto Cand1I = Cand1Attrs.begin();
8495 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8496 for (auto &Cand2A : Cand2Attrs) {
8497 Cand1ID.clear();
8498 Cand2ID.clear();
8499
8500 auto &Cand1A = *Cand1I++;
8501 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8502 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8503 if (Cand1ID != Cand2ID)
8504 return false;
8505 }
8506
8507 return true;
8508}
8509
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008510/// isBetterOverloadCandidate - Determines whether the first overload
8511/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008512bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8513 const OverloadCandidate &Cand2,
8514 SourceLocation Loc,
8515 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008516 // Define viable functions to be better candidates than non-viable
8517 // functions.
8518 if (!Cand2.Viable)
8519 return Cand1.Viable;
8520 else if (!Cand1.Viable)
8521 return false;
8522
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008523 // C++ [over.match.best]p1:
8524 //
8525 // -- if F is a static member function, ICS1(F) is defined such
8526 // that ICS1(F) is neither better nor worse than ICS1(G) for
8527 // any function G, and, symmetrically, ICS1(G) is neither
8528 // better nor worse than ICS1(F).
8529 unsigned StartArg = 0;
8530 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8531 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008532
Douglas Gregord3cb3562009-07-07 23:38:56 +00008533 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008534 // A viable function F1 is defined to be a better function than another
8535 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008536 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008537 unsigned NumArgs = Cand1.NumConversions;
8538 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008539 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008540 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008541 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008542 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008543 Cand2.Conversions[ArgIdx])) {
8544 case ImplicitConversionSequence::Better:
8545 // Cand1 has a better conversion sequence.
8546 HasBetterConversion = true;
8547 break;
8548
8549 case ImplicitConversionSequence::Worse:
8550 // Cand1 can't be better than Cand2.
8551 return false;
8552
8553 case ImplicitConversionSequence::Indistinguishable:
8554 // Do nothing.
8555 break;
8556 }
8557 }
8558
Mike Stump11289f42009-09-09 15:08:12 +00008559 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008560 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008561 if (HasBetterConversion)
8562 return true;
8563
Douglas Gregora1f013e2008-11-07 22:36:19 +00008564 // -- the context is an initialization by user-defined conversion
8565 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8566 // from the return type of F1 to the destination type (i.e.,
8567 // the type of the entity being initialized) is a better
8568 // conversion sequence than the standard conversion sequence
8569 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008570 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008571 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008572 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008573 // First check whether we prefer one of the conversion functions over the
8574 // other. This only distinguishes the results in non-standard, extension
8575 // cases such as the conversion from a lambda closure type to a function
8576 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008577 ImplicitConversionSequence::CompareKind Result =
8578 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8579 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008580 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008581 Cand1.FinalConversion,
8582 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008583
Richard Smithec2748a2014-05-17 04:36:39 +00008584 if (Result != ImplicitConversionSequence::Indistinguishable)
8585 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008586
8587 // FIXME: Compare kind of reference binding if conversion functions
8588 // convert to a reference type used in direct reference binding, per
8589 // C++14 [over.match.best]p1 section 2 bullet 3.
8590 }
8591
8592 // -- F1 is a non-template function and F2 is a function template
8593 // specialization, or, if not that,
8594 bool Cand1IsSpecialization = Cand1.Function &&
8595 Cand1.Function->getPrimaryTemplate();
8596 bool Cand2IsSpecialization = Cand2.Function &&
8597 Cand2.Function->getPrimaryTemplate();
8598 if (Cand1IsSpecialization != Cand2IsSpecialization)
8599 return Cand2IsSpecialization;
8600
8601 // -- F1 and F2 are function template specializations, and the function
8602 // template for F1 is more specialized than the template for F2
8603 // according to the partial ordering rules described in 14.5.5.2, or,
8604 // if not that,
8605 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8606 if (FunctionTemplateDecl *BetterTemplate
8607 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8608 Cand2.Function->getPrimaryTemplate(),
8609 Loc,
8610 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8611 : TPOC_Call,
8612 Cand1.ExplicitCallArguments,
8613 Cand2.ExplicitCallArguments))
8614 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008615 }
8616
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008617 // Check for enable_if value-based overload resolution.
8618 if (Cand1.Function && Cand2.Function &&
8619 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008620 Cand2.Function->hasAttr<EnableIfAttr>()))
8621 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008622
Artem Belevich94a55e82015-09-22 17:22:59 +00008623 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8624 Cand1.Function && Cand2.Function) {
8625 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8626 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8627 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8628 }
8629
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008630 bool HasPS1 = Cand1.Function != nullptr &&
8631 functionHasPassObjectSizeParams(Cand1.Function);
8632 bool HasPS2 = Cand2.Function != nullptr &&
8633 functionHasPassObjectSizeParams(Cand2.Function);
8634 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008635}
8636
Richard Smith2dbe4042015-11-04 19:26:32 +00008637/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008638/// name lookup and overload resolution. This applies when the same internal/no
8639/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008640/// the same header). In such a case, we don't consider the declarations to
8641/// declare the same entity, but we also don't want lookups with both
8642/// declarations visible to be ambiguous in some cases (this happens when using
8643/// a modularized libstdc++).
8644bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8645 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008646 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8647 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8648 if (!VA || !VB)
8649 return false;
8650
8651 // The declarations must be declaring the same name as an internal linkage
8652 // entity in different modules.
8653 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8654 VB->getDeclContext()->getRedeclContext()) ||
8655 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8656 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8657 VA->isExternallyVisible() || VB->isExternallyVisible())
8658 return false;
8659
8660 // Check that the declarations appear to be equivalent.
8661 //
8662 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8663 // For constants and functions, we should check the initializer or body is
8664 // the same. For non-constant variables, we shouldn't allow it at all.
8665 if (Context.hasSameType(VA->getType(), VB->getType()))
8666 return true;
8667
8668 // Enum constants within unnamed enumerations will have different types, but
8669 // may still be similar enough to be interchangeable for our purposes.
8670 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8671 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8672 // Only handle anonymous enums. If the enumerations were named and
8673 // equivalent, they would have been merged to the same type.
8674 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8675 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8676 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8677 !Context.hasSameType(EnumA->getIntegerType(),
8678 EnumB->getIntegerType()))
8679 return false;
8680 // Allow this only if the value is the same for both enumerators.
8681 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8682 }
8683 }
8684
8685 // Nothing else is sufficiently similar.
8686 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008687}
8688
8689void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8690 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8691 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8692
8693 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8694 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8695 << !M << (M ? M->getFullModuleName() : "");
8696
8697 for (auto *E : Equiv) {
8698 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8699 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8700 << !M << (M ? M->getFullModuleName() : "");
8701 }
Richard Smith896c66e2015-10-21 07:13:52 +00008702}
8703
Mike Stump11289f42009-09-09 15:08:12 +00008704/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008705/// within an overload candidate set.
8706///
James Dennettffad8b72012-06-22 08:10:18 +00008707/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008708/// which overload resolution occurs.
8709///
James Dennettffad8b72012-06-22 08:10:18 +00008710/// \param Best If overload resolution was successful or found a deleted
8711/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008712///
8713/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008714OverloadingResult
8715OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008716 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008717 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008718 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008719 Best = end();
8720 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8721 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008723 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008724 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008725 }
8726
8727 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008728 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008729 return OR_No_Viable_Function;
8730
Richard Smith2dbe4042015-11-04 19:26:32 +00008731 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008732
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008733 // Make sure that this function is better than every other viable
8734 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008735 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008736 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008737 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008738 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008739 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008740 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8741 Cand->Function)) {
8742 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008743 continue;
8744 }
8745
John McCall5c32be02010-08-24 20:38:10 +00008746 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008747 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008749 }
Mike Stump11289f42009-09-09 15:08:12 +00008750
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008751 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008752 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008753 (Best->Function->isDeleted() ||
8754 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008755 return OR_Deleted;
8756
Richard Smith2dbe4042015-11-04 19:26:32 +00008757 if (!EquivalentCands.empty())
8758 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8759 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008760
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008761 return OR_Success;
8762}
8763
John McCall53262c92010-01-12 02:15:36 +00008764namespace {
8765
8766enum OverloadCandidateKind {
8767 oc_function,
8768 oc_method,
8769 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008770 oc_function_template,
8771 oc_method_template,
8772 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008773 oc_implicit_default_constructor,
8774 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008775 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008776 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008777 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008778 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008779};
8780
John McCalle1ac8d12010-01-13 00:25:19 +00008781OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8782 FunctionDecl *Fn,
8783 std::string &Description) {
8784 bool isTemplate = false;
8785
8786 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8787 isTemplate = true;
8788 Description = S.getTemplateArgumentBindingsText(
8789 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8790 }
John McCallfd0b2f82010-01-06 09:43:14 +00008791
8792 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008793 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008794 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008795
Sebastian Redl08905022011-02-05 19:23:19 +00008796 if (Ctor->getInheritedConstructor())
8797 return oc_implicit_inherited_constructor;
8798
Alexis Hunt119c10e2011-05-25 23:16:36 +00008799 if (Ctor->isDefaultConstructor())
8800 return oc_implicit_default_constructor;
8801
8802 if (Ctor->isMoveConstructor())
8803 return oc_implicit_move_constructor;
8804
8805 assert(Ctor->isCopyConstructor() &&
8806 "unexpected sort of implicit constructor");
8807 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008808 }
8809
8810 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8811 // This actually gets spelled 'candidate function' for now, but
8812 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008813 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008814 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008815
Alexis Hunt119c10e2011-05-25 23:16:36 +00008816 if (Meth->isMoveAssignmentOperator())
8817 return oc_implicit_move_assignment;
8818
Douglas Gregor12695102012-02-10 08:36:38 +00008819 if (Meth->isCopyAssignmentOperator())
8820 return oc_implicit_copy_assignment;
8821
8822 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8823 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008824 }
8825
John McCalle1ac8d12010-01-13 00:25:19 +00008826 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008827}
8828
Larisse Voufo98b20f12013-07-19 23:00:19 +00008829void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008830 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8831 if (!Ctor) return;
8832
8833 Ctor = Ctor->getInheritedConstructor();
8834 if (!Ctor) return;
8835
8836 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8837}
8838
John McCall53262c92010-01-12 02:15:36 +00008839} // end anonymous namespace
8840
George Burgess IV5f21c712015-10-12 19:57:04 +00008841static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8842 const FunctionDecl *FD) {
8843 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8844 bool AlwaysTrue;
8845 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8846 return false;
8847 if (!AlwaysTrue)
8848 return false;
8849 }
8850 return true;
8851}
8852
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008853/// \brief Returns true if we can take the address of the function.
8854///
8855/// \param Complain - If true, we'll emit a diagnostic
8856/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8857/// we in overload resolution?
8858/// \param Loc - The location of the statement we're complaining about. Ignored
8859/// if we're not complaining, or if we're in overload resolution.
8860static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8861 bool Complain,
8862 bool InOverloadResolution,
8863 SourceLocation Loc) {
8864 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8865 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008866 if (InOverloadResolution)
8867 S.Diag(FD->getLocStart(),
8868 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8869 else
8870 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8871 }
8872 return false;
8873 }
8874
8875 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8876 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8877 if (I == FD->param_end())
8878 return true;
8879
8880 if (Complain) {
8881 // Add one to ParamNo because it's user-facing
8882 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8883 if (InOverloadResolution)
8884 S.Diag(FD->getLocation(),
8885 diag::note_ovl_candidate_has_pass_object_size_params)
8886 << ParamNo;
8887 else
8888 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8889 << FD << ParamNo;
8890 }
8891 return false;
8892}
8893
8894static bool checkAddressOfCandidateIsAvailable(Sema &S,
8895 const FunctionDecl *FD) {
8896 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8897 /*InOverloadResolution=*/true,
8898 /*Loc=*/SourceLocation());
8899}
8900
8901bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8902 bool Complain,
8903 SourceLocation Loc) {
8904 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8905 /*InOverloadResolution=*/false,
8906 Loc);
8907}
8908
John McCall53262c92010-01-12 02:15:36 +00008909// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008910void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8911 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008912 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8913 return;
8914
John McCalle1ac8d12010-01-13 00:25:19 +00008915 std::string FnDesc;
8916 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008917 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8918 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008919
8920 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008921 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008922 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008923}
8924
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008925// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008926// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008927void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8928 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008929 assert(OverloadedExpr->getType() == Context.OverloadTy);
8930
8931 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8932 OverloadExpr *OvlExpr = Ovl.Expression;
8933
8934 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8935 IEnd = OvlExpr->decls_end();
8936 I != IEnd; ++I) {
8937 if (FunctionTemplateDecl *FunTmpl =
8938 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008939 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8940 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008941 } else if (FunctionDecl *Fun
8942 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008943 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008944 }
8945 }
8946}
8947
John McCall0d1da222010-01-12 00:44:57 +00008948/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8949/// "lead" diagnostic; it will be given two arguments, the source and
8950/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008951void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8952 Sema &S,
8953 SourceLocation CaretLoc,
8954 const PartialDiagnostic &PDiag) const {
8955 S.Diag(CaretLoc, PDiag)
8956 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008957 // FIXME: The note limiting machinery is borrowed from
8958 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8959 // refactoring here.
8960 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8961 unsigned CandsShown = 0;
8962 AmbiguousConversionSequence::const_iterator I, E;
8963 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8964 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8965 break;
8966 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008967 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008968 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008969 if (I != E)
8970 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008971}
8972
Richard Smith17c00b42014-11-12 01:24:00 +00008973static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008974 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00008975 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8976 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008977 assert(Cand->Function && "for now, candidate must be a function");
8978 FunctionDecl *Fn = Cand->Function;
8979
8980 // There's a conversion slot for the object argument if this is a
8981 // non-constructor method. Note that 'I' corresponds the
8982 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008983 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008984 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008985 if (I == 0)
8986 isObjectArgument = true;
8987 else
8988 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008989 }
8990
John McCalle1ac8d12010-01-13 00:25:19 +00008991 std::string FnDesc;
8992 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8993
John McCall6a61b522010-01-13 09:16:55 +00008994 Expr *FromExpr = Conv.Bad.FromExpr;
8995 QualType FromTy = Conv.Bad.getFromType();
8996 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008997
John McCallfb7ad0f2010-02-02 02:42:52 +00008998 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008999 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009000 Expr *E = FromExpr->IgnoreParens();
9001 if (isa<UnaryOperator>(E))
9002 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009003 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009004
9005 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9006 << (unsigned) FnKind << FnDesc
9007 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9008 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009009 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009010 return;
9011 }
9012
John McCall6d174642010-01-23 08:10:49 +00009013 // Do some hand-waving analysis to see if the non-viability is due
9014 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009015 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9016 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9017 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9018 CToTy = RT->getPointeeType();
9019 else {
9020 // TODO: detect and diagnose the full richness of const mismatches.
9021 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9022 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
9023 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
9024 }
9025
9026 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9027 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009028 Qualifiers FromQs = CFromTy.getQualifiers();
9029 Qualifiers ToQs = CToTy.getQualifiers();
9030
9031 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9032 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9033 << (unsigned) FnKind << FnDesc
9034 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9035 << FromTy
9036 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9037 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009038 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009039 return;
9040 }
9041
John McCall31168b02011-06-15 23:02:42 +00009042 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009043 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009044 << (unsigned) FnKind << FnDesc
9045 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9046 << FromTy
9047 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9048 << (unsigned) isObjectArgument << I+1;
9049 MaybeEmitInheritedConstructorNote(S, Fn);
9050 return;
9051 }
9052
Douglas Gregoraec25842011-04-26 23:16:46 +00009053 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9055 << (unsigned) FnKind << FnDesc
9056 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9057 << FromTy
9058 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9059 << (unsigned) isObjectArgument << I+1;
9060 MaybeEmitInheritedConstructorNote(S, Fn);
9061 return;
9062 }
9063
John McCall47000992010-01-14 03:28:57 +00009064 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9065 assert(CVR && "unexpected qualifiers mismatch");
9066
9067 if (isObjectArgument) {
9068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9069 << (unsigned) FnKind << FnDesc
9070 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9071 << FromTy << (CVR - 1);
9072 } else {
9073 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9074 << (unsigned) FnKind << FnDesc
9075 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9076 << FromTy << (CVR - 1) << I+1;
9077 }
Sebastian Redl08905022011-02-05 19:23:19 +00009078 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009079 return;
9080 }
9081
Sebastian Redla72462c2011-09-24 17:48:32 +00009082 // Special diagnostic for failure to convert an initializer list, since
9083 // telling the user that it has type void is not useful.
9084 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9085 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9086 << (unsigned) FnKind << FnDesc
9087 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9088 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9089 MaybeEmitInheritedConstructorNote(S, Fn);
9090 return;
9091 }
9092
John McCall6d174642010-01-23 08:10:49 +00009093 // Diagnose references or pointers to incomplete types differently,
9094 // since it's far from impossible that the incompleteness triggered
9095 // the failure.
9096 QualType TempFromTy = FromTy.getNonReferenceType();
9097 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9098 TempFromTy = PTy->getPointeeType();
9099 if (TempFromTy->isIncompleteType()) {
9100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9101 << (unsigned) FnKind << FnDesc
9102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9103 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009104 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009105 return;
9106 }
9107
Douglas Gregor56f2e342010-06-30 23:01:39 +00009108 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009109 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009110 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9111 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9112 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9113 FromPtrTy->getPointeeType()) &&
9114 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9115 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009116 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009117 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009118 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009119 }
9120 } else if (const ObjCObjectPointerType *FromPtrTy
9121 = FromTy->getAs<ObjCObjectPointerType>()) {
9122 if (const ObjCObjectPointerType *ToPtrTy
9123 = ToTy->getAs<ObjCObjectPointerType>())
9124 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9125 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9126 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9127 FromPtrTy->getPointeeType()) &&
9128 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009129 BaseToDerivedConversion = 2;
9130 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009131 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9132 !FromTy->isIncompleteType() &&
9133 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009134 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009135 BaseToDerivedConversion = 3;
9136 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9137 ToTy.getNonReferenceType().getCanonicalType() ==
9138 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9140 << (unsigned) FnKind << FnDesc
9141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9142 << (unsigned) isObjectArgument << I + 1;
9143 MaybeEmitInheritedConstructorNote(S, Fn);
9144 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009145 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009147
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009148 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009149 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009150 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009151 << (unsigned) FnKind << FnDesc
9152 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009153 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009154 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009155 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009156 return;
9157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009158
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009159 if (isa<ObjCObjectPointerType>(CFromTy) &&
9160 isa<PointerType>(CToTy)) {
9161 Qualifiers FromQs = CFromTy.getQualifiers();
9162 Qualifiers ToQs = CToTy.getQualifiers();
9163 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9165 << (unsigned) FnKind << FnDesc
9166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9167 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9168 MaybeEmitInheritedConstructorNote(S, Fn);
9169 return;
9170 }
9171 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009172
9173 if (TakingCandidateAddress &&
9174 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9175 return;
9176
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009177 // Emit the generic diagnostic and, optionally, add the hints to it.
9178 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9179 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009181 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9182 << (unsigned) (Cand->Fix.Kind);
9183
9184 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009185 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9186 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009187 FDiag << *HI;
9188 S.Diag(Fn->getLocation(), FDiag);
9189
Sebastian Redl08905022011-02-05 19:23:19 +00009190 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009191}
9192
Larisse Voufo98b20f12013-07-19 23:00:19 +00009193/// Additional arity mismatch diagnosis specific to a function overload
9194/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9195/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009196static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9197 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009198 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009199 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009201 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009202 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009203 // right number of arguments, because only overloaded operators have
9204 // the weird behavior of overloading member and non-member functions.
9205 // Just don't report anything.
9206 if (Fn->isInvalidDecl() &&
9207 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009208 return true;
9209
9210 if (NumArgs < MinParams) {
9211 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9212 (Cand->FailureKind == ovl_fail_bad_deduction &&
9213 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9214 } else {
9215 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9216 (Cand->FailureKind == ovl_fail_bad_deduction &&
9217 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9218 }
9219
9220 return false;
9221}
9222
9223/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009224static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009225 assert(isa<FunctionDecl>(D) &&
9226 "The templated declaration should at least be a function"
9227 " when diagnosing bad template argument deduction due to too many"
9228 " or too few arguments");
9229
9230 FunctionDecl *Fn = cast<FunctionDecl>(D);
9231
9232 // TODO: treat calls to a missing default constructor as a special case
9233 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9234 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009235
John McCall6a61b522010-01-13 09:16:55 +00009236 // at least / at most / exactly
9237 unsigned mode, modeCount;
9238 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009239 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9240 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009241 mode = 0; // "at least"
9242 else
9243 mode = 2; // "exactly"
9244 modeCount = MinParams;
9245 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009246 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009247 mode = 1; // "at most"
9248 else
9249 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009250 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009251 }
9252
9253 std::string Description;
9254 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9255
Richard Smith10ff50d2012-05-11 05:16:41 +00009256 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009258 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9259 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009260 else
9261 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009262 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9263 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009264 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009265}
9266
Larisse Voufo98b20f12013-07-19 23:00:19 +00009267/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009268static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9269 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009270 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9271 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9272}
Larisse Voufo47c08452013-07-19 22:53:23 +00009273
Richard Smith17c00b42014-11-12 01:24:00 +00009274static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9276 return FD->getDescribedFunctionTemplate();
9277 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9278 return RD->getDescribedClassTemplate();
9279
9280 llvm_unreachable("Unsupported: Getting the described template declaration"
9281 " for bad deduction diagnosis");
9282}
9283
9284/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009285static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9286 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009287 unsigned NumArgs,
9288 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009289 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009290 NamedDecl *ParamD;
9291 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9292 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9293 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009294 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009295 case Sema::TDK_Success:
9296 llvm_unreachable("TDK_success while diagnosing bad deduction");
9297
9298 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009299 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009300 S.Diag(Templated->getLocation(),
9301 diag::note_ovl_candidate_incomplete_deduction)
9302 << ParamD->getDeclName();
9303 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009304 return;
9305 }
9306
John McCall42d7d192010-08-05 09:05:08 +00009307 case Sema::TDK_Underqualified: {
9308 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9309 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9310
Larisse Voufo98b20f12013-07-19 23:00:19 +00009311 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009312
9313 // Param will have been canonicalized, but it should just be a
9314 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009315 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009316 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009317 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009318 assert(S.Context.hasSameType(Param, NonCanonParam));
9319
9320 // Arg has also been canonicalized, but there's nothing we can do
9321 // about that. It also doesn't matter as much, because it won't
9322 // have any template parameters in it (because deduction isn't
9323 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009324 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009325
Larisse Voufo98b20f12013-07-19 23:00:19 +00009326 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9327 << ParamD->getDeclName() << Arg << NonCanonParam;
9328 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009329 return;
9330 }
9331
9332 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009333 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009334 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009335 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009336 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009337 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009338 which = 1;
9339 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009340 which = 2;
9341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009342
Larisse Voufo98b20f12013-07-19 23:00:19 +00009343 S.Diag(Templated->getLocation(),
9344 diag::note_ovl_candidate_inconsistent_deduction)
9345 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9346 << *DeductionFailure.getSecondArg();
9347 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009348 return;
9349 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009350
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009351 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009352 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009353 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009354 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009355 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009356 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009357 else {
9358 int index = 0;
9359 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9360 index = TTP->getIndex();
9361 else if (NonTypeTemplateParmDecl *NTTP
9362 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9363 index = NTTP->getIndex();
9364 else
9365 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009366 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009367 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009368 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009369 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009370 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009371 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009372
Douglas Gregor02eb4832010-05-08 18:13:28 +00009373 case Sema::TDK_TooManyArguments:
9374 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009375 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009376 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009377
9378 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009379 S.Diag(Templated->getLocation(),
9380 diag::note_ovl_candidate_instantiation_depth);
9381 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009382 return;
9383
9384 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009385 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009386 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009387 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009388 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009389 TemplateArgString = " ";
9390 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009391 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009392 }
9393
Richard Smith6f8d2c62012-05-09 05:17:00 +00009394 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009395 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009396 if (PDiag && PDiag->second.getDiagID() ==
9397 diag::err_typename_nested_not_found_enable_if) {
9398 // FIXME: Use the source range of the condition, and the fully-qualified
9399 // name of the enable_if template. These are both present in PDiag.
9400 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9401 << "'enable_if'" << TemplateArgString;
9402 return;
9403 }
9404
Richard Smith9ca64612012-05-07 09:03:25 +00009405 // Format the SFINAE diagnostic into the argument string.
9406 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9407 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009408 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009409 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009410 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009411 SFINAEArgString = ": ";
9412 R = SourceRange(PDiag->first, PDiag->first);
9413 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9414 }
9415
Larisse Voufo98b20f12013-07-19 23:00:19 +00009416 S.Diag(Templated->getLocation(),
9417 diag::note_ovl_candidate_substitution_failure)
9418 << TemplateArgString << SFINAEArgString << R;
9419 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009420 return;
9421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009422
Richard Smith8c6eeb92013-01-31 04:03:12 +00009423 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009424 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9425 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009426 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009427 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009428 return;
9429 }
9430
Richard Smith9b534542015-12-31 02:02:54 +00009431 case Sema::TDK_DeducedMismatch: {
9432 // Format the template argument list into the argument string.
9433 SmallString<128> TemplateArgString;
9434 if (TemplateArgumentList *Args =
9435 DeductionFailure.getTemplateArgumentList()) {
9436 TemplateArgString = " ";
9437 TemplateArgString += S.getTemplateArgumentBindingsText(
9438 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9439 }
9440
9441 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9442 << (*DeductionFailure.getCallArgIndex() + 1)
9443 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9444 << TemplateArgString;
9445 break;
9446 }
9447
Richard Trieue3732352013-04-08 21:11:40 +00009448 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009449 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009450 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9451 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009452 if (FirstTA.getKind() == TemplateArgument::Template &&
9453 SecondTA.getKind() == TemplateArgument::Template) {
9454 TemplateName FirstTN = FirstTA.getAsTemplate();
9455 TemplateName SecondTN = SecondTA.getAsTemplate();
9456 if (FirstTN.getKind() == TemplateName::Template &&
9457 SecondTN.getKind() == TemplateName::Template) {
9458 if (FirstTN.getAsTemplateDecl()->getName() ==
9459 SecondTN.getAsTemplateDecl()->getName()) {
9460 // FIXME: This fixes a bad diagnostic where both templates are named
9461 // the same. This particular case is a bit difficult since:
9462 // 1) It is passed as a string to the diagnostic printer.
9463 // 2) The diagnostic printer only attempts to find a better
9464 // name for types, not decls.
9465 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009466 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009467 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9468 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9469 return;
9470 }
9471 }
9472 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009473
9474 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9475 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9476 return;
9477
Faisal Vali2b391ab2013-09-26 19:54:12 +00009478 // FIXME: For generic lambda parameters, check if the function is a lambda
9479 // call operator, and if so, emit a prettier and more informative
9480 // diagnostic that mentions 'auto' and lambda in addition to
9481 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009482 S.Diag(Templated->getLocation(),
9483 diag::note_ovl_candidate_non_deduced_mismatch)
9484 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009485 return;
Richard Trieue3732352013-04-08 21:11:40 +00009486 }
John McCall8b9ed552010-02-01 18:53:26 +00009487 // TODO: diagnose these individually, then kill off
9488 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009489 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009490 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9491 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009492 return;
9493 }
9494}
9495
Larisse Voufo98b20f12013-07-19 23:00:19 +00009496/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009497static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009498 unsigned NumArgs,
9499 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009500 unsigned TDK = Cand->DeductionFailure.Result;
9501 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9502 if (CheckArityMismatch(S, Cand, NumArgs))
9503 return;
9504 }
9505 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009506 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009507}
9508
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009509/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009510static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009511 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9512 FunctionDecl *Callee = Cand->Function;
9513
9514 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9515 CalleeTarget = S.IdentifyCUDATarget(Callee);
9516
9517 std::string FnDesc;
9518 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9519
9520 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009521 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9522
9523 // This could be an implicit constructor for which we could not infer the
9524 // target due to a collsion. Diagnose that case.
9525 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9526 if (Meth != nullptr && Meth->isImplicit()) {
9527 CXXRecordDecl *ParentClass = Meth->getParent();
9528 Sema::CXXSpecialMember CSM;
9529
9530 switch (FnKind) {
9531 default:
9532 return;
9533 case oc_implicit_default_constructor:
9534 CSM = Sema::CXXDefaultConstructor;
9535 break;
9536 case oc_implicit_copy_constructor:
9537 CSM = Sema::CXXCopyConstructor;
9538 break;
9539 case oc_implicit_move_constructor:
9540 CSM = Sema::CXXMoveConstructor;
9541 break;
9542 case oc_implicit_copy_assignment:
9543 CSM = Sema::CXXCopyAssignment;
9544 break;
9545 case oc_implicit_move_assignment:
9546 CSM = Sema::CXXMoveAssignment;
9547 break;
9548 };
9549
9550 bool ConstRHS = false;
9551 if (Meth->getNumParams()) {
9552 if (const ReferenceType *RT =
9553 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9554 ConstRHS = RT->getPointeeType().isConstQualified();
9555 }
9556 }
9557
9558 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9559 /* ConstRHS */ ConstRHS,
9560 /* Diagnose */ true);
9561 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009562}
9563
Richard Smith17c00b42014-11-12 01:24:00 +00009564static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009565 FunctionDecl *Callee = Cand->Function;
9566 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9567
9568 S.Diag(Callee->getLocation(),
9569 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9570 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9571}
9572
John McCall8b9ed552010-02-01 18:53:26 +00009573/// Generates a 'note' diagnostic for an overload candidate. We've
9574/// already generated a primary error at the call site.
9575///
9576/// It really does need to be a single diagnostic with its caret
9577/// pointed at the candidate declaration. Yes, this creates some
9578/// major challenges of technical writing. Yes, this makes pointing
9579/// out problems with specific arguments quite awkward. It's still
9580/// better than generating twenty screens of text for every failed
9581/// overload.
9582///
9583/// It would be great to be able to express per-candidate problems
9584/// more richly for those diagnostic clients that cared, but we'd
9585/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009586static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009587 unsigned NumArgs,
9588 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009589 FunctionDecl *Fn = Cand->Function;
9590
John McCall12f97bc2010-01-08 04:41:39 +00009591 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009592 if (Cand->Viable && (Fn->isDeleted() ||
9593 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009594 std::string FnDesc;
9595 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009596
9597 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009598 << FnKind << FnDesc
9599 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009600 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009601 return;
John McCall12f97bc2010-01-08 04:41:39 +00009602 }
9603
John McCalle1ac8d12010-01-13 00:25:19 +00009604 // We don't really have anything else to say about viable candidates.
9605 if (Cand->Viable) {
9606 S.NoteOverloadCandidate(Fn);
9607 return;
9608 }
John McCall0d1da222010-01-12 00:44:57 +00009609
John McCall6a61b522010-01-13 09:16:55 +00009610 switch (Cand->FailureKind) {
9611 case ovl_fail_too_many_arguments:
9612 case ovl_fail_too_few_arguments:
9613 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009614
John McCall6a61b522010-01-13 09:16:55 +00009615 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009616 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009617
John McCall578a1f82014-12-14 01:46:53 +00009618 case ovl_fail_illegal_constructor: {
9619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9620 << (Fn->getPrimaryTemplate() ? 1 : 0);
9621 MaybeEmitInheritedConstructorNote(S, Fn);
9622 return;
9623 }
9624
John McCallfe796dd2010-01-23 05:17:32 +00009625 case ovl_fail_trivial_conversion:
9626 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009627 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009628 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009629
John McCall65eb8792010-02-25 01:37:24 +00009630 case ovl_fail_bad_conversion: {
9631 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009632 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009633 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009634 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009635
John McCall6a61b522010-01-13 09:16:55 +00009636 // FIXME: this currently happens when we're called from SemaInit
9637 // when user-conversion overload fails. Figure out how to handle
9638 // those conditions and diagnose them well.
9639 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009640 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009641
9642 case ovl_fail_bad_target:
9643 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009644
9645 case ovl_fail_enable_if:
9646 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009647
9648 case ovl_fail_addr_not_available: {
9649 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9650 (void)Available;
9651 assert(!Available);
9652 break;
9653 }
John McCall65eb8792010-02-25 01:37:24 +00009654 }
John McCalld3224162010-01-08 00:58:21 +00009655}
9656
Richard Smith17c00b42014-11-12 01:24:00 +00009657static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009658 // Desugar the type of the surrogate down to a function type,
9659 // retaining as many typedefs as possible while still showing
9660 // the function type (and, therefore, its parameter types).
9661 QualType FnType = Cand->Surrogate->getConversionType();
9662 bool isLValueReference = false;
9663 bool isRValueReference = false;
9664 bool isPointer = false;
9665 if (const LValueReferenceType *FnTypeRef =
9666 FnType->getAs<LValueReferenceType>()) {
9667 FnType = FnTypeRef->getPointeeType();
9668 isLValueReference = true;
9669 } else if (const RValueReferenceType *FnTypeRef =
9670 FnType->getAs<RValueReferenceType>()) {
9671 FnType = FnTypeRef->getPointeeType();
9672 isRValueReference = true;
9673 }
9674 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9675 FnType = FnTypePtr->getPointeeType();
9676 isPointer = true;
9677 }
9678 // Desugar down to a function type.
9679 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9680 // Reconstruct the pointer/reference as appropriate.
9681 if (isPointer) FnType = S.Context.getPointerType(FnType);
9682 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9683 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9684
9685 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9686 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009687 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009688}
9689
Richard Smith17c00b42014-11-12 01:24:00 +00009690static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9691 SourceLocation OpLoc,
9692 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009693 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009694 std::string TypeStr("operator");
9695 TypeStr += Opc;
9696 TypeStr += "(";
9697 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009698 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009699 TypeStr += ")";
9700 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9701 } else {
9702 TypeStr += ", ";
9703 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9704 TypeStr += ")";
9705 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9706 }
9707}
9708
Richard Smith17c00b42014-11-12 01:24:00 +00009709static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9710 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009711 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009712 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9713 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009714 if (ICS.isBad()) break; // all meaningless after first invalid
9715 if (!ICS.isAmbiguous()) continue;
9716
John McCall5c32be02010-08-24 20:38:10 +00009717 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009718 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009719 }
9720}
9721
Larisse Voufo98b20f12013-07-19 23:00:19 +00009722static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009723 if (Cand->Function)
9724 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009725 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009726 return Cand->Surrogate->getLocation();
9727 return SourceLocation();
9728}
9729
Larisse Voufo98b20f12013-07-19 23:00:19 +00009730static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009731 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009732 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009733 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009734
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009735 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009736 case Sema::TDK_Incomplete:
9737 return 1;
9738
9739 case Sema::TDK_Underqualified:
9740 case Sema::TDK_Inconsistent:
9741 return 2;
9742
9743 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009744 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009745 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009746 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009747 return 3;
9748
9749 case Sema::TDK_InstantiationDepth:
9750 case Sema::TDK_FailedOverloadResolution:
9751 return 4;
9752
9753 case Sema::TDK_InvalidExplicitArguments:
9754 return 5;
9755
9756 case Sema::TDK_TooManyArguments:
9757 case Sema::TDK_TooFewArguments:
9758 return 6;
9759 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009760 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009761}
9762
Richard Smith17c00b42014-11-12 01:24:00 +00009763namespace {
John McCallad2587a2010-01-12 00:48:53 +00009764struct CompareOverloadCandidatesForDisplay {
9765 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009766 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009767 size_t NumArgs;
9768
Richard Smith0f59cb32015-12-18 21:45:41 +00009769 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009770 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009771
9772 bool operator()(const OverloadCandidate *L,
9773 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009774 // Fast-path this check.
9775 if (L == R) return false;
9776
John McCall12f97bc2010-01-08 04:41:39 +00009777 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009778 if (L->Viable) {
9779 if (!R->Viable) return true;
9780
9781 // TODO: introduce a tri-valued comparison for overload
9782 // candidates. Would be more worthwhile if we had a sort
9783 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009784 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9785 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009786 } else if (R->Viable)
9787 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009788
John McCall3712d9e2010-01-15 23:32:50 +00009789 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009790
John McCall3712d9e2010-01-15 23:32:50 +00009791 // Criteria by which we can sort non-viable candidates:
9792 if (!L->Viable) {
9793 // 1. Arity mismatches come after other candidates.
9794 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009795 L->FailureKind == ovl_fail_too_few_arguments) {
9796 if (R->FailureKind == ovl_fail_too_many_arguments ||
9797 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009798 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9799 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9800 if (LDist == RDist) {
9801 if (L->FailureKind == R->FailureKind)
9802 // Sort non-surrogates before surrogates.
9803 return !L->IsSurrogate && R->IsSurrogate;
9804 // Sort candidates requiring fewer parameters than there were
9805 // arguments given after candidates requiring more parameters
9806 // than there were arguments given.
9807 return L->FailureKind == ovl_fail_too_many_arguments;
9808 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009809 return LDist < RDist;
9810 }
John McCall3712d9e2010-01-15 23:32:50 +00009811 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009812 }
John McCall3712d9e2010-01-15 23:32:50 +00009813 if (R->FailureKind == ovl_fail_too_many_arguments ||
9814 R->FailureKind == ovl_fail_too_few_arguments)
9815 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009816
John McCallfe796dd2010-01-23 05:17:32 +00009817 // 2. Bad conversions come first and are ordered by the number
9818 // of bad conversions and quality of good conversions.
9819 if (L->FailureKind == ovl_fail_bad_conversion) {
9820 if (R->FailureKind != ovl_fail_bad_conversion)
9821 return true;
9822
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009823 // The conversion that can be fixed with a smaller number of changes,
9824 // comes first.
9825 unsigned numLFixes = L->Fix.NumConversionsFixed;
9826 unsigned numRFixes = R->Fix.NumConversionsFixed;
9827 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9828 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009829 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009830 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009831 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009832
John McCallfe796dd2010-01-23 05:17:32 +00009833 // If there's any ordering between the defined conversions...
9834 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009835 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009836
9837 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009838 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009839 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009840 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009841 L->Conversions[I],
9842 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009843 case ImplicitConversionSequence::Better:
9844 leftBetter++;
9845 break;
9846
9847 case ImplicitConversionSequence::Worse:
9848 leftBetter--;
9849 break;
9850
9851 case ImplicitConversionSequence::Indistinguishable:
9852 break;
9853 }
9854 }
9855 if (leftBetter > 0) return true;
9856 if (leftBetter < 0) return false;
9857
9858 } else if (R->FailureKind == ovl_fail_bad_conversion)
9859 return false;
9860
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009861 if (L->FailureKind == ovl_fail_bad_deduction) {
9862 if (R->FailureKind != ovl_fail_bad_deduction)
9863 return true;
9864
9865 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9866 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009867 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009868 } else if (R->FailureKind == ovl_fail_bad_deduction)
9869 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009870
John McCall3712d9e2010-01-15 23:32:50 +00009871 // TODO: others?
9872 }
9873
9874 // Sort everything else by location.
9875 SourceLocation LLoc = GetLocationForCandidate(L);
9876 SourceLocation RLoc = GetLocationForCandidate(R);
9877
9878 // Put candidates without locations (e.g. builtins) at the end.
9879 if (LLoc.isInvalid()) return false;
9880 if (RLoc.isInvalid()) return true;
9881
9882 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009883 }
9884};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009885}
John McCall12f97bc2010-01-08 04:41:39 +00009886
John McCallfe796dd2010-01-23 05:17:32 +00009887/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009888/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009889static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9890 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009891 assert(!Cand->Viable);
9892
9893 // Don't do anything on failures other than bad conversion.
9894 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9895
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009896 // We only want the FixIts if all the arguments can be corrected.
9897 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009898 // Use a implicit copy initialization to check conversion fixes.
9899 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009900
John McCallfe796dd2010-01-23 05:17:32 +00009901 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009902 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009903 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009904 while (true) {
9905 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9906 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009907 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009908 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009909 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009910 }
John McCallfe796dd2010-01-23 05:17:32 +00009911 }
9912
9913 if (ConvIdx == ConvCount)
9914 return;
9915
John McCall65eb8792010-02-25 01:37:24 +00009916 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9917 "remaining conversion is initialized?");
9918
Douglas Gregoradc7a702010-04-16 17:45:54 +00009919 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009920 // operation somehow.
9921 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009922
9923 const FunctionProtoType* Proto;
9924 unsigned ArgIdx = ConvIdx;
9925
9926 if (Cand->IsSurrogate) {
9927 QualType ConvType
9928 = Cand->Surrogate->getConversionType().getNonReferenceType();
9929 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9930 ConvType = ConvPtrType->getPointeeType();
9931 Proto = ConvType->getAs<FunctionProtoType>();
9932 ArgIdx--;
9933 } else if (Cand->Function) {
9934 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9935 if (isa<CXXMethodDecl>(Cand->Function) &&
9936 !isa<CXXConstructorDecl>(Cand->Function))
9937 ArgIdx--;
9938 } else {
9939 // Builtin binary operator with a bad first conversion.
9940 assert(ConvCount <= 3);
9941 for (; ConvIdx != ConvCount; ++ConvIdx)
9942 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009943 = TryCopyInitialization(S, Args[ConvIdx],
9944 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009945 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009946 /*InOverloadResolution*/ true,
9947 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009948 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009949 return;
9950 }
9951
9952 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009953 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009954 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009955 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009956 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9957 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9958 /*InOverloadResolution=*/true,
9959 /*AllowObjCWritebackConversion=*/
9960 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009961 // Store the FixIt in the candidate if it exists.
9962 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009963 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009964 }
John McCallfe796dd2010-01-23 05:17:32 +00009965 else
9966 Cand->Conversions[ConvIdx].setEllipsis();
9967 }
9968}
9969
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009970/// PrintOverloadCandidates - When overload resolution fails, prints
9971/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009972/// set.
John McCall5c32be02010-08-24 20:38:10 +00009973void OverloadCandidateSet::NoteCandidates(Sema &S,
9974 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009975 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009976 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009977 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009978 // Sort the candidates by viability and position. Sorting directly would
9979 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009980 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009981 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9982 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009983 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009984 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009985 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009986 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009987 if (Cand->Function || Cand->IsSurrogate)
9988 Cands.push_back(Cand);
9989 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9990 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009991 }
9992 }
9993
John McCallad2587a2010-01-12 00:48:53 +00009994 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +00009995 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009996
John McCall0d1da222010-01-12 00:44:57 +00009997 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009998
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009999 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010000 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010001 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010002 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10003 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010004
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010005 // Set an arbitrary limit on the number of candidate functions we'll spam
10006 // the user with. FIXME: This limit should depend on details of the
10007 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010008 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010009 break;
10010 }
10011 ++CandsShown;
10012
John McCalld3224162010-01-08 00:58:21 +000010013 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010014 NoteFunctionCandidate(S, Cand, Args.size(),
10015 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010016 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010017 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010018 else {
10019 assert(Cand->Viable &&
10020 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010021 // Generally we only see ambiguities including viable builtin
10022 // operators if overload resolution got screwed up by an
10023 // ambiguous user-defined conversion.
10024 //
10025 // FIXME: It's quite possible for different conversions to see
10026 // different ambiguities, though.
10027 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010028 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010029 ReportedAmbiguousConversions = true;
10030 }
John McCalld3224162010-01-08 00:58:21 +000010031
John McCall0d1da222010-01-12 00:44:57 +000010032 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010033 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010034 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010035 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010036
10037 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010038 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010039}
10040
Larisse Voufo98b20f12013-07-19 23:00:19 +000010041static SourceLocation
10042GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10043 return Cand->Specialization ? Cand->Specialization->getLocation()
10044 : SourceLocation();
10045}
10046
Richard Smith17c00b42014-11-12 01:24:00 +000010047namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010048struct CompareTemplateSpecCandidatesForDisplay {
10049 Sema &S;
10050 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10051
10052 bool operator()(const TemplateSpecCandidate *L,
10053 const TemplateSpecCandidate *R) {
10054 // Fast-path this check.
10055 if (L == R)
10056 return false;
10057
10058 // Assuming that both candidates are not matches...
10059
10060 // Sort by the ranking of deduction failures.
10061 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10062 return RankDeductionFailure(L->DeductionFailure) <
10063 RankDeductionFailure(R->DeductionFailure);
10064
10065 // Sort everything else by location.
10066 SourceLocation LLoc = GetLocationForCandidate(L);
10067 SourceLocation RLoc = GetLocationForCandidate(R);
10068
10069 // Put candidates without locations (e.g. builtins) at the end.
10070 if (LLoc.isInvalid())
10071 return false;
10072 if (RLoc.isInvalid())
10073 return true;
10074
10075 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10076 }
10077};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010078}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010079
10080/// Diagnose a template argument deduction failure.
10081/// We are treating these failures as overload failures due to bad
10082/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010083void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10084 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010085 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010086 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010087}
10088
10089void TemplateSpecCandidateSet::destroyCandidates() {
10090 for (iterator i = begin(), e = end(); i != e; ++i) {
10091 i->DeductionFailure.Destroy();
10092 }
10093}
10094
10095void TemplateSpecCandidateSet::clear() {
10096 destroyCandidates();
10097 Candidates.clear();
10098}
10099
10100/// NoteCandidates - When no template specialization match is found, prints
10101/// diagnostic messages containing the non-matching specializations that form
10102/// the candidate set.
10103/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10104/// OCD == OCD_AllCandidates and Cand->Viable == false.
10105void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10106 // Sort the candidates by position (assuming no candidate is a match).
10107 // Sorting directly would be prohibitive, so we make a set of pointers
10108 // and sort those.
10109 SmallVector<TemplateSpecCandidate *, 32> Cands;
10110 Cands.reserve(size());
10111 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10112 if (Cand->Specialization)
10113 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010114 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010115 // in general, want to list every possible builtin candidate.
10116 }
10117
10118 std::sort(Cands.begin(), Cands.end(),
10119 CompareTemplateSpecCandidatesForDisplay(S));
10120
10121 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10122 // for generalization purposes (?).
10123 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10124
10125 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10126 unsigned CandsShown = 0;
10127 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10128 TemplateSpecCandidate *Cand = *I;
10129
10130 // Set an arbitrary limit on the number of candidates we'll spam
10131 // the user with. FIXME: This limit should depend on details of the
10132 // candidate list.
10133 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10134 break;
10135 ++CandsShown;
10136
10137 assert(Cand->Specialization &&
10138 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010139 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010140 }
10141
10142 if (I != E)
10143 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10144}
10145
Douglas Gregorb491ed32011-02-19 21:32:49 +000010146// [PossiblyAFunctionType] --> [Return]
10147// NonFunctionType --> NonFunctionType
10148// R (A) --> R(A)
10149// R (*)(A) --> R (A)
10150// R (&)(A) --> R (A)
10151// R (S::*)(A) --> R (A)
10152QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10153 QualType Ret = PossiblyAFunctionType;
10154 if (const PointerType *ToTypePtr =
10155 PossiblyAFunctionType->getAs<PointerType>())
10156 Ret = ToTypePtr->getPointeeType();
10157 else if (const ReferenceType *ToTypeRef =
10158 PossiblyAFunctionType->getAs<ReferenceType>())
10159 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010160 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010161 PossiblyAFunctionType->getAs<MemberPointerType>())
10162 Ret = MemTypePtr->getPointeeType();
10163 Ret =
10164 Context.getCanonicalType(Ret).getUnqualifiedType();
10165 return Ret;
10166}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010167
Richard Smith17c00b42014-11-12 01:24:00 +000010168namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010169// A helper class to help with address of function resolution
10170// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010171class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010172 Sema& S;
10173 Expr* SourceExpr;
10174 const QualType& TargetType;
10175 QualType TargetFunctionType; // Extracted function type from target type
10176
10177 bool Complain;
10178 //DeclAccessPair& ResultFunctionAccessPair;
10179 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010180
Douglas Gregorb491ed32011-02-19 21:32:49 +000010181 bool TargetTypeIsNonStaticMemberFunction;
10182 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010183 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010184 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010185
Douglas Gregorb491ed32011-02-19 21:32:49 +000010186 OverloadExpr::FindResult OvlExprInfo;
10187 OverloadExpr *OvlExpr;
10188 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010189 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010190 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010191
Douglas Gregorb491ed32011-02-19 21:32:49 +000010192public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010193 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10194 const QualType &TargetType, bool Complain)
10195 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10196 Complain(Complain), Context(S.getASTContext()),
10197 TargetTypeIsNonStaticMemberFunction(
10198 !!TargetType->getAs<MemberPointerType>()),
10199 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010200 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010201 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010202 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10203 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010204 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010205 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010206
David Majnemera4f7c7a2013-08-01 06:13:59 +000010207 if (TargetFunctionType->isFunctionType()) {
10208 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10209 if (!UME->isImplicitAccess() &&
10210 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10211 StaticMemberFunctionFromBoundPointer = true;
10212 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10213 DeclAccessPair dap;
10214 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10215 OvlExpr, false, &dap)) {
10216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10217 if (!Method->isStatic()) {
10218 // If the target type is a non-function type and the function found
10219 // is a non-static member function, pretend as if that was the
10220 // target, it's the only possible type to end up with.
10221 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010222
David Majnemera4f7c7a2013-08-01 06:13:59 +000010223 // And skip adding the function if its not in the proper form.
10224 // We'll diagnose this due to an empty set of functions.
10225 if (!OvlExprInfo.HasFormOfMemberPointer)
10226 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010227 }
10228
David Majnemera4f7c7a2013-08-01 06:13:59 +000010229 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010230 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010231 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010232 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010233
10234 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010235 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010236
Douglas Gregorb491ed32011-02-19 21:32:49 +000010237 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10238 // C++ [over.over]p4:
10239 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010240 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010241 if (FoundNonTemplateFunction)
10242 EliminateAllTemplateMatches();
10243 else
10244 EliminateAllExceptMostSpecializedTemplate();
10245 }
10246 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010247
10248 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10249 Matches.size() > 1)
10250 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010251 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010252
10253 bool hasComplained() const { return HasComplained; }
10254
Douglas Gregorb491ed32011-02-19 21:32:49 +000010255private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010256 // Is A considered a better overload candidate for the desired type than B?
10257 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10258 return hasBetterEnableIfAttrs(S, A, B);
10259 }
10260
10261 // Returns true if we've eliminated any (read: all but one) candidates, false
10262 // otherwise.
10263 bool eliminiateSuboptimalOverloadCandidates() {
10264 // Same algorithm as overload resolution -- one pass to pick the "best",
10265 // another pass to be sure that nothing is better than the best.
10266 auto Best = Matches.begin();
10267 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10268 if (isBetterCandidate(I->second, Best->second))
10269 Best = I;
10270
10271 const FunctionDecl *BestFn = Best->second;
10272 auto IsBestOrInferiorToBest = [this, BestFn](
10273 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10274 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10275 };
10276
10277 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10278 // option, so we can potentially give the user a better error
10279 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10280 return false;
10281 Matches[0] = *Best;
10282 Matches.resize(1);
10283 return true;
10284 }
10285
Douglas Gregorb491ed32011-02-19 21:32:49 +000010286 bool isTargetTypeAFunction() const {
10287 return TargetFunctionType->isFunctionType();
10288 }
10289
10290 // [ToType] [Return]
10291
10292 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10293 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10294 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10295 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10296 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10297 }
10298
10299 // return true if any matching specializations were found
10300 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10301 const DeclAccessPair& CurAccessFunPair) {
10302 if (CXXMethodDecl *Method
10303 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10304 // Skip non-static function templates when converting to pointer, and
10305 // static when converting to member pointer.
10306 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10307 return false;
10308 }
10309 else if (TargetTypeIsNonStaticMemberFunction)
10310 return false;
10311
10312 // C++ [over.over]p2:
10313 // If the name is a function template, template argument deduction is
10314 // done (14.8.2.2), and if the argument deduction succeeds, the
10315 // resulting template argument list is used to generate a single
10316 // function template specialization, which is added to the set of
10317 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010318 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010319 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010320 if (Sema::TemplateDeductionResult Result
10321 = S.DeduceTemplateArguments(FunctionTemplate,
10322 &OvlExplicitTemplateArgs,
10323 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010324 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010325 // Make a note of the failed deduction for diagnostics.
10326 FailedCandidates.addCandidate()
10327 .set(FunctionTemplate->getTemplatedDecl(),
10328 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010329 return false;
10330 }
10331
Douglas Gregor19a41f12013-04-17 08:45:07 +000010332 // Template argument deduction ensures that we have an exact match or
10333 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010334 // This function template specicalization works.
10335 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010336 assert(S.isSameOrCompatibleFunctionType(
10337 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010338 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010339
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010340 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010341 return false;
10342
Douglas Gregorb491ed32011-02-19 21:32:49 +000010343 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10344 return true;
10345 }
10346
10347 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10348 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010349 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010350 // Skip non-static functions when converting to pointer, and static
10351 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010352 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10353 return false;
10354 }
10355 else if (TargetTypeIsNonStaticMemberFunction)
10356 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010357
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010358 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010359 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010360 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010361 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010362 return false;
10363
Richard Smith2a7d4812013-05-04 07:00:32 +000010364 // If any candidate has a placeholder return type, trigger its deduction
10365 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010366 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010367 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010368 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10369 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010370 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010371 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010372
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010373 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010374 return false;
10375
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010376 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010377 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10378 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010379 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010380 ResultTy) ||
10381 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10382 Matches.push_back(std::make_pair(
10383 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010384 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010385 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010386 }
Mike Stump11289f42009-09-09 15:08:12 +000010387 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010388
10389 return false;
10390 }
10391
10392 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10393 bool Ret = false;
10394
10395 // If the overload expression doesn't have the form of a pointer to
10396 // member, don't try to convert it to a pointer-to-member type.
10397 if (IsInvalidFormOfPointerToMemberFunction())
10398 return false;
10399
10400 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10401 E = OvlExpr->decls_end();
10402 I != E; ++I) {
10403 // Look through any using declarations to find the underlying function.
10404 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10405
10406 // C++ [over.over]p3:
10407 // Non-member functions and static member functions match
10408 // targets of type "pointer-to-function" or "reference-to-function."
10409 // Nonstatic member functions match targets of
10410 // type "pointer-to-member-function."
10411 // Note that according to DR 247, the containing class does not matter.
10412 if (FunctionTemplateDecl *FunctionTemplate
10413 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10414 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10415 Ret = true;
10416 }
10417 // If we have explicit template arguments supplied, skip non-templates.
10418 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10419 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10420 Ret = true;
10421 }
10422 assert(Ret || Matches.empty());
10423 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010424 }
10425
Douglas Gregorb491ed32011-02-19 21:32:49 +000010426 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010427 // [...] and any given function template specialization F1 is
10428 // eliminated if the set contains a second function template
10429 // specialization whose function template is more specialized
10430 // than the function template of F1 according to the partial
10431 // ordering rules of 14.5.5.2.
10432
10433 // The algorithm specified above is quadratic. We instead use a
10434 // two-pass algorithm (similar to the one used to identify the
10435 // best viable function in an overload set) that identifies the
10436 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010437
10438 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10439 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10440 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010441
Larisse Voufo98b20f12013-07-19 23:00:19 +000010442 // TODO: It looks like FailedCandidates does not serve much purpose
10443 // here, since the no_viable diagnostic has index 0.
10444 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010445 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010446 SourceExpr->getLocStart(), S.PDiag(),
10447 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10448 .second->getDeclName(),
10449 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10450 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010451
Douglas Gregorb491ed32011-02-19 21:32:49 +000010452 if (Result != MatchesCopy.end()) {
10453 // Make it the first and only element
10454 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10455 Matches[0].second = cast<FunctionDecl>(*Result);
10456 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010457 } else
10458 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010460
Douglas Gregorb491ed32011-02-19 21:32:49 +000010461 void EliminateAllTemplateMatches() {
10462 // [...] any function template specializations in the set are
10463 // eliminated if the set also contains a non-template function, [...]
10464 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010465 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010466 ++I;
10467 else {
10468 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010469 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010470 }
10471 }
10472 }
10473
Artem Belevich94a55e82015-09-22 17:22:59 +000010474 void EliminateSuboptimalCudaMatches() {
10475 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10476 }
10477
Douglas Gregorb491ed32011-02-19 21:32:49 +000010478public:
10479 void ComplainNoMatchesFound() const {
10480 assert(Matches.empty());
10481 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10482 << OvlExpr->getName() << TargetFunctionType
10483 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010484 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010485 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10486 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010487 else {
10488 // We have some deduction failure messages. Use them to diagnose
10489 // the function templates, and diagnose the non-template candidates
10490 // normally.
10491 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10492 IEnd = OvlExpr->decls_end();
10493 I != IEnd; ++I)
10494 if (FunctionDecl *Fun =
10495 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010496 if (!functionHasPassObjectSizeParams(Fun))
10497 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10498 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010499 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10500 }
10501 }
10502
Douglas Gregorb491ed32011-02-19 21:32:49 +000010503 bool IsInvalidFormOfPointerToMemberFunction() const {
10504 return TargetTypeIsNonStaticMemberFunction &&
10505 !OvlExprInfo.HasFormOfMemberPointer;
10506 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010507
Douglas Gregorb491ed32011-02-19 21:32:49 +000010508 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10509 // TODO: Should we condition this on whether any functions might
10510 // have matched, or is it more appropriate to do that in callers?
10511 // TODO: a fixit wouldn't hurt.
10512 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10513 << TargetType << OvlExpr->getSourceRange();
10514 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010515
10516 bool IsStaticMemberFunctionFromBoundPointer() const {
10517 return StaticMemberFunctionFromBoundPointer;
10518 }
10519
10520 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10521 S.Diag(OvlExpr->getLocStart(),
10522 diag::err_invalid_form_pointer_member_function)
10523 << OvlExpr->getSourceRange();
10524 }
10525
Douglas Gregorb491ed32011-02-19 21:32:49 +000010526 void ComplainOfInvalidConversion() const {
10527 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10528 << OvlExpr->getName() << TargetType;
10529 }
10530
10531 void ComplainMultipleMatchesFound() const {
10532 assert(Matches.size() > 1);
10533 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10534 << OvlExpr->getName()
10535 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010536 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10537 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010538 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010539
10540 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10541
Douglas Gregorb491ed32011-02-19 21:32:49 +000010542 int getNumMatches() const { return Matches.size(); }
10543
10544 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010545 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010546 return Matches[0].second;
10547 }
10548
10549 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010550 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010551 return &Matches[0].first;
10552 }
10553};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010554}
Richard Smith17c00b42014-11-12 01:24:00 +000010555
Douglas Gregorb491ed32011-02-19 21:32:49 +000010556/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10557/// an overloaded function (C++ [over.over]), where @p From is an
10558/// expression with overloaded function type and @p ToType is the type
10559/// we're trying to resolve to. For example:
10560///
10561/// @code
10562/// int f(double);
10563/// int f(int);
10564///
10565/// int (*pfd)(double) = f; // selects f(double)
10566/// @endcode
10567///
10568/// This routine returns the resulting FunctionDecl if it could be
10569/// resolved, and NULL otherwise. When @p Complain is true, this
10570/// routine will emit diagnostics if there is an error.
10571FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010572Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10573 QualType TargetType,
10574 bool Complain,
10575 DeclAccessPair &FoundResult,
10576 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010577 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010578
10579 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10580 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010581 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010582 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010583 bool ShouldComplain = Complain && !Resolver.hasComplained();
10584 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010585 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10586 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10587 else
10588 Resolver.ComplainNoMatchesFound();
10589 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010590 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010591 Resolver.ComplainMultipleMatchesFound();
10592 else if (NumMatches == 1) {
10593 Fn = Resolver.getMatchingFunctionDecl();
10594 assert(Fn);
10595 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010596 if (Complain) {
10597 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10598 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10599 else
10600 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10601 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010602 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010603
10604 if (pHadMultipleCandidates)
10605 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010606 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010607}
10608
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010609/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010610/// resolve that overloaded function expression down to a single function.
10611///
10612/// This routine can only resolve template-ids that refer to a single function
10613/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010614/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010615/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010616///
10617/// If no template-ids are found, no diagnostics are emitted and NULL is
10618/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010619FunctionDecl *
10620Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10621 bool Complain,
10622 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010623 // C++ [over.over]p1:
10624 // [...] [Note: any redundant set of parentheses surrounding the
10625 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010626 // C++ [over.over]p1:
10627 // [...] The overloaded function name can be preceded by the &
10628 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010629
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010630 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010631 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010632 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010633
10634 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010635 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010636 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010637
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010638 // Look through all of the overloaded functions, searching for one
10639 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010640 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010641 for (UnresolvedSetIterator I = ovl->decls_begin(),
10642 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010643 // C++0x [temp.arg.explicit]p3:
10644 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010645 // where deduction is not done, if a template argument list is
10646 // specified and it, along with any default template arguments,
10647 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010648 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010649 FunctionTemplateDecl *FunctionTemplate
10650 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010651
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010652 // C++ [over.over]p2:
10653 // If the name is a function template, template argument deduction is
10654 // done (14.8.2.2), and if the argument deduction succeeds, the
10655 // resulting template argument list is used to generate a single
10656 // function template specialization, which is added to the set of
10657 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010658 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010659 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010660 if (TemplateDeductionResult Result
10661 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010662 Specialization, Info,
10663 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010664 // Make a note of the failed deduction for diagnostics.
10665 // TODO: Actually use the failed-deduction info?
10666 FailedCandidates.addCandidate()
10667 .set(FunctionTemplate->getTemplatedDecl(),
10668 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010669 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010670 }
10671
John McCall0009fcc2011-04-26 20:42:42 +000010672 assert(Specialization && "no specialization and no error?");
10673
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010674 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010675 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010676 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010677 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10678 << ovl->getName();
10679 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010680 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010681 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010682 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010683
John McCall0009fcc2011-04-26 20:42:42 +000010684 Matched = Specialization;
10685 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010687
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010688 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010689 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010690 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010691 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010692
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010693 return Matched;
10694}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010695
Douglas Gregor1beec452011-03-12 01:48:56 +000010696
10697
10698
John McCall50a2c2c2011-10-11 23:14:30 +000010699// Resolve and fix an overloaded expression that can be resolved
10700// because it identifies a single function template specialization.
10701//
Douglas Gregor1beec452011-03-12 01:48:56 +000010702// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010703//
10704// Return true if it was logically possible to so resolve the
10705// expression, regardless of whether or not it succeeded. Always
10706// returns true if 'complain' is set.
10707bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10708 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010709 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010710 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010711 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010712 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010713
John McCall50a2c2c2011-10-11 23:14:30 +000010714 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010715
John McCall0009fcc2011-04-26 20:42:42 +000010716 DeclAccessPair found;
10717 ExprResult SingleFunctionExpression;
10718 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10719 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010720 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010721 SrcExpr = ExprError();
10722 return true;
10723 }
John McCall0009fcc2011-04-26 20:42:42 +000010724
10725 // It is only correct to resolve to an instance method if we're
10726 // resolving a form that's permitted to be a pointer to member.
10727 // Otherwise we'll end up making a bound member expression, which
10728 // is illegal in all the contexts we resolve like this.
10729 if (!ovl.HasFormOfMemberPointer &&
10730 isa<CXXMethodDecl>(fn) &&
10731 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010732 if (!complain) return false;
10733
10734 Diag(ovl.Expression->getExprLoc(),
10735 diag::err_bound_member_function)
10736 << 0 << ovl.Expression->getSourceRange();
10737
10738 // TODO: I believe we only end up here if there's a mix of
10739 // static and non-static candidates (otherwise the expression
10740 // would have 'bound member' type, not 'overload' type).
10741 // Ideally we would note which candidate was chosen and why
10742 // the static candidates were rejected.
10743 SrcExpr = ExprError();
10744 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010745 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010746
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010747 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010748 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010749 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010750
10751 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010752 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010753 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010754 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010755 if (SingleFunctionExpression.isInvalid()) {
10756 SrcExpr = ExprError();
10757 return true;
10758 }
10759 }
John McCall0009fcc2011-04-26 20:42:42 +000010760 }
10761
10762 if (!SingleFunctionExpression.isUsable()) {
10763 if (complain) {
10764 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10765 << ovl.Expression->getName()
10766 << DestTypeForComplaining
10767 << OpRangeForComplaining
10768 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010769 NoteAllOverloadCandidates(SrcExpr.get());
10770
10771 SrcExpr = ExprError();
10772 return true;
10773 }
10774
10775 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010776 }
10777
John McCall50a2c2c2011-10-11 23:14:30 +000010778 SrcExpr = SingleFunctionExpression;
10779 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010780}
10781
Douglas Gregorcabea402009-09-22 15:41:20 +000010782/// \brief Add a single candidate to the overload set.
10783static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010784 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010785 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010786 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010787 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010788 bool PartialOverloading,
10789 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010790 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010791 if (isa<UsingShadowDecl>(Callee))
10792 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10793
Douglas Gregorcabea402009-09-22 15:41:20 +000010794 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010795 if (ExplicitTemplateArgs) {
10796 assert(!KnownValid && "Explicit template arguments?");
10797 return;
10798 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010799 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10800 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010801 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010802 return;
John McCalld14a8642009-11-21 08:51:07 +000010803 }
10804
10805 if (FunctionTemplateDecl *FuncTemplate
10806 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010807 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010808 ExplicitTemplateArgs, Args, CandidateSet,
10809 /*SuppressUsedConversions=*/false,
10810 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010811 return;
10812 }
10813
Richard Smith95ce4f62011-06-26 22:19:54 +000010814 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010815}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010816
Douglas Gregorcabea402009-09-22 15:41:20 +000010817/// \brief Add the overload candidates named by callee and/or found by argument
10818/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010819void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010820 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010821 OverloadCandidateSet &CandidateSet,
10822 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010823
10824#ifndef NDEBUG
10825 // Verify that ArgumentDependentLookup is consistent with the rules
10826 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010827 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010828 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10829 // and let Y be the lookup set produced by argument dependent
10830 // lookup (defined as follows). If X contains
10831 //
10832 // -- a declaration of a class member, or
10833 //
10834 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010835 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010836 //
10837 // -- a declaration that is neither a function or a function
10838 // template
10839 //
10840 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010841
John McCall57500772009-12-16 12:17:52 +000010842 if (ULE->requiresADL()) {
10843 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10844 E = ULE->decls_end(); I != E; ++I) {
10845 assert(!(*I)->getDeclContext()->isRecord());
10846 assert(isa<UsingShadowDecl>(*I) ||
10847 !(*I)->getDeclContext()->isFunctionOrMethod());
10848 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010849 }
10850 }
10851#endif
10852
John McCall57500772009-12-16 12:17:52 +000010853 // It would be nice to avoid this copy.
10854 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010855 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010856 if (ULE->hasExplicitTemplateArgs()) {
10857 ULE->copyTemplateArgumentsInto(TABuffer);
10858 ExplicitTemplateArgs = &TABuffer;
10859 }
10860
10861 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10862 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010863 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10864 CandidateSet, PartialOverloading,
10865 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010866
John McCall57500772009-12-16 12:17:52 +000010867 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010868 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010869 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010870 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010871}
John McCalld681c392009-12-16 08:11:27 +000010872
Richard Smith0603bbb2013-06-12 22:56:54 +000010873/// Determine whether a declaration with the specified name could be moved into
10874/// a different namespace.
10875static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10876 switch (Name.getCXXOverloadedOperator()) {
10877 case OO_New: case OO_Array_New:
10878 case OO_Delete: case OO_Array_Delete:
10879 return false;
10880
10881 default:
10882 return true;
10883 }
10884}
10885
Richard Smith998a5912011-06-05 22:42:48 +000010886/// Attempt to recover from an ill-formed use of a non-dependent name in a
10887/// template, where the non-dependent name was declared after the template
10888/// was defined. This is common in code written for a compilers which do not
10889/// correctly implement two-stage name lookup.
10890///
10891/// Returns true if a viable candidate was found and a diagnostic was issued.
10892static bool
10893DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10894 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010895 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010896 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010897 ArrayRef<Expr *> Args,
10898 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010899 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10900 return false;
10901
10902 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010903 if (DC->isTransparentContext())
10904 continue;
10905
Richard Smith998a5912011-06-05 22:42:48 +000010906 SemaRef.LookupQualifiedName(R, DC);
10907
10908 if (!R.empty()) {
10909 R.suppressDiagnostics();
10910
10911 if (isa<CXXRecordDecl>(DC)) {
10912 // Don't diagnose names we find in classes; we get much better
10913 // diagnostics for these from DiagnoseEmptyLookup.
10914 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010915 if (DoDiagnoseEmptyLookup)
10916 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010917 return false;
10918 }
10919
Richard Smith100b24a2014-04-17 01:52:14 +000010920 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010921 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10922 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010923 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010924 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010925
10926 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010927 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010928 // No viable functions. Don't bother the user with notes for functions
10929 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010930 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010931 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010932 }
Richard Smith998a5912011-06-05 22:42:48 +000010933
10934 // Find the namespaces where ADL would have looked, and suggest
10935 // declaring the function there instead.
10936 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10937 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010938 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010939 AssociatedNamespaces,
10940 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010941 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010942 if (canBeDeclaredInNamespace(R.getLookupName())) {
10943 DeclContext *Std = SemaRef.getStdNamespace();
10944 for (Sema::AssociatedNamespaceSet::iterator
10945 it = AssociatedNamespaces.begin(),
10946 end = AssociatedNamespaces.end(); it != end; ++it) {
10947 // Never suggest declaring a function within namespace 'std'.
10948 if (Std && Std->Encloses(*it))
10949 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010950
Richard Smith0603bbb2013-06-12 22:56:54 +000010951 // Never suggest declaring a function within a namespace with a
10952 // reserved name, like __gnu_cxx.
10953 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10954 if (NS &&
10955 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10956 continue;
10957
10958 SuggestedNamespaces.insert(*it);
10959 }
Richard Smith998a5912011-06-05 22:42:48 +000010960 }
10961
10962 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10963 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010964 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010965 SemaRef.Diag(Best->Function->getLocation(),
10966 diag::note_not_found_by_two_phase_lookup)
10967 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010968 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010969 SemaRef.Diag(Best->Function->getLocation(),
10970 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010971 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010972 } else {
10973 // FIXME: It would be useful to list the associated namespaces here,
10974 // but the diagnostics infrastructure doesn't provide a way to produce
10975 // a localized representation of a list of items.
10976 SemaRef.Diag(Best->Function->getLocation(),
10977 diag::note_not_found_by_two_phase_lookup)
10978 << R.getLookupName() << 2;
10979 }
10980
10981 // Try to recover by calling this function.
10982 return true;
10983 }
10984
10985 R.clear();
10986 }
10987
10988 return false;
10989}
10990
10991/// Attempt to recover from ill-formed use of a non-dependent operator in a
10992/// template, where the non-dependent operator was declared after the template
10993/// was defined.
10994///
10995/// Returns true if a viable candidate was found and a diagnostic was issued.
10996static bool
10997DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10998 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010999 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011000 DeclarationName OpName =
11001 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11002 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11003 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011004 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011005 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011006}
11007
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011008namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011009class BuildRecoveryCallExprRAII {
11010 Sema &SemaRef;
11011public:
11012 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11013 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11014 SemaRef.IsBuildingRecoveryCallExpr = true;
11015 }
11016
11017 ~BuildRecoveryCallExprRAII() {
11018 SemaRef.IsBuildingRecoveryCallExpr = false;
11019 }
11020};
11021
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011022}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011023
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011024static std::unique_ptr<CorrectionCandidateCallback>
11025MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11026 bool HasTemplateArgs, bool AllowTypoCorrection) {
11027 if (!AllowTypoCorrection)
11028 return llvm::make_unique<NoTypoCorrectionCCC>();
11029 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11030 HasTemplateArgs, ME);
11031}
11032
John McCalld681c392009-12-16 08:11:27 +000011033/// Attempts to recover from a call where no functions were found.
11034///
11035/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011036static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011037BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011038 UnresolvedLookupExpr *ULE,
11039 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011040 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011041 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011042 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011043 // Do not try to recover if it is already building a recovery call.
11044 // This stops infinite loops for template instantiations like
11045 //
11046 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11047 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11048 //
11049 if (SemaRef.IsBuildingRecoveryCallExpr)
11050 return ExprError();
11051 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011052
11053 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011054 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011055 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011056
John McCall57500772009-12-16 12:17:52 +000011057 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011058 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011059 if (ULE->hasExplicitTemplateArgs()) {
11060 ULE->copyTemplateArgumentsInto(TABuffer);
11061 ExplicitTemplateArgs = &TABuffer;
11062 }
11063
John McCalld681c392009-12-16 08:11:27 +000011064 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11065 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011066 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011067 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011068 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011069 ExplicitTemplateArgs, Args,
11070 &DoDiagnoseEmptyLookup) &&
11071 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11072 S, SS, R,
11073 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11074 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11075 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011076 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011077
John McCall57500772009-12-16 12:17:52 +000011078 assert(!R.empty() && "lookup results empty despite recovery");
11079
11080 // Build an implicit member call if appropriate. Just drop the
11081 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011082 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011083 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011084 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11085 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011086 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011087 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011088 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011089 else
11090 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11091
11092 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011093 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011094
11095 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011096 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011097 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011098 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011099 MultiExprArg(Args.data(), Args.size()),
11100 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011101}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011102
Sam Panzer0f384432012-08-21 00:52:01 +000011103/// \brief Constructs and populates an OverloadedCandidateSet from
11104/// the given function.
11105/// \returns true when an the ExprResult output parameter has been set.
11106bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11107 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011108 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011109 SourceLocation RParenLoc,
11110 OverloadCandidateSet *CandidateSet,
11111 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011112#ifndef NDEBUG
11113 if (ULE->requiresADL()) {
11114 // To do ADL, we must have found an unqualified name.
11115 assert(!ULE->getQualifier() && "qualified name with ADL");
11116
11117 // We don't perform ADL for implicit declarations of builtins.
11118 // Verify that this was correctly set up.
11119 FunctionDecl *F;
11120 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11121 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11122 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011123 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011124
John McCall57500772009-12-16 12:17:52 +000011125 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011126 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011127 }
John McCall57500772009-12-16 12:17:52 +000011128#endif
11129
John McCall4124c492011-10-17 18:40:02 +000011130 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011131 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011132 *Result = ExprError();
11133 return true;
11134 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011135
John McCall57500772009-12-16 12:17:52 +000011136 // Add the functions denoted by the callee to the set of candidate
11137 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011138 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011139
Hans Wennborgb2747382015-06-12 21:23:23 +000011140 if (getLangOpts().MSVCCompat &&
11141 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011142 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11143
11144 OverloadCandidateSet::iterator Best;
11145 if (CandidateSet->empty() ||
11146 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11147 OR_No_Viable_Function) {
11148 // In Microsoft mode, if we are inside a template class member function then
11149 // create a type dependent CallExpr. The goal is to postpone name lookup
11150 // to instantiation time to be able to search into type dependent base
11151 // classes.
11152 CallExpr *CE = new (Context) CallExpr(
11153 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011154 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011155 CE->setValueDependent(true);
11156 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011157 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011158 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011159 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011160 }
John McCalld681c392009-12-16 08:11:27 +000011161
Hans Wennborg64937c62015-06-11 21:21:57 +000011162 if (CandidateSet->empty())
11163 return false;
11164
John McCall4124c492011-10-17 18:40:02 +000011165 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011166 return false;
11167}
John McCall4124c492011-10-17 18:40:02 +000011168
Sam Panzer0f384432012-08-21 00:52:01 +000011169/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11170/// the completed call expression. If overload resolution fails, emits
11171/// diagnostics and returns ExprError()
11172static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11173 UnresolvedLookupExpr *ULE,
11174 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011175 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011176 SourceLocation RParenLoc,
11177 Expr *ExecConfig,
11178 OverloadCandidateSet *CandidateSet,
11179 OverloadCandidateSet::iterator *Best,
11180 OverloadingResult OverloadResult,
11181 bool AllowTypoCorrection) {
11182 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011183 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011184 RParenLoc, /*EmptyLookup=*/true,
11185 AllowTypoCorrection);
11186
11187 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011188 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011189 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011190 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011191 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11192 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011193 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011194 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11195 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011196 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011197
Richard Smith998a5912011-06-05 22:42:48 +000011198 case OR_No_Viable_Function: {
11199 // Try to recover by looking for viable functions which the user might
11200 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011201 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011202 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011203 /*EmptyLookup=*/false,
11204 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011205 if (!Recovery.isInvalid())
11206 return Recovery;
11207
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011208 // If the user passes in a function that we can't take the address of, we
11209 // generally end up emitting really bad error messages. Here, we attempt to
11210 // emit better ones.
11211 for (const Expr *Arg : Args) {
11212 if (!Arg->getType()->isFunctionType())
11213 continue;
11214 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11215 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11216 if (FD &&
11217 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11218 Arg->getExprLoc()))
11219 return ExprError();
11220 }
11221 }
11222
11223 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11224 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011225 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011226 break;
Richard Smith998a5912011-06-05 22:42:48 +000011227 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011228
11229 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011230 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011231 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011232 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011233 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011234
Sam Panzer0f384432012-08-21 00:52:01 +000011235 case OR_Deleted: {
11236 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11237 << (*Best)->Function->isDeleted()
11238 << ULE->getName()
11239 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11240 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011241 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011242
Sam Panzer0f384432012-08-21 00:52:01 +000011243 // We emitted an error for the unvailable/deleted function call but keep
11244 // the call in the AST.
11245 FunctionDecl *FDecl = (*Best)->Function;
11246 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011247 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11248 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011249 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011250 }
11251
Douglas Gregorb412e172010-07-25 18:17:45 +000011252 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011253 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011254}
11255
George Burgess IV7204ed92016-01-07 02:26:57 +000011256static void markUnaddressableCandidatesUnviable(Sema &S,
11257 OverloadCandidateSet &CS) {
11258 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11259 if (I->Viable &&
11260 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11261 I->Viable = false;
11262 I->FailureKind = ovl_fail_addr_not_available;
11263 }
11264 }
11265}
11266
Sam Panzer0f384432012-08-21 00:52:01 +000011267/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11268/// (which eventually refers to the declaration Func) and the call
11269/// arguments Args/NumArgs, attempt to resolve the function call down
11270/// to a specific function. If overload resolution succeeds, returns
11271/// the call expression produced by overload resolution.
11272/// Otherwise, emits diagnostics and returns ExprError.
11273ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11274 UnresolvedLookupExpr *ULE,
11275 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011276 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011277 SourceLocation RParenLoc,
11278 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011279 bool AllowTypoCorrection,
11280 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011281 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11282 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011283 ExprResult result;
11284
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011285 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11286 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011287 return result;
11288
George Burgess IV7204ed92016-01-07 02:26:57 +000011289 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11290 // functions that aren't addressible are considered unviable.
11291 if (CalleesAddressIsTaken)
11292 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11293
Sam Panzer0f384432012-08-21 00:52:01 +000011294 OverloadCandidateSet::iterator Best;
11295 OverloadingResult OverloadResult =
11296 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11297
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011298 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011299 RParenLoc, ExecConfig, &CandidateSet,
11300 &Best, OverloadResult,
11301 AllowTypoCorrection);
11302}
11303
John McCall4c4c1df2010-01-26 03:27:55 +000011304static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011305 return Functions.size() > 1 ||
11306 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11307}
11308
Douglas Gregor084d8552009-03-13 23:49:33 +000011309/// \brief Create a unary operation that may resolve to an overloaded
11310/// operator.
11311///
11312/// \param OpLoc The location of the operator itself (e.g., '*').
11313///
Craig Toppera92ffb02015-12-10 08:51:49 +000011314/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011315///
James Dennett18348b62012-06-22 08:52:37 +000011316/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011317/// considered by overload resolution. The caller needs to build this
11318/// set based on the context using, e.g.,
11319/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11320/// set should not contain any member functions; those will be added
11321/// by CreateOverloadedUnaryOp().
11322///
James Dennett91738ff2012-06-22 10:32:46 +000011323/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011324ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011325Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011326 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011327 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011328 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11329 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11330 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011331 // TODO: provide better source location info.
11332 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011333
John McCall4124c492011-10-17 18:40:02 +000011334 if (checkPlaceholderForOverload(*this, Input))
11335 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011336
Craig Topperc3ec1492014-05-26 06:22:03 +000011337 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011338 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011339
Douglas Gregor084d8552009-03-13 23:49:33 +000011340 // For post-increment and post-decrement, add the implicit '0' as
11341 // the second argument, so that we know this is a post-increment or
11342 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011343 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011344 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011345 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11346 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011347 NumArgs = 2;
11348 }
11349
Richard Smithe54c3072013-05-05 15:51:06 +000011350 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11351
Douglas Gregor084d8552009-03-13 23:49:33 +000011352 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011353 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011354 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11355 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011356
Craig Topperc3ec1492014-05-26 06:22:03 +000011357 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011358 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011359 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011360 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011361 /*ADL*/ true, IsOverloaded(Fns),
11362 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011363 return new (Context)
11364 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11365 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011366 }
11367
11368 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011369 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011370
11371 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011372 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011373
11374 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011375 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011376
John McCall4c4c1df2010-01-26 03:27:55 +000011377 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011378 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011379 /*ExplicitTemplateArgs*/nullptr,
11380 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011381
Douglas Gregor084d8552009-03-13 23:49:33 +000011382 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011383 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011384
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011385 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11386
Douglas Gregor084d8552009-03-13 23:49:33 +000011387 // Perform overload resolution.
11388 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011389 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011390 case OR_Success: {
11391 // We found a built-in operator or an overloaded operator.
11392 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011393
Douglas Gregor084d8552009-03-13 23:49:33 +000011394 if (FnDecl) {
11395 // We matched an overloaded operator. Build a call to that
11396 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011397
Douglas Gregor084d8552009-03-13 23:49:33 +000011398 // Convert the arguments.
11399 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011400 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011401
John Wiegley01296292011-04-08 18:41:53 +000011402 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011403 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011404 Best->FoundDecl, Method);
11405 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011406 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011407 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011408 } else {
11409 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011410 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011411 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011412 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011413 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011414 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011415 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011416 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011417 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011418 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011419 }
11420
Douglas Gregor084d8552009-03-13 23:49:33 +000011421 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011422 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011423 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011424 if (FnExpr.isInvalid())
11425 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011426
Richard Smithc1564702013-11-15 02:58:23 +000011427 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011428 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011429 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11430 ResultTy = ResultTy.getNonLValueExprType(Context);
11431
Eli Friedman030eee42009-11-18 03:58:17 +000011432 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011433 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011434 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011435 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011436
Alp Toker314cc812014-01-25 16:55:45 +000011437 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011438 return ExprError();
11439
John McCallb268a282010-08-23 23:25:46 +000011440 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011441 } else {
11442 // We matched a built-in operator. Convert the arguments, then
11443 // break out so that we will build the appropriate built-in
11444 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011445 ExprResult InputRes =
11446 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11447 Best->Conversions[0], AA_Passing);
11448 if (InputRes.isInvalid())
11449 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011450 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011451 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011452 }
John Wiegley01296292011-04-08 18:41:53 +000011453 }
11454
11455 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011456 // This is an erroneous use of an operator which can be overloaded by
11457 // a non-member function. Check for non-member operators which were
11458 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011459 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011460 // FIXME: Recover by calling the found function.
11461 return ExprError();
11462
John Wiegley01296292011-04-08 18:41:53 +000011463 // No viable function; fall through to handling this as a
11464 // built-in operator, which will produce an error message for us.
11465 break;
11466
11467 case OR_Ambiguous:
11468 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11469 << UnaryOperator::getOpcodeStr(Opc)
11470 << Input->getType()
11471 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011472 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011473 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11474 return ExprError();
11475
11476 case OR_Deleted:
11477 Diag(OpLoc, diag::err_ovl_deleted_oper)
11478 << Best->Function->isDeleted()
11479 << UnaryOperator::getOpcodeStr(Opc)
11480 << getDeletedOrUnavailableSuffix(Best->Function)
11481 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011483 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011484 return ExprError();
11485 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011486
11487 // Either we found no viable overloaded operator or we matched a
11488 // built-in operator. In either case, fall through to trying to
11489 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011490 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011491}
11492
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011493/// \brief Create a binary operation that may resolve to an overloaded
11494/// operator.
11495///
11496/// \param OpLoc The location of the operator itself (e.g., '+').
11497///
Craig Toppera92ffb02015-12-10 08:51:49 +000011498/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011499///
James Dennett18348b62012-06-22 08:52:37 +000011500/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011501/// considered by overload resolution. The caller needs to build this
11502/// set based on the context using, e.g.,
11503/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11504/// set should not contain any member functions; those will be added
11505/// by CreateOverloadedBinOp().
11506///
11507/// \param LHS Left-hand argument.
11508/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011509ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011510Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011511 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011512 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011513 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011514 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011515 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011516
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011517 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11518 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11519
11520 // If either side is type-dependent, create an appropriate dependent
11521 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011522 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011523 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011524 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011525 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011526 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011527 return new (Context) BinaryOperator(
11528 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11529 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011530
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011531 return new (Context) CompoundAssignOperator(
11532 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11533 Context.DependentTy, Context.DependentTy, OpLoc,
11534 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011535 }
John McCall4c4c1df2010-01-26 03:27:55 +000011536
11537 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011538 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011539 // TODO: provide better source location info in DNLoc component.
11540 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011541 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011542 = UnresolvedLookupExpr::Create(Context, NamingClass,
11543 NestedNameSpecifierLoc(), OpNameInfo,
11544 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011545 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011546 return new (Context)
11547 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11548 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011549 }
11550
John McCall4124c492011-10-17 18:40:02 +000011551 // Always do placeholder-like conversions on the RHS.
11552 if (checkPlaceholderForOverload(*this, Args[1]))
11553 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011554
John McCall526ab472011-10-25 17:37:35 +000011555 // Do placeholder-like conversion on the LHS; note that we should
11556 // not get here with a PseudoObject LHS.
11557 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011558 if (checkPlaceholderForOverload(*this, Args[0]))
11559 return ExprError();
11560
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011561 // If this is the assignment operator, we only perform overload resolution
11562 // if the left-hand side is a class or enumeration type. This is actually
11563 // a hack. The standard requires that we do overload resolution between the
11564 // various built-in candidates, but as DR507 points out, this can lead to
11565 // problems. So we do it this way, which pretty much follows what GCC does.
11566 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011567 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011568 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011569
John McCalle26a8722010-12-04 08:14:53 +000011570 // If this is the .* operator, which is not overloadable, just
11571 // create a built-in binary operator.
11572 if (Opc == BO_PtrMemD)
11573 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11574
Douglas Gregor084d8552009-03-13 23:49:33 +000011575 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011576 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011577
11578 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011579 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011580
11581 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011582 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011583
Richard Smith0daabd72014-09-23 20:31:39 +000011584 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11585 // performed for an assignment operator (nor for operator[] nor operator->,
11586 // which don't get here).
11587 if (Opc != BO_Assign)
11588 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11589 /*ExplicitTemplateArgs*/ nullptr,
11590 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011591
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011592 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011593 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011594
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011595 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11596
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011597 // Perform overload resolution.
11598 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011599 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011600 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011601 // We found a built-in operator or an overloaded operator.
11602 FunctionDecl *FnDecl = Best->Function;
11603
11604 if (FnDecl) {
11605 // We matched an overloaded operator. Build a call to that
11606 // operator.
11607
11608 // Convert the arguments.
11609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011610 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011611 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011612
Chandler Carruth8e543b32010-12-12 08:17:55 +000011613 ExprResult Arg1 =
11614 PerformCopyInitialization(
11615 InitializedEntity::InitializeParameter(Context,
11616 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011617 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011618 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011619 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011620
John Wiegley01296292011-04-08 18:41:53 +000011621 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011622 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011623 Best->FoundDecl, Method);
11624 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011625 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011626 Args[0] = Arg0.getAs<Expr>();
11627 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011628 } else {
11629 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011630 ExprResult Arg0 = PerformCopyInitialization(
11631 InitializedEntity::InitializeParameter(Context,
11632 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011633 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011634 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011635 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011636
Chandler Carruth8e543b32010-12-12 08:17:55 +000011637 ExprResult Arg1 =
11638 PerformCopyInitialization(
11639 InitializedEntity::InitializeParameter(Context,
11640 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011641 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011642 if (Arg1.isInvalid())
11643 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011644 Args[0] = LHS = Arg0.getAs<Expr>();
11645 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011646 }
11647
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011648 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011649 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011650 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011651 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011652 if (FnExpr.isInvalid())
11653 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011654
Richard Smithc1564702013-11-15 02:58:23 +000011655 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011656 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011657 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11658 ResultTy = ResultTy.getNonLValueExprType(Context);
11659
John McCallb268a282010-08-23 23:25:46 +000011660 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011661 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011662 Args, ResultTy, VK, OpLoc,
11663 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011664
Alp Toker314cc812014-01-25 16:55:45 +000011665 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011666 FnDecl))
11667 return ExprError();
11668
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011669 ArrayRef<const Expr *> ArgsArray(Args, 2);
11670 // Cut off the implicit 'this'.
11671 if (isa<CXXMethodDecl>(FnDecl))
11672 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011673
11674 // Check for a self move.
11675 if (Op == OO_Equal)
11676 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11677
Douglas Gregorb4866e82015-06-19 18:13:19 +000011678 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011679 TheCall->getSourceRange(), VariadicDoesNotApply);
11680
John McCallb268a282010-08-23 23:25:46 +000011681 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011682 } else {
11683 // We matched a built-in operator. Convert the arguments, then
11684 // break out so that we will build the appropriate built-in
11685 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011686 ExprResult ArgsRes0 =
11687 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11688 Best->Conversions[0], AA_Passing);
11689 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011690 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011691 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011692
John Wiegley01296292011-04-08 18:41:53 +000011693 ExprResult ArgsRes1 =
11694 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11695 Best->Conversions[1], AA_Passing);
11696 if (ArgsRes1.isInvalid())
11697 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011698 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011699 break;
11700 }
11701 }
11702
Douglas Gregor66950a32009-09-30 21:46:01 +000011703 case OR_No_Viable_Function: {
11704 // C++ [over.match.oper]p9:
11705 // If the operator is the operator , [...] and there are no
11706 // viable functions, then the operator is assumed to be the
11707 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011708 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011709 break;
11710
Chandler Carruth8e543b32010-12-12 08:17:55 +000011711 // For class as left operand for assignment or compound assigment
11712 // operator do not fall through to handling in built-in, but report that
11713 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011714 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011715 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011716 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011717 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11718 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011719 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011720 if (Args[0]->getType()->isIncompleteType()) {
11721 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11722 << Args[0]->getType()
11723 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11724 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011725 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011726 // This is an erroneous use of an operator which can be overloaded by
11727 // a non-member function. Check for non-member operators which were
11728 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011729 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011730 // FIXME: Recover by calling the found function.
11731 return ExprError();
11732
Douglas Gregor66950a32009-09-30 21:46:01 +000011733 // No viable function; try to create a built-in operation, which will
11734 // produce an error. Then, show the non-viable candidates.
11735 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011737 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011738 "C++ binary operator overloading is missing candidates!");
11739 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011740 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011741 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011742 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011743 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011744
11745 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011746 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011747 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011748 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011749 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011750 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011751 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011752 return ExprError();
11753
11754 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011755 if (isImplicitlyDeleted(Best->Function)) {
11756 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11757 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011758 << Context.getRecordType(Method->getParent())
11759 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011760
Richard Smithde1a4872012-12-28 12:23:24 +000011761 // The user probably meant to call this special member. Just
11762 // explain why it's deleted.
11763 NoteDeletedFunction(Method);
11764 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011765 } else {
11766 Diag(OpLoc, diag::err_ovl_deleted_oper)
11767 << Best->Function->isDeleted()
11768 << BinaryOperator::getOpcodeStr(Opc)
11769 << getDeletedOrUnavailableSuffix(Best->Function)
11770 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11771 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011772 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011773 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011774 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011775 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011776
Douglas Gregor66950a32009-09-30 21:46:01 +000011777 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011778 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011779}
11780
John McCalldadc5752010-08-24 06:29:42 +000011781ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011782Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11783 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011784 Expr *Base, Expr *Idx) {
11785 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011786 DeclarationName OpName =
11787 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11788
11789 // If either side is type-dependent, create an appropriate dependent
11790 // expression.
11791 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11792
Craig Topperc3ec1492014-05-26 06:22:03 +000011793 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011794 // CHECKME: no 'operator' keyword?
11795 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11796 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011797 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011798 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011799 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011800 /*ADL*/ true, /*Overloaded*/ false,
11801 UnresolvedSetIterator(),
11802 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011803 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011804
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011805 return new (Context)
11806 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11807 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011808 }
11809
John McCall4124c492011-10-17 18:40:02 +000011810 // Handle placeholders on both operands.
11811 if (checkPlaceholderForOverload(*this, Args[0]))
11812 return ExprError();
11813 if (checkPlaceholderForOverload(*this, Args[1]))
11814 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011815
Sebastian Redladba46e2009-10-29 20:17:01 +000011816 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011817 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011818
11819 // Subscript can only be overloaded as a member function.
11820
11821 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011822 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011823
11824 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011825 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011826
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011827 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11828
Sebastian Redladba46e2009-10-29 20:17:01 +000011829 // Perform overload resolution.
11830 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011831 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011832 case OR_Success: {
11833 // We found a built-in operator or an overloaded operator.
11834 FunctionDecl *FnDecl = Best->Function;
11835
11836 if (FnDecl) {
11837 // We matched an overloaded operator. Build a call to that
11838 // operator.
11839
John McCalla0296f72010-03-19 07:35:19 +000011840 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011841
Sebastian Redladba46e2009-10-29 20:17:01 +000011842 // Convert the arguments.
11843 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011844 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011845 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011846 Best->FoundDecl, Method);
11847 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011848 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011849 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011850
Anders Carlssona68e51e2010-01-29 18:37:50 +000011851 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011852 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011853 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011854 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011855 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011856 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011857 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011858 if (InputInit.isInvalid())
11859 return ExprError();
11860
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011861 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011862
Sebastian Redladba46e2009-10-29 20:17:01 +000011863 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011864 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11865 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011866 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011867 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011868 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011869 OpLocInfo.getLoc(),
11870 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011871 if (FnExpr.isInvalid())
11872 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011873
Richard Smithc1564702013-11-15 02:58:23 +000011874 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011875 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011876 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11877 ResultTy = ResultTy.getNonLValueExprType(Context);
11878
John McCallb268a282010-08-23 23:25:46 +000011879 CXXOperatorCallExpr *TheCall =
11880 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011881 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011882 ResultTy, VK, RLoc,
11883 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011884
Alp Toker314cc812014-01-25 16:55:45 +000011885 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011886 return ExprError();
11887
John McCallb268a282010-08-23 23:25:46 +000011888 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011889 } else {
11890 // We matched a built-in operator. Convert the arguments, then
11891 // break out so that we will build the appropriate built-in
11892 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011893 ExprResult ArgsRes0 =
11894 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11895 Best->Conversions[0], AA_Passing);
11896 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011897 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011898 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011899
11900 ExprResult ArgsRes1 =
11901 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11902 Best->Conversions[1], AA_Passing);
11903 if (ArgsRes1.isInvalid())
11904 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011905 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011906
11907 break;
11908 }
11909 }
11910
11911 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011912 if (CandidateSet.empty())
11913 Diag(LLoc, diag::err_ovl_no_oper)
11914 << Args[0]->getType() << /*subscript*/ 0
11915 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11916 else
11917 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11918 << Args[0]->getType()
11919 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011920 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011921 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011922 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011923 }
11924
11925 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011926 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011927 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011928 << Args[0]->getType() << Args[1]->getType()
11929 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011930 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011931 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011932 return ExprError();
11933
11934 case OR_Deleted:
11935 Diag(LLoc, diag::err_ovl_deleted_oper)
11936 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011937 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011938 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011939 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011940 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011941 return ExprError();
11942 }
11943
11944 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011945 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011946}
11947
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011948/// BuildCallToMemberFunction - Build a call to a member
11949/// function. MemExpr is the expression that refers to the member
11950/// function (and includes the object parameter), Args/NumArgs are the
11951/// arguments to the function call (not including the object
11952/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011953/// expression refers to a non-static member function or an overloaded
11954/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011955ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011956Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011957 SourceLocation LParenLoc,
11958 MultiExprArg Args,
11959 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011960 assert(MemExprE->getType() == Context.BoundMemberTy ||
11961 MemExprE->getType() == Context.OverloadTy);
11962
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011963 // Dig out the member expression. This holds both the object
11964 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011965 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011966
John McCall0009fcc2011-04-26 20:42:42 +000011967 // Determine whether this is a call to a pointer-to-member function.
11968 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11969 assert(op->getType() == Context.BoundMemberTy);
11970 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11971
11972 QualType fnType =
11973 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11974
11975 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11976 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011977 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011978
11979 // Check that the object type isn't more qualified than the
11980 // member function we're calling.
11981 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11982
11983 QualType objectType = op->getLHS()->getType();
11984 if (op->getOpcode() == BO_PtrMemI)
11985 objectType = objectType->castAs<PointerType>()->getPointeeType();
11986 Qualifiers objectQuals = objectType.getQualifiers();
11987
11988 Qualifiers difference = objectQuals - funcQuals;
11989 difference.removeObjCGCAttr();
11990 difference.removeAddressSpace();
11991 if (difference) {
11992 std::string qualsString = difference.getAsString();
11993 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11994 << fnType.getUnqualifiedType()
11995 << qualsString
11996 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11997 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011998
John McCall0009fcc2011-04-26 20:42:42 +000011999 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012000 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012001 resultType, valueKind, RParenLoc);
12002
Alp Toker314cc812014-01-25 16:55:45 +000012003 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012004 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012005 return ExprError();
12006
Craig Topperc3ec1492014-05-26 06:22:03 +000012007 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012008 return ExprError();
12009
Richard Trieu9be9c682013-06-22 02:30:38 +000012010 if (CheckOtherCall(call, proto))
12011 return ExprError();
12012
John McCall0009fcc2011-04-26 20:42:42 +000012013 return MaybeBindToTemporary(call);
12014 }
12015
David Majnemerced8bdf2015-02-25 17:36:15 +000012016 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12017 return new (Context)
12018 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12019
John McCall4124c492011-10-17 18:40:02 +000012020 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012021 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012022 return ExprError();
12023
John McCall10eae182009-11-30 22:42:35 +000012024 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012025 CXXMethodDecl *Method = nullptr;
12026 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12027 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012028 if (isa<MemberExpr>(NakedMemExpr)) {
12029 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012030 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012031 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012032 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012033 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012034 } else {
12035 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012036 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012037
John McCall6e9f8f62009-12-03 04:06:58 +000012038 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012039 Expr::Classification ObjectClassification
12040 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12041 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012042
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012043 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012044 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12045 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012046
John McCall2d74de92009-12-01 22:10:20 +000012047 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012048 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012049 if (UnresExpr->hasExplicitTemplateArgs()) {
12050 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12051 TemplateArgs = &TemplateArgsBuffer;
12052 }
12053
John McCall10eae182009-11-30 22:42:35 +000012054 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12055 E = UnresExpr->decls_end(); I != E; ++I) {
12056
John McCall6e9f8f62009-12-03 04:06:58 +000012057 NamedDecl *Func = *I;
12058 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12059 if (isa<UsingShadowDecl>(Func))
12060 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12061
Douglas Gregor02824322011-01-26 19:30:28 +000012062
Francois Pichet64225792011-01-18 05:04:39 +000012063 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012064 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012065 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012066 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012067 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012068 // If explicit template arguments were provided, we can't call a
12069 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012070 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012071 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012072
John McCalla0296f72010-03-19 07:35:19 +000012073 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012074 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012075 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012076 } else {
John McCall10eae182009-11-30 22:42:35 +000012077 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012078 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012079 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012080 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012081 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012082 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012083 }
Mike Stump11289f42009-09-09 15:08:12 +000012084
John McCall10eae182009-11-30 22:42:35 +000012085 DeclarationName DeclName = UnresExpr->getMemberName();
12086
John McCall4124c492011-10-17 18:40:02 +000012087 UnbridgedCasts.restore();
12088
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012089 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012090 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012091 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012092 case OR_Success:
12093 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012094 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012095 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012096 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12097 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012098 // If FoundDecl is different from Method (such as if one is a template
12099 // and the other a specialization), make sure DiagnoseUseOfDecl is
12100 // called on both.
12101 // FIXME: This would be more comprehensively addressed by modifying
12102 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12103 // being used.
12104 if (Method != FoundDecl.getDecl() &&
12105 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12106 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012107 break;
12108
12109 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012110 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012111 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012112 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012114 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012115 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012116
12117 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012118 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012119 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012120 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012121 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012122 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012123
12124 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012125 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012126 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012127 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012128 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012129 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012130 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012131 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012132 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012133 }
12134
John McCall16df1e52010-03-30 21:47:33 +000012135 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012136
John McCall2d74de92009-12-01 22:10:20 +000012137 // If overload resolution picked a static member, build a
12138 // non-member call based on that function.
12139 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012140 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12141 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012142 }
12143
John McCall10eae182009-11-30 22:42:35 +000012144 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012145 }
12146
Alp Toker314cc812014-01-25 16:55:45 +000012147 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012148 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12149 ResultType = ResultType.getNonLValueExprType(Context);
12150
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012151 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012152 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012153 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012154 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012155
Eli Bendersky291a57e2014-09-25 23:59:08 +000012156 // (CUDA B.1): Check for invalid calls between targets.
12157 if (getLangOpts().CUDA) {
12158 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12159 if (CheckCUDATarget(Caller, Method)) {
12160 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12161 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12162 << IdentifyCUDATarget(Caller);
12163 return ExprError();
12164 }
12165 }
12166 }
12167
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012168 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012169 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012170 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012171 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012172
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012173 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012174 // We only need to do this if there was actually an overload; otherwise
12175 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012176 if (!Method->isStatic()) {
12177 ExprResult ObjectArg =
12178 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12179 FoundDecl, Method);
12180 if (ObjectArg.isInvalid())
12181 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012182 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012183 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012184
12185 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012186 const FunctionProtoType *Proto =
12187 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012188 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012189 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012190 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012191
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012192 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012193
Richard Smith55ce3522012-06-25 20:30:08 +000012194 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012195 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012196
George Burgess IVaea6ade2015-09-25 17:53:16 +000012197 // In the case the method to call was not selected by the overloading
12198 // resolution process, we still need to handle the enable_if attribute. Do
12199 // that here, so it will not hide previous -- and more relevant -- errors
12200 if (isa<MemberExpr>(NakedMemExpr)) {
12201 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12202 Diag(MemExprE->getLocStart(),
12203 diag::err_ovl_no_viable_member_function_in_call)
12204 << Method << Method->getSourceRange();
12205 Diag(Method->getLocation(),
12206 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12207 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12208 return ExprError();
12209 }
12210 }
12211
Anders Carlsson47061ee2011-05-06 14:25:31 +000012212 if ((isa<CXXConstructorDecl>(CurContext) ||
12213 isa<CXXDestructorDecl>(CurContext)) &&
12214 TheCall->getMethodDecl()->isPure()) {
12215 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12216
Davide Italianoccb37382015-07-14 23:36:10 +000012217 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12218 MemExpr->performsVirtualDispatch(getLangOpts())) {
12219 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012220 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12221 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12222 << MD->getParent()->getDeclName();
12223
12224 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012225 if (getLangOpts().AppleKext)
12226 Diag(MemExpr->getLocStart(),
12227 diag::note_pure_qualified_call_kext)
12228 << MD->getParent()->getDeclName()
12229 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012230 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012231 }
John McCallb268a282010-08-23 23:25:46 +000012232 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012233}
12234
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012235/// BuildCallToObjectOfClassType - Build a call to an object of class
12236/// type (C++ [over.call.object]), which can end up invoking an
12237/// overloaded function call operator (@c operator()) or performing a
12238/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012239ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012240Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012241 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012242 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012243 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012244 if (checkPlaceholderForOverload(*this, Obj))
12245 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012246 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012247
12248 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012249 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012250 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012251
Nico Weberb58e51c2014-11-19 05:21:39 +000012252 assert(Object.get()->getType()->isRecordType() &&
12253 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012254 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012255
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012256 // C++ [over.call.object]p1:
12257 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012258 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012259 // candidate functions includes at least the function call
12260 // operators of T. The function call operators of T are obtained by
12261 // ordinary lookup of the name operator() in the context of
12262 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012263 OverloadCandidateSet CandidateSet(LParenLoc,
12264 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012265 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012266
John Wiegley01296292011-04-08 18:41:53 +000012267 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012268 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012269 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012270
John McCall27b18f82009-11-17 02:14:36 +000012271 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12272 LookupQualifiedName(R, Record->getDecl());
12273 R.suppressDiagnostics();
12274
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012275 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012276 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012277 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012278 Object.get()->Classify(Context),
12279 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012280 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012282
Douglas Gregorab7897a2008-11-19 22:57:39 +000012283 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012284 // In addition, for each (non-explicit in C++0x) conversion function
12285 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012286 //
12287 // operator conversion-type-id () cv-qualifier;
12288 //
12289 // where cv-qualifier is the same cv-qualification as, or a
12290 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012291 // denotes the type "pointer to function of (P1,...,Pn) returning
12292 // R", or the type "reference to pointer to function of
12293 // (P1,...,Pn) returning R", or the type "reference to function
12294 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012295 // is also considered as a candidate function. Similarly,
12296 // surrogate call functions are added to the set of candidate
12297 // functions for each conversion function declared in an
12298 // accessible base class provided the function is not hidden
12299 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012300 const auto &Conversions =
12301 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12302 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012303 NamedDecl *D = *I;
12304 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12305 if (isa<UsingShadowDecl>(D))
12306 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012307
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012308 // Skip over templated conversion functions; they aren't
12309 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012310 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012311 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012312
John McCall6e9f8f62009-12-03 04:06:58 +000012313 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012314 if (!Conv->isExplicit()) {
12315 // Strip the reference type (if any) and then the pointer type (if
12316 // any) to get down to what might be a function type.
12317 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12318 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12319 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012320
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012321 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12322 {
12323 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012324 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012325 }
12326 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012327 }
Mike Stump11289f42009-09-09 15:08:12 +000012328
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012329 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12330
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012331 // Perform overload resolution.
12332 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012333 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012334 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012335 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012336 // Overload resolution succeeded; we'll build the appropriate call
12337 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012338 break;
12339
12340 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012341 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012342 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012343 << Object.get()->getType() << /*call*/ 1
12344 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012345 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012346 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012347 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012348 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012349 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012350 break;
12351
12352 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012353 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012354 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012355 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012356 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012357 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012358
12359 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012360 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012361 diag::err_ovl_deleted_object_call)
12362 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012363 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012364 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012365 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012366 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012367 break;
Mike Stump11289f42009-09-09 15:08:12 +000012368 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012369
Douglas Gregorb412e172010-07-25 18:17:45 +000012370 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012371 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012372
John McCall4124c492011-10-17 18:40:02 +000012373 UnbridgedCasts.restore();
12374
Craig Topperc3ec1492014-05-26 06:22:03 +000012375 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012376 // Since there is no function declaration, this is one of the
12377 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012378 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012379 = cast<CXXConversionDecl>(
12380 Best->Conversions[0].UserDefined.ConversionFunction);
12381
Craig Topperc3ec1492014-05-26 06:22:03 +000012382 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12383 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012384 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12385 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012386 assert(Conv == Best->FoundDecl.getDecl() &&
12387 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012388 // We selected one of the surrogate functions that converts the
12389 // object parameter to a function pointer. Perform the conversion
12390 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012391
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012392 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012393 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012394 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12395 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012396 if (Call.isInvalid())
12397 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012398 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012399 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12400 CK_UserDefinedConversion, Call.get(),
12401 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012402
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012403 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012404 }
12405
Craig Topperc3ec1492014-05-26 06:22:03 +000012406 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012407
Douglas Gregorab7897a2008-11-19 22:57:39 +000012408 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12409 // that calls this method, using Object for the implicit object
12410 // parameter and passing along the remaining arguments.
12411 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012412
12413 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012414 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012415 return ExprError();
12416
Chandler Carruth8e543b32010-12-12 08:17:55 +000012417 const FunctionProtoType *Proto =
12418 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012419
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012420 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012421
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012422 DeclarationNameInfo OpLocInfo(
12423 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12424 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012425 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012426 HadMultipleCandidates,
12427 OpLocInfo.getLoc(),
12428 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012429 if (NewFn.isInvalid())
12430 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012431
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012432 // Build the full argument list for the method call (the implicit object
12433 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012434 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012435 MethodArgs[0] = Object.get();
12436 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12437
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012438 // Once we've built TheCall, all of the expressions are properly
12439 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012440 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012441 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12442 ResultTy = ResultTy.getNonLValueExprType(Context);
12443
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012444 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012445 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012446 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12447 ResultTy, VK, RParenLoc, false);
12448 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012449
Alp Toker314cc812014-01-25 16:55:45 +000012450 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012451 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012452
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012453 // We may have default arguments. If so, we need to allocate more
12454 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012455 if (Args.size() < NumParams)
12456 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012457
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012458 bool IsError = false;
12459
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012460 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012461 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012462 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012463 Best->FoundDecl, Method);
12464 if (ObjRes.isInvalid())
12465 IsError = true;
12466 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012467 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012468 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012469
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012470 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012471 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012472 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012473 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012474 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012475
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012476 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012477
John McCalldadc5752010-08-24 06:29:42 +000012478 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012479 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012480 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012481 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012482 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012483
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012484 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012485 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012486 } else {
John McCalldadc5752010-08-24 06:29:42 +000012487 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012488 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12489 if (DefArg.isInvalid()) {
12490 IsError = true;
12491 break;
12492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012493
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012494 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012495 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012496
12497 TheCall->setArg(i + 1, Arg);
12498 }
12499
12500 // If this is a variadic call, handle args passed through "...".
12501 if (Proto->isVariadic()) {
12502 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012503 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012504 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12505 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012506 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012507 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012508 }
12509 }
12510
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012511 if (IsError) return true;
12512
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012513 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012514
Richard Smith55ce3522012-06-25 20:30:08 +000012515 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012516 return true;
12517
John McCalle172be52010-08-24 06:09:16 +000012518 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012519}
12520
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012521/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012522/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012523/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012524ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012525Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12526 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012527 assert(Base->getType()->isRecordType() &&
12528 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012529
John McCall4124c492011-10-17 18:40:02 +000012530 if (checkPlaceholderForOverload(*this, Base))
12531 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012532
John McCallbc077cf2010-02-08 23:07:23 +000012533 SourceLocation Loc = Base->getExprLoc();
12534
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012535 // C++ [over.ref]p1:
12536 //
12537 // [...] An expression x->m is interpreted as (x.operator->())->m
12538 // for a class object x of type T if T::operator->() exists and if
12539 // the operator is selected as the best match function by the
12540 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012541 DeclarationName OpName =
12542 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012543 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012544 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012545
John McCallbc077cf2010-02-08 23:07:23 +000012546 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012547 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012548 return ExprError();
12549
John McCall27b18f82009-11-17 02:14:36 +000012550 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12551 LookupQualifiedName(R, BaseRecord->getDecl());
12552 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012553
12554 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012555 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012556 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012557 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012558 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012559
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012560 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12561
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012562 // Perform overload resolution.
12563 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012564 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012565 case OR_Success:
12566 // Overload resolution succeeded; we'll build the call below.
12567 break;
12568
12569 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012570 if (CandidateSet.empty()) {
12571 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012572 if (NoArrowOperatorFound) {
12573 // Report this specific error to the caller instead of emitting a
12574 // diagnostic, as requested.
12575 *NoArrowOperatorFound = true;
12576 return ExprError();
12577 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012578 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12579 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012580 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012581 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012582 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012583 }
12584 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012585 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012586 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012588 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012589
12590 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012591 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12592 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012593 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012594 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012595
12596 case OR_Deleted:
12597 Diag(OpLoc, diag::err_ovl_deleted_oper)
12598 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012599 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012600 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012601 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012602 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012603 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012604 }
12605
Craig Topperc3ec1492014-05-26 06:22:03 +000012606 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012607
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012608 // Convert the object parameter.
12609 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012610 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012611 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012612 Best->FoundDecl, Method);
12613 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012614 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012615 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012616
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012617 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012618 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012619 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012620 if (FnExpr.isInvalid())
12621 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012622
Alp Toker314cc812014-01-25 16:55:45 +000012623 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012624 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12625 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012626 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012627 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012628 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012629
Alp Toker314cc812014-01-25 16:55:45 +000012630 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012631 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012632
12633 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012634}
12635
Richard Smithbcc22fc2012-03-09 08:00:36 +000012636/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12637/// a literal operator described by the provided lookup results.
12638ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12639 DeclarationNameInfo &SuffixInfo,
12640 ArrayRef<Expr*> Args,
12641 SourceLocation LitEndLoc,
12642 TemplateArgumentListInfo *TemplateArgs) {
12643 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012644
Richard Smith100b24a2014-04-17 01:52:14 +000012645 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12646 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012647 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12648 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012649
Richard Smithbcc22fc2012-03-09 08:00:36 +000012650 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12651
Richard Smithbcc22fc2012-03-09 08:00:36 +000012652 // Perform overload resolution. This will usually be trivial, but might need
12653 // to perform substitutions for a literal operator template.
12654 OverloadCandidateSet::iterator Best;
12655 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12656 case OR_Success:
12657 case OR_Deleted:
12658 break;
12659
12660 case OR_No_Viable_Function:
12661 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12662 << R.getLookupName();
12663 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12664 return ExprError();
12665
12666 case OR_Ambiguous:
12667 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12668 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12669 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012670 }
12671
Richard Smithbcc22fc2012-03-09 08:00:36 +000012672 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012673 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12674 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012675 SuffixInfo.getLoc(),
12676 SuffixInfo.getInfo());
12677 if (Fn.isInvalid())
12678 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012679
12680 // Check the argument types. This should almost always be a no-op, except
12681 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012682 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012683 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012684 ExprResult InputInit = PerformCopyInitialization(
12685 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12686 SourceLocation(), Args[ArgIdx]);
12687 if (InputInit.isInvalid())
12688 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012689 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012690 }
12691
Alp Toker314cc812014-01-25 16:55:45 +000012692 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012693 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12694 ResultTy = ResultTy.getNonLValueExprType(Context);
12695
Richard Smithc67fdd42012-03-07 08:35:16 +000012696 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012697 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012698 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012699 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12700
Alp Toker314cc812014-01-25 16:55:45 +000012701 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012702 return ExprError();
12703
Craig Topperc3ec1492014-05-26 06:22:03 +000012704 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012705 return ExprError();
12706
12707 return MaybeBindToTemporary(UDL);
12708}
12709
Sam Panzer0f384432012-08-21 00:52:01 +000012710/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12711/// given LookupResult is non-empty, it is assumed to describe a member which
12712/// will be invoked. Otherwise, the function will be found via argument
12713/// dependent lookup.
12714/// CallExpr is set to a valid expression and FRS_Success returned on success,
12715/// otherwise CallExpr is set to ExprError() and some non-success value
12716/// is returned.
12717Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012718Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12719 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012720 const DeclarationNameInfo &NameInfo,
12721 LookupResult &MemberLookup,
12722 OverloadCandidateSet *CandidateSet,
12723 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012724 Scope *S = nullptr;
12725
Sam Panzer0f384432012-08-21 00:52:01 +000012726 CandidateSet->clear();
12727 if (!MemberLookup.empty()) {
12728 ExprResult MemberRef =
12729 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12730 /*IsPtr=*/false, CXXScopeSpec(),
12731 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012732 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012733 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012734 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012735 if (MemberRef.isInvalid()) {
12736 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012737 return FRS_DiagnosticIssued;
12738 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012739 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012740 if (CallExpr->isInvalid()) {
12741 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012742 return FRS_DiagnosticIssued;
12743 }
12744 } else {
12745 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012746 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012747 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012748 NestedNameSpecifierLoc(), NameInfo,
12749 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012750 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012751
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012752 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012753 CandidateSet, CallExpr);
12754 if (CandidateSet->empty() || CandidateSetError) {
12755 *CallExpr = ExprError();
12756 return FRS_NoViableFunction;
12757 }
12758 OverloadCandidateSet::iterator Best;
12759 OverloadingResult OverloadResult =
12760 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12761
12762 if (OverloadResult == OR_No_Viable_Function) {
12763 *CallExpr = ExprError();
12764 return FRS_NoViableFunction;
12765 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012766 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012767 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012768 OverloadResult,
12769 /*AllowTypoCorrection=*/false);
12770 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12771 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012772 return FRS_DiagnosticIssued;
12773 }
12774 }
12775 return FRS_Success;
12776}
12777
12778
Douglas Gregorcd695e52008-11-10 20:40:00 +000012779/// FixOverloadedFunctionReference - E is an expression that refers to
12780/// a C++ overloaded function (possibly with some parentheses and
12781/// perhaps a '&' around it). We have resolved the overloaded function
12782/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012783/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012784Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012785 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012786 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012787 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12788 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012789 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012790 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012791
Douglas Gregor51c538b2009-11-20 19:42:02 +000012792 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012793 }
12794
Douglas Gregor51c538b2009-11-20 19:42:02 +000012795 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012796 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12797 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012798 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012799 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012800 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012801 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012802 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012803 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012804
12805 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012806 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012807 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012808 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012809 }
12810
Douglas Gregor51c538b2009-11-20 19:42:02 +000012811 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012812 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012813 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12815 if (Method->isStatic()) {
12816 // Do nothing: static member functions aren't any different
12817 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012818 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012819 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012820 // UnresolvedLookupExpr holding an overloaded member function
12821 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012822 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12823 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012824 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012825 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012826
John McCalld14a8642009-11-21 08:51:07 +000012827 assert(isa<DeclRefExpr>(SubExpr)
12828 && "fixed to something other than a decl ref");
12829 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12830 && "fixed to a member ref with no nested name qualifier");
12831
12832 // We have taken the address of a pointer to member
12833 // function. Perform the computation here so that we get the
12834 // appropriate pointer to member type.
12835 QualType ClassType
12836 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12837 QualType MemPtrType
12838 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12839
John McCall7decc9e2010-11-18 06:31:45 +000012840 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12841 VK_RValue, OK_Ordinary,
12842 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012843 }
12844 }
John McCall16df1e52010-03-30 21:47:33 +000012845 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12846 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012847 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012848 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012849
John McCalle3027922010-08-25 11:45:40 +000012850 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012851 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012852 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012853 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012854 }
John McCalld14a8642009-11-21 08:51:07 +000012855
12856 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012857 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012858 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012859 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012860 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12861 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012862 }
12863
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012864 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12865 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012866 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012867 Fn,
John McCall113bee02012-03-10 09:33:50 +000012868 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012869 ULE->getNameLoc(),
12870 Fn->getType(),
12871 VK_LValue,
12872 Found.getDecl(),
12873 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012874 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012875 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12876 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012877 }
12878
John McCall10eae182009-11-30 22:42:35 +000012879 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012880 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012881 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012882 if (MemExpr->hasExplicitTemplateArgs()) {
12883 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12884 TemplateArgs = &TemplateArgsBuffer;
12885 }
John McCall6b51f282009-11-23 01:53:49 +000012886
John McCall2d74de92009-12-01 22:10:20 +000012887 Expr *Base;
12888
John McCall7decc9e2010-11-18 06:31:45 +000012889 // If we're filling in a static method where we used to have an
12890 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012891 if (MemExpr->isImplicitAccess()) {
12892 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012893 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12894 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012895 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012896 Fn,
John McCall113bee02012-03-10 09:33:50 +000012897 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012898 MemExpr->getMemberLoc(),
12899 Fn->getType(),
12900 VK_LValue,
12901 Found.getDecl(),
12902 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012903 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012904 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12905 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012906 } else {
12907 SourceLocation Loc = MemExpr->getMemberLoc();
12908 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012909 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012910 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012911 Base = new (Context) CXXThisExpr(Loc,
12912 MemExpr->getBaseType(),
12913 /*isImplicit=*/true);
12914 }
John McCall2d74de92009-12-01 22:10:20 +000012915 } else
John McCallc3007a22010-10-26 07:05:15 +000012916 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012917
John McCall4adb38c2011-04-27 00:36:17 +000012918 ExprValueKind valueKind;
12919 QualType type;
12920 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12921 valueKind = VK_LValue;
12922 type = Fn->getType();
12923 } else {
12924 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012925 type = Context.BoundMemberTy;
12926 }
12927
12928 MemberExpr *ME = MemberExpr::Create(
12929 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12930 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12931 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12932 OK_Ordinary);
12933 ME->setHadMultipleCandidates(true);
12934 MarkMemberReferenced(ME);
12935 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012937
John McCallc3007a22010-10-26 07:05:15 +000012938 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012939}
12940
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012941ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012942 DeclAccessPair Found,
12943 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012944 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012945}