blob: cf7fb557a756715e2b92ee34e93bf6d87a43ec28 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
Nick Lewycky134af912013-02-07 05:08:22 +000046/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000047static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000048CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000050 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000052 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000053 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000061 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000062 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000066
67 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000068 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000070}
71
John McCall5c32be02010-08-24 20:38:10 +000072static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000074 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000075 bool CStyle,
76 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000077
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000078static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000083static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000087 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000089
90
91static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000092CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000093 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000102CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000108ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 };
140 return Rank[(int)Kind];
141}
142
143/// GetImplicitConversionName - Return the name of this kind of
144/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000145static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000151 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000155 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Integral conversion",
157 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000162 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000163 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000167 "Complex-real conversion",
168 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000169 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000184 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000185 ReferenceBinding = false;
186 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000191 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000192 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000193}
194
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195/// getRank - Retrieve the rank of this standard conversion sequence
196/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197/// implicit conversions.
198ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207}
208
209/// isPointerConversionToBool - Determines whether this conversion is
210/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000211/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000213bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000218 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000222 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227}
228
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229/// isPointerConversionToVoidPointer - Determines whether this
230/// conversion is a conversion of a pointer to a void pointer. This is
231/// used as part of the ranking of standard conversion sequences (C++
232/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000233bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000235isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000236 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000237 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250}
251
Richard Smith66e05fe2012-01-18 05:21:49 +0000252/// Skip any implicit casts which could be either part of a narrowing conversion
253/// or after one in an implicit conversion.
254static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000261 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274}
275
276/// Check if this standard conversion sequence represents a narrowing
277/// conversion, according to C++11 [dcl.init.list]p7.
278///
279/// \param Ctx The AST context.
280/// \param Converted The result of applying this standard conversion sequence.
281/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000283/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000285NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000286StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000288 APValue &ConstantValue,
289 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
296 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000297 // 'bool' is an integral type; dispatch to the right place to handle it.
298 case ICK_Boolean_Conversion:
299 if (FromType->isRealFloatingType())
300 goto FloatingIntegralConversion;
301 if (FromType->isIntegralOrUnscopedEnumerationType())
302 goto IntegralConversion;
303 // Boolean conversions can be from pointers and pointers to members
304 // [conv.bool], and those aren't considered narrowing conversions.
305 return NK_Not_Narrowing;
306
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000314 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000315 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
316 return NK_Type_Narrowing;
317 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
318 llvm::APSInt IntConstantValue;
319 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
320 if (Initializer &&
321 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
322 // Convert the integer to the floating type.
323 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
324 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
325 llvm::APFloat::rmNearestTiesToEven);
326 // And back.
327 llvm::APSInt ConvertedValue = IntConstantValue;
328 bool ignored;
329 Result.convertToInteger(ConvertedValue,
330 llvm::APFloat::rmTowardZero, &ignored);
331 // If the resulting value is different, this was a narrowing conversion.
332 if (IntConstantValue != ConvertedValue) {
333 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000334 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000335 return NK_Constant_Narrowing;
336 }
337 } else {
338 // Variables are always narrowings.
339 return NK_Variable_Narrowing;
340 }
341 }
342 return NK_Not_Narrowing;
343
344 // -- from long double to double or float, or from double to float, except
345 // where the source is a constant expression and the actual value after
346 // conversion is within the range of values that can be represented (even
347 // if it cannot be represented exactly), or
348 case ICK_Floating_Conversion:
349 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
350 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
351 // FromType is larger than ToType.
352 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
353 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
354 // Constant!
355 assert(ConstantValue.isFloat());
356 llvm::APFloat FloatVal = ConstantValue.getFloat();
357 // Convert the source value into the target type.
358 bool ignored;
359 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
360 Ctx.getFloatTypeSemantics(ToType),
361 llvm::APFloat::rmNearestTiesToEven, &ignored);
362 // If there was no overflow, the source value is within the range of
363 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000364 if (ConvertStatus & llvm::APFloat::opOverflow) {
365 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000367 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000368 } else {
369 return NK_Variable_Narrowing;
370 }
371 }
372 return NK_Not_Narrowing;
373
374 // -- from an integer type or unscoped enumeration type to an integer type
375 // that cannot represent all the values of the original type, except where
376 // the source is a constant expression and the actual value after
377 // conversion will fit into the target type and will produce the original
378 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000379 case ICK_Integral_Conversion:
380 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000381 assert(FromType->isIntegralOrUnscopedEnumerationType());
382 assert(ToType->isIntegralOrUnscopedEnumerationType());
383 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
384 const unsigned FromWidth = Ctx.getIntWidth(FromType);
385 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
386 const unsigned ToWidth = Ctx.getIntWidth(ToType);
387
388 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000389 (FromWidth == ToWidth && FromSigned != ToSigned) ||
390 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Not all values of FromType can be represented in ToType.
392 llvm::APSInt InitializerValue;
393 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000394 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
395 // Such conversions on variables are always narrowing.
396 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000397 }
398 bool Narrowing = false;
399 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000400 // Negative -> unsigned is narrowing. Otherwise, more bits is never
401 // narrowing.
402 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000403 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000404 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000405 // Add a bit to the InitializerValue so we don't have to worry about
406 // signed vs. unsigned comparisons.
407 InitializerValue = InitializerValue.extend(
408 InitializerValue.getBitWidth() + 1);
409 // Convert the initializer to and from the target width and signed-ness.
410 llvm::APSInt ConvertedValue = InitializerValue;
411 ConvertedValue = ConvertedValue.trunc(ToWidth);
412 ConvertedValue.setIsSigned(ToSigned);
413 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
414 ConvertedValue.setIsSigned(InitializerValue.isSigned());
415 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 if (ConvertedValue != InitializerValue)
417 Narrowing = true;
418 }
419 if (Narrowing) {
420 ConstantType = Initializer->getType();
421 ConstantValue = APValue(InitializerValue);
422 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000423 }
424 }
425 return NK_Not_Narrowing;
426 }
427
428 default:
429 // Other kinds of conversions are not narrowings.
430 return NK_Not_Narrowing;
431 }
432}
433
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000434/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000435/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000436LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438 bool PrintedSomething = false;
439 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 PrintedSomething = true;
442 }
443
444 if (Second != ICK_Identity) {
445 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449
450 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (Third != ICK_Identity) {
461 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 }
471}
472
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000475void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000478 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000481 if (ConversionFunction)
482 OS << '\'' << *ConversionFunction << '\'';
483 else
484 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000487 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 }
489}
490
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000491/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000493void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000495 if (isStdInitializerListElement())
496 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 switch (ConversionKind) {
498 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 break;
502 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000504 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 break;
506 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 break;
John McCall0d1da222010-01-12 00:44:57 +0000509 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000510 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000511 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 break;
515 }
516
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518}
519
John McCall0d1da222010-01-12 00:44:57 +0000520void AmbiguousConversionSequence::construct() {
521 new (&conversions()) ConversionSet();
522}
523
524void AmbiguousConversionSequence::destruct() {
525 conversions().~ConversionSet();
526}
527
528void
529AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
530 FromTypePtr = O.FromTypePtr;
531 ToTypePtr = O.ToTypePtr;
532 new (&conversions()) ConversionSet(O.conversions());
533}
534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000536 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 // template argument information.
538 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000539 TemplateArgument FirstArg;
540 TemplateArgument SecondArg;
541 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000542 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000543 // template parameter and template argument information.
544 struct DFIParamWithArguments : DFIArguments {
545 TemplateParameter Param;
546 };
Richard Smith9b534542015-12-31 02:02:54 +0000547 // Structure used by DeductionFailureInfo to store template argument
548 // information and the index of the problematic call argument.
549 struct DFIDeducedMismatchArgs : DFIArguments {
550 TemplateArgumentList *TemplateArgs;
551 unsigned CallArgIndex;
552 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000557DeductionFailureInfo
558clang::MakeDeductionFailureInfo(ASTContext &Context,
559 Sema::TemplateDeductionResult TDK,
560 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000563 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 switch (TDK) {
565 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000566 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000568 case Sema::TDK_TooManyArguments:
569 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000570 case Sema::TDK_MiscellaneousDeductionFailure:
571 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000575 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = Info.Param.getOpaqueValue();
577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Richard Smith9b534542015-12-31 02:02:54 +0000579 case Sema::TDK_DeducedMismatch: {
580 // FIXME: Should allocate from normal heap so that we can free this later.
581 auto *Saved = new (Context) DFIDeducedMismatchArgs;
582 Saved->FirstArg = Info.FirstArg;
583 Saved->SecondArg = Info.SecondArg;
584 Saved->TemplateArgs = Info.take();
585 Saved->CallArgIndex = Info.CallArgIndex;
586 Result.Data = Saved;
587 break;
588 }
589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000625 return Result;
626}
John McCall0d1da222010-01-12 00:44:57 +0000627
Larisse Voufo98b20f12013-07-19 23:00:19 +0000628void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000642 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000643 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000644 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000647
648 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000649 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000650 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
652 Diag->~PartialDiagnosticAt();
653 HasDiagnostic = false;
654 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000658 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 break;
660 }
661}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Larisse Voufo98b20f12013-07-19 23:00:19 +0000663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000666 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000667}
668
Larisse Voufo98b20f12013-07-19 23:00:19 +0000669TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
671 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000672 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000674 case Sema::TDK_TooManyArguments:
675 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000676 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000677 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Larisse Voufo98b20f12013-07-19 23:00:19 +0000698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
705 case Sema::TDK_Incomplete:
706 case Sema::TDK_InvalidExplicitArguments:
707 case Sema::TDK_Inconsistent:
708 case Sema::TDK_Underqualified:
709 case Sema::TDK_NonDeducedMismatch:
710 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000712
Richard Smith9b534542015-12-31 02:02:54 +0000713 case Sema::TDK_DeducedMismatch:
714 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
715
Richard Smith44ecdbd2013-01-31 05:19:49 +0000716 case Sema::TDK_SubstitutionFailure:
717 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718
Richard Smith44ecdbd2013-01-31 05:19:49 +0000719 // Unhandled
720 case Sema::TDK_MiscellaneousDeductionFailure:
721 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000722 }
723
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000725}
726
Larisse Voufo98b20f12013-07-19 23:00:19 +0000727const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
729 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000730 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_InstantiationDepth:
732 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000733 case Sema::TDK_TooManyArguments:
734 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000735 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000736 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000737 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000738 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000741 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000742 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000743 case Sema::TDK_NonDeducedMismatch:
744 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745
Douglas Gregor461761d2010-05-08 18:20:53 +0000746 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 break;
749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750
Craig Topperc3ec1492014-05-26 06:22:03 +0000751 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000753
Larisse Voufo98b20f12013-07-19 23:00:19 +0000754const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
756 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000757 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000758 case Sema::TDK_InstantiationDepth:
759 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000760 case Sema::TDK_TooManyArguments:
761 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000762 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000763 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000764 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000765 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000768 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000769 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_NonDeducedMismatch:
771 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772
Douglas Gregor461761d2010-05-08 18:20:53 +0000773 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000774 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 break;
776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Craig Topperc3ec1492014-05-26 06:22:03 +0000778 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779}
780
Larisse Voufo98b20f12013-07-19 23:00:19 +0000781Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000782 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
783 Sema::TDK_FailedOverloadResolution)
784 return static_cast<Expr*>(Data);
785
Craig Topperc3ec1492014-05-26 06:22:03 +0000786 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000787}
788
Richard Smith9b534542015-12-31 02:02:54 +0000789llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
790 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
791 Sema::TDK_DeducedMismatch)
792 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
793
794 return llvm::None;
795}
796
Benjamin Kramer97e59492012-10-09 15:52:25 +0000797void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000798 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000799 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
800 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000801 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
802 i->DeductionFailure.Destroy();
803 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000804}
805
806void OverloadCandidateSet::clear() {
807 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000808 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000809 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000810 Functions.clear();
811}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
John McCall4124c492011-10-17 18:40:02 +0000813namespace {
814 class UnbridgedCastsSet {
815 struct Entry {
816 Expr **Addr;
817 Expr *Saved;
818 };
819 SmallVector<Entry, 2> Entries;
820
821 public:
822 void save(Sema &S, Expr *&E) {
823 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
824 Entry entry = { &E, E };
825 Entries.push_back(entry);
826 E = S.stripARCUnbridgedCast(E);
827 }
828
829 void restore() {
830 for (SmallVectorImpl<Entry>::iterator
831 i = Entries.begin(), e = Entries.end(); i != e; ++i)
832 *i->Addr = i->Saved;
833 }
834 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000835}
John McCall4124c492011-10-17 18:40:02 +0000836
837/// checkPlaceholderForOverload - Do any interesting placeholder-like
838/// preprocessing on the given expression.
839///
840/// \param unbridgedCasts a collection to which to add unbridged casts;
841/// without this, they will be immediately diagnosed as errors
842///
843/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000844static bool
845checkPlaceholderForOverload(Sema &S, Expr *&E,
846 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000847 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
848 // We can't handle overloaded expressions here because overload
849 // resolution might reasonably tweak them.
850 if (placeholder->getKind() == BuiltinType::Overload) return false;
851
852 // If the context potentially accepts unbridged ARC casts, strip
853 // the unbridged cast and add it to the collection for later restoration.
854 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
855 unbridgedCasts) {
856 unbridgedCasts->save(S, E);
857 return false;
858 }
859
860 // Go ahead and check everything else.
861 ExprResult result = S.CheckPlaceholderExpr(E);
862 if (result.isInvalid())
863 return true;
864
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000865 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000866 return false;
867 }
868
869 // Nothing to do.
870 return false;
871}
872
873/// checkArgPlaceholdersForOverload - Check a set of call operands for
874/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000875static bool checkArgPlaceholdersForOverload(Sema &S,
876 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000877 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000878 for (unsigned i = 0, e = Args.size(); i != e; ++i)
879 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000880 return true;
881
882 return false;
883}
884
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000886// overload of the declarations in Old. This routine returns false if
887// New and Old cannot be overloaded, e.g., if New has the same
888// signature as some function in Old (C++ 1.3.10) or if the Old
889// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000890// it does return false, MatchedDecl will point to the decl that New
891// cannot be overloaded with. This decl may be a UsingShadowDecl on
892// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000893//
894// Example: Given the following input:
895//
896// void f(int, float); // #1
897// void f(int, int); // #2
898// int f(int, int); // #3
899//
900// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000901// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000902//
John McCall3d988d92009-12-02 08:47:38 +0000903// When we process #2, Old contains only the FunctionDecl for #1. By
904// comparing the parameter types, we see that #1 and #2 are overloaded
905// (since they have different signatures), so this routine returns
906// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000907//
John McCall3d988d92009-12-02 08:47:38 +0000908// When we process #3, Old is an overload set containing #1 and #2. We
909// compare the signatures of #3 to #1 (they're overloaded, so we do
910// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
911// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912// signature), IsOverload returns false and MatchedDecl will be set to
913// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000914//
915// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
916// into a class by a using declaration. The rules for whether to hide
917// shadow declarations ignore some properties which otherwise figure
918// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000919Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000920Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
921 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000922 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000923 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000924 NamedDecl *OldD = *I;
925
926 bool OldIsUsingDecl = false;
927 if (isa<UsingShadowDecl>(OldD)) {
928 OldIsUsingDecl = true;
929
930 // We can always introduce two using declarations into the same
931 // context, even if they have identical signatures.
932 if (NewIsUsingDecl) continue;
933
934 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
935 }
936
Richard Smithf091e122015-09-15 01:28:55 +0000937 // A using-declaration does not conflict with another declaration
938 // if one of them is hidden.
939 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
940 continue;
941
John McCalle9cccd82010-06-16 08:42:20 +0000942 // If either declaration was introduced by a using declaration,
943 // we'll need to use slightly different rules for matching.
944 // Essentially, these rules are the normal rules, except that
945 // function templates hide function templates with different
946 // return types or template parameter lists.
947 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000948 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
949 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000950
Alp Tokera2794f92014-01-22 07:29:52 +0000951 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000952 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
953 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
954 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
955 continue;
956 }
957
Alp Tokera2794f92014-01-22 07:29:52 +0000958 if (!isa<FunctionTemplateDecl>(OldD) &&
959 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000960 continue;
961
John McCalldaa3d6b2009-12-09 03:35:25 +0000962 Match = *I;
963 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000964 }
John McCalla8987a2942010-11-10 03:01:53 +0000965 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000966 // We can overload with these, which can show up when doing
967 // redeclaration checks for UsingDecls.
968 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000969 } else if (isa<TagDecl>(OldD)) {
970 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000971 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
972 // Optimistically assume that an unresolved using decl will
973 // overload; if it doesn't, we'll have to diagnose during
974 // template instantiation.
975 } else {
John McCall1f82f242009-11-18 22:49:29 +0000976 // (C++ 13p1):
977 // Only function declarations can be overloaded; object and type
978 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000979 Match = *I;
980 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000981 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000982 }
John McCall1f82f242009-11-18 22:49:29 +0000983
John McCalldaa3d6b2009-12-09 03:35:25 +0000984 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000985}
986
Richard Smithac974a32013-06-30 09:48:50 +0000987bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
988 bool UseUsingDeclRules) {
989 // C++ [basic.start.main]p2: This function shall not be overloaded.
990 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000991 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000992
David Majnemerc729b0b2013-09-16 22:44:20 +0000993 // MSVCRT user defined entry points cannot be overloaded.
994 if (New->isMSVCRTEntryPoint())
995 return false;
996
John McCall1f82f242009-11-18 22:49:29 +0000997 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
998 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
999
1000 // C++ [temp.fct]p2:
1001 // A function template can be overloaded with other function templates
1002 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001003 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001004 return true;
1005
1006 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001007 QualType OldQType = Context.getCanonicalType(Old->getType());
1008 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001009
1010 // Compare the signatures (C++ 1.3.10) of the two functions to
1011 // determine whether they are overloads. If we find any mismatch
1012 // in the signature, they are overloads.
1013
1014 // If either of these functions is a K&R-style function (no
1015 // prototype), then we consider them to have matching signatures.
1016 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1017 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1018 return false;
1019
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001020 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1021 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001022
1023 // The signature of a function includes the types of its
1024 // parameters (C++ 1.3.10), which includes the presence or absence
1025 // of the ellipsis; see C++ DR 357).
1026 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001027 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001028 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001029 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001030 return true;
1031
1032 // C++ [temp.over.link]p4:
1033 // The signature of a function template consists of its function
1034 // signature, its return type and its template parameter list. The names
1035 // of the template parameters are significant only for establishing the
1036 // relationship between the template parameters and the rest of the
1037 // signature.
1038 //
1039 // We check the return type and template parameter lists for function
1040 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001041 //
1042 // However, we don't consider either of these when deciding whether
1043 // a member introduced by a shadow declaration is hidden.
1044 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001045 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1046 OldTemplate->getTemplateParameters(),
1047 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001048 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001049 return true;
1050
1051 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001052 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001053 //
1054 // As part of this, also check whether one of the member functions
1055 // is static, in which case they are not overloads (C++
1056 // 13.1p2). While not part of the definition of the signature,
1057 // this check is important to determine whether these functions
1058 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001059 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1060 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001061 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001062 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1063 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1064 if (!UseUsingDeclRules &&
1065 (OldMethod->getRefQualifier() == RQ_None ||
1066 NewMethod->getRefQualifier() == RQ_None)) {
1067 // C++0x [over.load]p2:
1068 // - Member function declarations with the same name and the same
1069 // parameter-type-list as well as member function template
1070 // declarations with the same name, the same parameter-type-list, and
1071 // the same template parameter lists cannot be overloaded if any of
1072 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001073 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001074 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001075 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001076 }
1077 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Richard Smith574f4f62013-01-14 05:37:29 +00001080 // We may not have applied the implicit const for a constexpr member
1081 // function yet (because we haven't yet resolved whether this is a static
1082 // or non-static member function). Add it now, on the assumption that this
1083 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001084 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001085 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001086 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001087 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001088 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001089
1090 // We do not allow overloading based off of '__restrict'.
1091 OldQuals &= ~Qualifiers::Restrict;
1092 NewQuals &= ~Qualifiers::Restrict;
1093 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001094 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001097 // Though pass_object_size is placed on parameters and takes an argument, we
1098 // consider it to be a function-level modifier for the sake of function
1099 // identity. Either the function has one or more parameters with
1100 // pass_object_size or it doesn't.
1101 if (functionHasPassObjectSizeParams(New) !=
1102 functionHasPassObjectSizeParams(Old))
1103 return true;
1104
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001105 // enable_if attributes are an order-sensitive part of the signature.
1106 for (specific_attr_iterator<EnableIfAttr>
1107 NewI = New->specific_attr_begin<EnableIfAttr>(),
1108 NewE = New->specific_attr_end<EnableIfAttr>(),
1109 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1110 OldE = Old->specific_attr_end<EnableIfAttr>();
1111 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1112 if (NewI == NewE || OldI == OldE)
1113 return true;
1114 llvm::FoldingSetNodeID NewID, OldID;
1115 NewI->getCond()->Profile(NewID, Context, true);
1116 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001117 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001118 return true;
1119 }
1120
Artem Belevich94a55e82015-09-22 17:22:59 +00001121 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1122 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1123 OldTarget = IdentifyCUDATarget(Old);
1124 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1125 return false;
1126
1127 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1128
1129 // Don't allow mixing of HD with other kinds. This guarantees that
1130 // we have only one viable function with this signature on any
1131 // side of CUDA compilation .
Artem Belevich1ef9b592016-02-24 21:54:45 +00001132 // __global__ functions can't be overloaded based on attribute
1133 // difference because, like HD, they also exist on both sides.
1134 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1135 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001136 return false;
1137
1138 // Allow overloading of functions with same signature, but
1139 // different CUDA target attributes.
1140 return NewTarget != OldTarget;
1141 }
1142
John McCall1f82f242009-11-18 22:49:29 +00001143 // The signatures match; this is not an overload.
1144 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145}
1146
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001147/// \brief Checks availability of the function depending on the current
1148/// function context. Inside an unavailable function, unavailability is ignored.
1149///
1150/// \returns true if \arg FD is unavailable and current context is inside
1151/// an available function, false otherwise.
1152bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001153 if (!FD->isUnavailable())
1154 return false;
1155
1156 // Walk up the context of the caller.
1157 Decl *C = cast<Decl>(CurContext);
1158 do {
1159 if (C->isUnavailable())
1160 return false;
1161 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1162 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001163}
1164
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001165/// \brief Tries a user-defined conversion from From to ToType.
1166///
1167/// Produces an implicit conversion sequence for when a standard conversion
1168/// is not an option. See TryImplicitConversion for more information.
1169static ImplicitConversionSequence
1170TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1171 bool SuppressUserConversions,
1172 bool AllowExplicit,
1173 bool InOverloadResolution,
1174 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001175 bool AllowObjCWritebackConversion,
1176 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001177 ImplicitConversionSequence ICS;
1178
1179 if (SuppressUserConversions) {
1180 // We're not in the case above, so there is no conversion that
1181 // we can perform.
1182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1183 return ICS;
1184 }
1185
1186 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001187 OverloadCandidateSet Conversions(From->getExprLoc(),
1188 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001189 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1190 Conversions, AllowExplicit,
1191 AllowObjCConversionOnExplicit)) {
1192 case OR_Success:
1193 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001195 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001196 // C++ [over.ics.user]p4:
1197 // A conversion of an expression of class type to the same class
1198 // type is given Exact Match rank, and a conversion of an
1199 // expression of class type to a base class of that type is
1200 // given Conversion rank, in spite of the fact that a copy
1201 // constructor (i.e., a user-defined conversion function) is
1202 // called for those cases.
1203 if (CXXConstructorDecl *Constructor
1204 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1205 QualType FromCanon
1206 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1207 QualType ToCanon
1208 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1209 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001210 (FromCanon == ToCanon ||
1211 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001212 // Turn this into a "standard" conversion sequence, so that it
1213 // gets ranked with standard conversion sequences.
1214 ICS.setStandard();
1215 ICS.Standard.setAsIdentityConversion();
1216 ICS.Standard.setFromType(From->getType());
1217 ICS.Standard.setAllToTypes(ToType);
1218 ICS.Standard.CopyConstructor = Constructor;
1219 if (ToCanon != FromCanon)
1220 ICS.Standard.Second = ICK_Derived_To_Base;
1221 }
1222 }
Richard Smith48372b62015-01-27 03:30:40 +00001223 break;
1224
1225 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001226 ICS.setAmbiguous();
1227 ICS.Ambiguous.setFromType(From->getType());
1228 ICS.Ambiguous.setToType(ToType);
1229 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1230 Cand != Conversions.end(); ++Cand)
1231 if (Cand->Viable)
1232 ICS.Ambiguous.addConversion(Cand->Function);
1233 break;
Richard Smith48372b62015-01-27 03:30:40 +00001234
1235 // Fall through.
1236 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001237 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001238 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001239 }
1240
1241 return ICS;
1242}
1243
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001244/// TryImplicitConversion - Attempt to perform an implicit conversion
1245/// from the given expression (Expr) to the given type (ToType). This
1246/// function returns an implicit conversion sequence that can be used
1247/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001248///
1249/// void f(float f);
1250/// void g(int i) { f(i); }
1251///
1252/// this routine would produce an implicit conversion sequence to
1253/// describe the initialization of f from i, which will be a standard
1254/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1255/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1256//
1257/// Note that this routine only determines how the conversion can be
1258/// performed; it does not actually perform the conversion. As such,
1259/// it will not produce any diagnostics if no conversion is available,
1260/// but will instead return an implicit conversion sequence of kind
1261/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001262///
1263/// If @p SuppressUserConversions, then user-defined conversions are
1264/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001265/// If @p AllowExplicit, then explicit user-defined conversions are
1266/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001267///
1268/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1269/// writeback conversion, which allows __autoreleasing id* parameters to
1270/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001271static ImplicitConversionSequence
1272TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1273 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001275 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001276 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001277 bool AllowObjCWritebackConversion,
1278 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001280 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001281 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001282 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001283 return ICS;
1284 }
1285
David Blaikiebbafb8a2012-03-11 07:00:24 +00001286 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001287 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001288 return ICS;
1289 }
1290
Douglas Gregor836a7e82010-08-11 02:15:33 +00001291 // C++ [over.ics.user]p4:
1292 // A conversion of an expression of class type to the same class
1293 // type is given Exact Match rank, and a conversion of an
1294 // expression of class type to a base class of that type is
1295 // given Conversion rank, in spite of the fact that a copy/move
1296 // constructor (i.e., a user-defined conversion function) is
1297 // called for those cases.
1298 QualType FromType = From->getType();
1299 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001300 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001301 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001302 ICS.setStandard();
1303 ICS.Standard.setAsIdentityConversion();
1304 ICS.Standard.setFromType(FromType);
1305 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001306
Douglas Gregor5ab11652010-04-17 22:01:05 +00001307 // We don't actually check at this point whether there is a valid
1308 // copy/move constructor, since overloading just assumes that it
1309 // exists. When we actually perform initialization, we'll find the
1310 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001311 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312
Douglas Gregor5ab11652010-04-17 22:01:05 +00001313 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001314 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001315 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
Douglas Gregor836a7e82010-08-11 02:15:33 +00001317 return ICS;
1318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001320 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1321 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001322 AllowObjCWritebackConversion,
1323 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001324}
1325
John McCall31168b02011-06-15 23:02:42 +00001326ImplicitConversionSequence
1327Sema::TryImplicitConversion(Expr *From, QualType ToType,
1328 bool SuppressUserConversions,
1329 bool AllowExplicit,
1330 bool InOverloadResolution,
1331 bool CStyle,
1332 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001333 return ::TryImplicitConversion(*this, From, ToType,
1334 SuppressUserConversions, AllowExplicit,
1335 InOverloadResolution, CStyle,
1336 AllowObjCWritebackConversion,
1337 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001338}
1339
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001340/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001341/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001342/// converted expression. Flavor is the kind of conversion we're
1343/// performing, used in the error message. If @p AllowExplicit,
1344/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001345ExprResult
1346Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001347 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001348 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001349 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001350}
1351
John Wiegley01296292011-04-08 18:41:53 +00001352ExprResult
1353Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001354 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001355 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001356 if (checkPlaceholderForOverload(*this, From))
1357 return ExprError();
1358
John McCall31168b02011-06-15 23:02:42 +00001359 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1360 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001361 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001362 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001363 if (getLangOpts().ObjC1)
1364 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1365 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001366 ICS = ::TryImplicitConversion(*this, From, ToType,
1367 /*SuppressUserConversions=*/false,
1368 AllowExplicit,
1369 /*InOverloadResolution=*/false,
1370 /*CStyle=*/false,
1371 AllowObjCWritebackConversion,
1372 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001373 return PerformImplicitConversion(From, ToType, ICS, Action);
1374}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375
1376/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001377/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001378bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1379 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001380 if (Context.hasSameUnqualifiedType(FromType, ToType))
1381 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382
John McCall991eb4b2010-12-21 00:44:39 +00001383 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1384 // where F adds one of the following at most once:
1385 // - a pointer
1386 // - a member pointer
1387 // - a block pointer
1388 CanQualType CanTo = Context.getCanonicalType(ToType);
1389 CanQualType CanFrom = Context.getCanonicalType(FromType);
1390 Type::TypeClass TyClass = CanTo->getTypeClass();
1391 if (TyClass != CanFrom->getTypeClass()) return false;
1392 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1393 if (TyClass == Type::Pointer) {
1394 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1395 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1396 } else if (TyClass == Type::BlockPointer) {
1397 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1398 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1399 } else if (TyClass == Type::MemberPointer) {
1400 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1401 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1402 } else {
1403 return false;
1404 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001405
John McCall991eb4b2010-12-21 00:44:39 +00001406 TyClass = CanTo->getTypeClass();
1407 if (TyClass != CanFrom->getTypeClass()) return false;
1408 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1409 return false;
1410 }
1411
1412 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1413 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1414 if (!EInfo.getNoReturn()) return false;
1415
1416 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1417 assert(QualType(FromFn, 0).isCanonical());
1418 if (QualType(FromFn, 0) != CanTo) return false;
1419
1420 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001421 return true;
1422}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
Douglas Gregor46188682010-05-18 22:42:18 +00001424/// \brief Determine whether the conversion from FromType to ToType is a valid
1425/// vector conversion.
1426///
1427/// \param ICK Will be set to the vector conversion kind, if this is a vector
1428/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001429static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001431 // We need at least one of these types to be a vector type to have a vector
1432 // conversion.
1433 if (!ToType->isVectorType() && !FromType->isVectorType())
1434 return false;
1435
1436 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001437 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001438 return false;
1439
1440 // There are no conversions between extended vector types, only identity.
1441 if (ToType->isExtVectorType()) {
1442 // There are no conversions between extended vector types other than the
1443 // identity conversion.
1444 if (FromType->isExtVectorType())
1445 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446
Douglas Gregor46188682010-05-18 22:42:18 +00001447 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001448 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001449 ICK = ICK_Vector_Splat;
1450 return true;
1451 }
1452 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001453
1454 // We can perform the conversion between vector types in the following cases:
1455 // 1)vector types are equivalent AltiVec and GCC vector types
1456 // 2)lax vector conversions are permitted and the vector types are of the
1457 // same size
1458 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001459 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1460 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001461 ICK = ICK_Vector_Conversion;
1462 return true;
1463 }
Douglas Gregor46188682010-05-18 22:42:18 +00001464 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001465
Douglas Gregor46188682010-05-18 22:42:18 +00001466 return false;
1467}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001469static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1470 bool InOverloadResolution,
1471 StandardConversionSequence &SCS,
1472 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001473
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001474/// IsStandardConversion - Determines whether there is a standard
1475/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1476/// expression From to the type ToType. Standard conversion sequences
1477/// only consider non-class types; for conversions that involve class
1478/// types, use TryImplicitConversion. If a conversion exists, SCS will
1479/// contain the standard conversion sequence required to perform this
1480/// conversion and this routine will return true. Otherwise, this
1481/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001482static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1483 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001484 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001485 bool CStyle,
1486 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001489 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001490 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001491 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001492 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001493 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001494
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001495 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001496 // abort early. When overloading in C, however, we do permit them.
1497 if (S.getLangOpts().CPlusPlus &&
1498 (FromType->isRecordType() || ToType->isRecordType()))
1499 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001500
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 // The first conversion can be an lvalue-to-rvalue conversion,
1502 // array-to-pointer conversion, or function-to-pointer conversion
1503 // (C++ 4p1).
1504
John McCall5c32be02010-08-24 20:38:10 +00001505 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001506 DeclAccessPair AccessPair;
1507 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001509 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001510 // We were able to resolve the address of the overloaded function,
1511 // so we can convert to the type of that function.
1512 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001513 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001514
1515 // we can sometimes resolve &foo<int> regardless of ToType, so check
1516 // if the type matches (identity) or we are converting to bool
1517 if (!S.Context.hasSameUnqualifiedType(
1518 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1519 QualType resultTy;
1520 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001521 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001522 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1523 // otherwise, only a boolean conversion is standard
1524 if (!ToType->isBooleanType())
1525 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527
Chandler Carruthffce2452011-03-29 08:08:18 +00001528 // Check if the "from" expression is taking the address of an overloaded
1529 // function and recompute the FromType accordingly. Take advantage of the
1530 // fact that non-static member functions *must* have such an address-of
1531 // expression.
1532 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1533 if (Method && !Method->isStatic()) {
1534 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1535 "Non-unary operator on non-static member address");
1536 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1537 == UO_AddrOf &&
1538 "Non-address-of operator on non-static member address");
1539 const Type *ClassType
1540 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1541 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001542 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1543 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1544 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001545 "Non-address-of operator for overloaded function expression");
1546 FromType = S.Context.getPointerType(FromType);
1547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Douglas Gregor980fb162010-04-29 18:24:40 +00001549 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001550 assert(S.Context.hasSameType(
1551 FromType,
1552 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001553 } else {
1554 return false;
1555 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001556 }
John McCall154a2fd2011-08-30 00:57:29 +00001557 // Lvalue-to-rvalue conversion (C++11 4.1):
1558 // A glvalue (3.10) of a non-function, non-array type T can
1559 // be converted to a prvalue.
1560 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001561 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001562 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001563 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565
Douglas Gregorc79862f2012-04-12 17:51:55 +00001566 // C11 6.3.2.1p2:
1567 // ... if the lvalue has atomic type, the value has the non-atomic version
1568 // of the type of the lvalue ...
1569 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1570 FromType = Atomic->getValueType();
1571
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 // If T is a non-class type, the type of the rvalue is the
1573 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001574 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1575 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001577 } else if (FromType->isArrayType()) {
1578 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001579 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580
1581 // An lvalue or rvalue of type "array of N T" or "array of unknown
1582 // bound of T" can be converted to an rvalue of type "pointer to
1583 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001584 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585
John McCall5c32be02010-08-24 20:38:10 +00001586 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001587 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001588 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589
1590 // For the purpose of ranking in overload resolution
1591 // (13.3.3.1.1), this conversion is considered an
1592 // array-to-pointer conversion followed by a qualification
1593 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001594 SCS.Second = ICK_Identity;
1595 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001596 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001597 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 }
John McCall086a4642010-11-24 05:12:34 +00001600 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001604 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1605 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1606 if (!S.checkAddressOfFunctionIsAvailable(FD))
1607 return false;
1608
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609 // An lvalue of function type T can be converted to an rvalue of
1610 // type "pointer to T." The result is a pointer to the
1611 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001612 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001613 } else {
1614 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001615 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001617 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618
1619 // The second conversion can be an integral promotion, floating
1620 // point promotion, integral conversion, floating point conversion,
1621 // floating-integral conversion, pointer conversion,
1622 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001623 // For overloading in C, this can also be a "compatible-type"
1624 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001625 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001626 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001627 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 // The unqualified versions of the types are the same: there's no
1629 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001631 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001632 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001633 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001635 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001639 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001640 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001641 SCS.Second = ICK_Complex_Promotion;
1642 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001643 } else if (ToType->isBooleanType() &&
1644 (FromType->isArithmeticType() ||
1645 FromType->isAnyPointerType() ||
1646 FromType->isBlockPointerType() ||
1647 FromType->isMemberPointerType() ||
1648 FromType->isNullPtrType())) {
1649 // Boolean conversions (C++ 4.12).
1650 SCS.Second = ICK_Boolean_Conversion;
1651 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001652 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001653 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001654 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001657 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001658 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001659 SCS.Second = ICK_Complex_Conversion;
1660 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001661 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1662 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001663 // Complex-real conversions (C99 6.3.1.7)
1664 SCS.Second = ICK_Complex_Real;
1665 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001666 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001667 // Floating point conversions (C++ 4.8).
1668 SCS.Second = ICK_Floating_Conversion;
1669 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001671 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001672 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001673 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001674 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001675 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001677 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001678 SCS.Second = ICK_Block_Pointer_Conversion;
1679 } else if (AllowObjCWritebackConversion &&
1680 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1681 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001682 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1683 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001684 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001686 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001687 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001689 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001690 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001691 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001692 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001693 SCS.Second = SecondICK;
1694 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001695 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001696 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001697 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001698 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001699 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001700 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001701 // Treat a conversion that strips "noreturn" as an identity conversion.
1702 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001703 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1704 InOverloadResolution,
1705 SCS, CStyle)) {
1706 SCS.Second = ICK_TransparentUnionConversion;
1707 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001708 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1709 CStyle)) {
1710 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001711 // appropriately.
1712 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001713 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001714 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001715 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001716 SCS.Second = ICK_Zero_Event_Conversion;
1717 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 } else {
1719 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001720 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001722 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001724 QualType CanonFrom;
1725 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001727 bool ObjCLifetimeConversion;
1728 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1729 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001730 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001731 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001732 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001733 CanonFrom = S.Context.getCanonicalType(FromType);
1734 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001735 } else {
1736 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001737 SCS.Third = ICK_Identity;
1738
Mike Stump11289f42009-09-09 15:08:12 +00001739 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001740 // [...] Any difference in top-level cv-qualification is
1741 // subsumed by the initialization itself and does not constitute
1742 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001743 CanonFrom = S.Context.getCanonicalType(FromType);
1744 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001746 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001747 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001748 FromType = ToType;
1749 CanonFrom = CanonTo;
1750 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001751 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001752 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753
George Burgess IV45461812015-10-11 20:13:20 +00001754 if (CanonFrom == CanonTo)
1755 return true;
1756
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001758 // this is a bad conversion sequence, unless we're resolving an overload in C.
1759 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001760 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001761
George Burgess IV45461812015-10-11 20:13:20 +00001762 ExprResult ER = ExprResult{From};
1763 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1764 /*Diagnose=*/false,
1765 /*DiagnoseCFAudited=*/false,
1766 /*ConvertRHS=*/false);
1767 if (Conv != Sema::Compatible)
1768 return false;
1769
1770 SCS.setAllToTypes(ToType);
1771 // We need to set all three because we want this conversion to rank terribly,
1772 // and we don't know what conversions it may overlap with.
1773 SCS.First = ICK_C_Only_Conversion;
1774 SCS.Second = ICK_C_Only_Conversion;
1775 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001776 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001778
1779static bool
1780IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1781 QualType &ToType,
1782 bool InOverloadResolution,
1783 StandardConversionSequence &SCS,
1784 bool CStyle) {
1785
1786 const RecordType *UT = ToType->getAsUnionType();
1787 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1788 return false;
1789 // The field to initialize within the transparent union.
1790 RecordDecl *UD = UT->getDecl();
1791 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001792 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001793 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1794 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001795 ToType = it->getType();
1796 return true;
1797 }
1798 }
1799 return false;
1800}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001801
1802/// IsIntegralPromotion - Determines whether the conversion from the
1803/// expression From (whose potentially-adjusted type is FromType) to
1804/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1805/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001806bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001807 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001808 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001809 if (!To) {
1810 return false;
1811 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812
1813 // An rvalue of type char, signed char, unsigned char, short int, or
1814 // unsigned short int can be converted to an rvalue of type int if
1815 // int can represent all the values of the source type; otherwise,
1816 // the source rvalue can be converted to an rvalue of type unsigned
1817 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001818 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1819 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 if (// We can promote any signed, promotable integer type to an int
1821 (FromType->isSignedIntegerType() ||
1822 // We can promote any unsigned integer type whose size is
1823 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001824 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001825 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001827 }
1828
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 return To->getKind() == BuiltinType::UInt;
1830 }
1831
Richard Smithb9c5a602012-09-13 21:18:54 +00001832 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001833 // A prvalue of an unscoped enumeration type whose underlying type is not
1834 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1835 // following types that can represent all the values of the enumeration
1836 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1837 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001838 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001840 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841 // with lowest integer conversion rank (4.13) greater than the rank of long
1842 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001843 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001844 // C++11 [conv.prom]p4:
1845 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1846 // can be converted to a prvalue of its underlying type. Moreover, if
1847 // integral promotion can be applied to its underlying type, a prvalue of an
1848 // unscoped enumeration type whose underlying type is fixed can also be
1849 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001850 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1851 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1852 // provided for a scoped enumeration.
1853 if (FromEnumType->getDecl()->isScoped())
1854 return false;
1855
Richard Smithb9c5a602012-09-13 21:18:54 +00001856 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001857 // even if that's not the promoted type. Note that the check for promoting
1858 // the underlying type is based on the type alone, and does not consider
1859 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001860 if (FromEnumType->getDecl()->isFixed()) {
1861 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1862 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001863 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001864 }
1865
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001866 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001868 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001869 return Context.hasSameUnqualifiedType(
1870 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001871 }
John McCall56774992009-12-09 09:09:27 +00001872
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001873 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1875 // to an rvalue a prvalue of the first of the following types that can
1876 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001877 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001879 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001881 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001883 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884 // Determine whether the type we're converting from is signed or
1885 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001886 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001887 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001889 // The types we'll try to promote to, in the appropriate
1890 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001891 QualType PromoteTypes[6] = {
1892 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001893 Context.LongTy, Context.UnsignedLongTy ,
1894 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001895 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001896 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001897 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1898 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001899 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001900 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1901 // We found the type that we can promote to. If this is the
1902 // type we wanted, we have a promotion. Otherwise, no
1903 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001904 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001905 }
1906 }
1907 }
1908
1909 // An rvalue for an integral bit-field (9.6) can be converted to an
1910 // rvalue of type int if int can represent all the values of the
1911 // bit-field; otherwise, it can be converted to unsigned int if
1912 // unsigned int can represent all the values of the bit-field. If
1913 // the bit-field is larger yet, no integral promotion applies to
1914 // it. If the bit-field has an enumerated type, it is treated as any
1915 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001916 // FIXME: We should delay checking of bit-fields until we actually perform the
1917 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001918 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001919 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001920 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001921 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001922 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001923 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001924 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001926 // Are we promoting to an int from a bitfield that fits in an int?
1927 if (BitWidth < ToSize ||
1928 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1929 return To->getKind() == BuiltinType::Int;
1930 }
Mike Stump11289f42009-09-09 15:08:12 +00001931
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001932 // Are we promoting to an unsigned int from an unsigned bitfield
1933 // that fits into an unsigned int?
1934 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1935 return To->getKind() == BuiltinType::UInt;
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001938 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001940 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001943 // An rvalue of type bool can be converted to an rvalue of type int,
1944 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001945 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001946 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001947 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001948
1949 return false;
1950}
1951
1952/// IsFloatingPointPromotion - Determines whether the conversion from
1953/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1954/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001955bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001956 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1957 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001958 /// An rvalue of type float can be converted to an rvalue of type
1959 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001960 if (FromBuiltin->getKind() == BuiltinType::Float &&
1961 ToBuiltin->getKind() == BuiltinType::Double)
1962 return true;
1963
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001964 // C99 6.3.1.5p1:
1965 // When a float is promoted to double or long double, or a
1966 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001967 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001968 (FromBuiltin->getKind() == BuiltinType::Float ||
1969 FromBuiltin->getKind() == BuiltinType::Double) &&
1970 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1971 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001972
1973 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001974 if (!getLangOpts().NativeHalfType &&
1975 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001976 ToBuiltin->getKind() == BuiltinType::Float)
1977 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001978 }
1979
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001980 return false;
1981}
1982
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001983/// \brief Determine if a conversion is a complex promotion.
1984///
1985/// A complex promotion is defined as a complex -> complex conversion
1986/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001987/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001988bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001989 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001990 if (!FromComplex)
1991 return false;
1992
John McCall9dd450b2009-09-21 23:43:11 +00001993 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001994 if (!ToComplex)
1995 return false;
1996
1997 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001998 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001999 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002000 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002001}
2002
Douglas Gregor237f96c2008-11-26 23:31:11 +00002003/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2004/// the pointer type FromPtr to a pointer to type ToPointee, with the
2005/// same type qualifiers as FromPtr has on its pointee type. ToType,
2006/// if non-empty, will be a pointer to ToType that may or may not have
2007/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002008///
Mike Stump11289f42009-09-09 15:08:12 +00002009static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002010BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002011 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002012 ASTContext &Context,
2013 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002014 assert((FromPtr->getTypeClass() == Type::Pointer ||
2015 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2016 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
John McCall31168b02011-06-15 23:02:42 +00002018 /// Conversions to 'id' subsume cv-qualifier conversions.
2019 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002020 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
2022 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002023 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002024 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002025 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002026
John McCall31168b02011-06-15 23:02:42 +00002027 if (StripObjCLifetime)
2028 Quals.removeObjCLifetime();
2029
Mike Stump11289f42009-09-09 15:08:12 +00002030 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002031 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002032 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002033 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002034 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002035
2036 // Build a pointer to ToPointee. It has the right qualifiers
2037 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002038 if (isa<ObjCObjectPointerType>(ToType))
2039 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002040 return Context.getPointerType(ToPointee);
2041 }
2042
2043 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002044 QualType QualifiedCanonToPointee
2045 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002047 if (isa<ObjCObjectPointerType>(ToType))
2048 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2049 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002050}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051
Mike Stump11289f42009-09-09 15:08:12 +00002052static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002053 bool InOverloadResolution,
2054 ASTContext &Context) {
2055 // Handle value-dependent integral null pointer constants correctly.
2056 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2057 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002058 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002059 return !InOverloadResolution;
2060
Douglas Gregor56751b52009-09-25 04:25:58 +00002061 return Expr->isNullPointerConstant(Context,
2062 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2063 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002064}
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002066/// IsPointerConversion - Determines whether the conversion of the
2067/// expression From, which has the (possibly adjusted) type FromType,
2068/// can be converted to the type ToType via a pointer conversion (C++
2069/// 4.10). If so, returns true and places the converted type (that
2070/// might differ from ToType in its cv-qualifiers at some level) into
2071/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002072///
Douglas Gregora29dc052008-11-27 01:19:21 +00002073/// This routine also supports conversions to and from block pointers
2074/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2075/// pointers to interfaces. FIXME: Once we've determined the
2076/// appropriate overloading rules for Objective-C, we may want to
2077/// split the Objective-C checks into a different routine; however,
2078/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002079/// conversions, so for now they live here. IncompatibleObjC will be
2080/// set if the conversion is an allowed Objective-C conversion that
2081/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002082bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002083 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002084 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002085 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002086 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002087 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2088 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002089 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002090
Mike Stump11289f42009-09-09 15:08:12 +00002091 // Conversion from a null pointer constant to any Objective-C pointer type.
2092 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002093 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002094 ConvertedType = ToType;
2095 return true;
2096 }
2097
Douglas Gregor231d1c62008-11-27 00:15:41 +00002098 // Blocks: Block pointers can be converted to void*.
2099 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002100 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002101 ConvertedType = ToType;
2102 return true;
2103 }
2104 // Blocks: A null pointer constant can be converted to a block
2105 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002106 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002107 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002108 ConvertedType = ToType;
2109 return true;
2110 }
2111
Sebastian Redl576fd422009-05-10 18:38:11 +00002112 // If the left-hand-side is nullptr_t, the right side can be a null
2113 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002114 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002115 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002116 ConvertedType = ToType;
2117 return true;
2118 }
2119
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002120 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002121 if (!ToTypePtr)
2122 return false;
2123
2124 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002125 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002126 ConvertedType = ToType;
2127 return true;
2128 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002129
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002131 // , including objective-c pointers.
2132 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002133 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002134 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002135 ConvertedType = BuildSimilarlyQualifiedPointerType(
2136 FromType->getAs<ObjCObjectPointerType>(),
2137 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002138 ToType, Context);
2139 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002140 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002141 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002142 if (!FromTypePtr)
2143 return false;
2144
2145 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002146
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002148 // pointer conversion, so don't do all of the work below.
2149 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2150 return false;
2151
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002152 // An rvalue of type "pointer to cv T," where T is an object type,
2153 // can be converted to an rvalue of type "pointer to cv void" (C++
2154 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002155 if (FromPointeeType->isIncompleteOrObjectType() &&
2156 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002158 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002159 ToType, Context,
2160 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002161 return true;
2162 }
2163
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002164 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002165 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002166 ToPointeeType->isVoidType()) {
2167 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2168 ToPointeeType,
2169 ToType, Context);
2170 return true;
2171 }
2172
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002173 // When we're overloading in C, we allow a special kind of pointer
2174 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002175 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002176 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002178 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002179 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002180 return true;
2181 }
2182
Douglas Gregor5c407d92008-10-23 00:40:37 +00002183 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002184 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002185 // An rvalue of type "pointer to cv D," where D is a class type,
2186 // can be converted to an rvalue of type "pointer to cv B," where
2187 // B is a base class (clause 10) of D. If B is an inaccessible
2188 // (clause 11) or ambiguous (10.2) base class of D, a program that
2189 // necessitates this conversion is ill-formed. The result of the
2190 // conversion is a pointer to the base class sub-object of the
2191 // derived class object. The null pointer value is converted to
2192 // the null pointer value of the destination type.
2193 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002194 // Note that we do not check for ambiguity or inaccessibility
2195 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002196 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002197 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002198 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002199 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002201 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002202 ToType, Context);
2203 return true;
2204 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002205
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002206 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2207 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2209 ToPointeeType,
2210 ToType, Context);
2211 return true;
2212 }
2213
Douglas Gregora119f102008-12-19 19:13:09 +00002214 return false;
2215}
Douglas Gregoraec25842011-04-26 23:16:46 +00002216
2217/// \brief Adopt the given qualifiers for the given type.
2218static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2219 Qualifiers TQs = T.getQualifiers();
2220
2221 // Check whether qualifiers already match.
2222 if (TQs == Qs)
2223 return T;
2224
2225 if (Qs.compatiblyIncludes(TQs))
2226 return Context.getQualifiedType(T, Qs);
2227
2228 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2229}
Douglas Gregora119f102008-12-19 19:13:09 +00002230
2231/// isObjCPointerConversion - Determines whether this is an
2232/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2233/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002234bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002235 QualType& ConvertedType,
2236 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002238 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239
Douglas Gregoraec25842011-04-26 23:16:46 +00002240 // The set of qualifiers on the type we're converting from.
2241 Qualifiers FromQualifiers = FromType.getQualifiers();
2242
Steve Naroff7cae42b2009-07-10 23:34:53 +00002243 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002244 const ObjCObjectPointerType* ToObjCPtr =
2245 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002246 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002247 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002248
Steve Naroff7cae42b2009-07-10 23:34:53 +00002249 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002250 // If the pointee types are the same (ignoring qualifications),
2251 // then this is not a pointer conversion.
2252 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2253 FromObjCPtr->getPointeeType()))
2254 return false;
2255
Douglas Gregorab209d82015-07-07 03:58:42 +00002256 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002257 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002258 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2259 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002260 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002261 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2262 FromObjCPtr->getPointeeType()))
2263 return false;
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 }
2270
2271 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2272 // Okay: this is some kind of implicit downcast of Objective-C
2273 // interfaces, which is permitted. However, we're going to
2274 // complain about it.
2275 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002277 ToObjCPtr->getPointeeType(),
2278 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002279 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002280 return true;
2281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002283 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002284 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002285 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002286 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002287 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002288 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002289 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002290 // to a block pointer type.
2291 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002292 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002293 return true;
2294 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002295 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002297 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002298 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002300 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002301 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002302 return true;
2303 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002304 else
Douglas Gregora119f102008-12-19 19:13:09 +00002305 return false;
2306
Douglas Gregor033f56d2008-12-23 00:53:59 +00002307 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002308 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002309 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002310 else if (const BlockPointerType *FromBlockPtr =
2311 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002312 FromPointeeType = FromBlockPtr->getPointeeType();
2313 else
Douglas Gregora119f102008-12-19 19:13:09 +00002314 return false;
2315
Douglas Gregora119f102008-12-19 19:13:09 +00002316 // If we have pointers to pointers, recursively check whether this
2317 // is an Objective-C conversion.
2318 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2319 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2320 IncompatibleObjC)) {
2321 // We always complain about this conversion.
2322 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002323 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002324 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002325 return true;
2326 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002327 // Allow conversion of pointee being objective-c pointer to another one;
2328 // as in I* to id.
2329 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2330 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2331 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2332 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002333
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002334 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002335 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002336 return true;
2337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002338
Douglas Gregor033f56d2008-12-23 00:53:59 +00002339 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002340 // differences in the argument and result types are in Objective-C
2341 // pointer conversions. If so, we permit the conversion (but
2342 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002343 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002344 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002345 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002346 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002347 if (FromFunctionType && ToFunctionType) {
2348 // If the function types are exactly the same, this isn't an
2349 // Objective-C pointer conversion.
2350 if (Context.getCanonicalType(FromPointeeType)
2351 == Context.getCanonicalType(ToPointeeType))
2352 return false;
2353
2354 // Perform the quick checks that will tell us whether these
2355 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002356 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002357 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2358 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2359 return false;
2360
2361 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002362 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2363 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002364 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002365 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2366 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002367 ConvertedType, IncompatibleObjC)) {
2368 // Okay, we have an Objective-C pointer conversion.
2369 HasObjCConversion = true;
2370 } else {
2371 // Function types are too different. Abort.
2372 return false;
2373 }
Mike Stump11289f42009-09-09 15:08:12 +00002374
Douglas Gregora119f102008-12-19 19:13:09 +00002375 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002376 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002377 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002378 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2379 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002380 if (Context.getCanonicalType(FromArgType)
2381 == Context.getCanonicalType(ToArgType)) {
2382 // Okay, the types match exactly. Nothing to do.
2383 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2384 ConvertedType, IncompatibleObjC)) {
2385 // Okay, we have an Objective-C pointer conversion.
2386 HasObjCConversion = true;
2387 } else {
2388 // Argument types are too different. Abort.
2389 return false;
2390 }
2391 }
2392
2393 if (HasObjCConversion) {
2394 // We had an Objective-C conversion. Allow this pointer
2395 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002396 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002397 IncompatibleObjC = true;
2398 return true;
2399 }
2400 }
2401
Sebastian Redl72b597d2009-01-25 19:43:20 +00002402 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002403}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404
John McCall31168b02011-06-15 23:02:42 +00002405/// \brief Determine whether this is an Objective-C writeback conversion,
2406/// used for parameter passing when performing automatic reference counting.
2407///
2408/// \param FromType The type we're converting form.
2409///
2410/// \param ToType The type we're converting to.
2411///
2412/// \param ConvertedType The type that will be produced after applying
2413/// this conversion.
2414bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2415 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002416 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002417 Context.hasSameUnqualifiedType(FromType, ToType))
2418 return false;
2419
2420 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2421 QualType ToPointee;
2422 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2423 ToPointee = ToPointer->getPointeeType();
2424 else
2425 return false;
2426
2427 Qualifiers ToQuals = ToPointee.getQualifiers();
2428 if (!ToPointee->isObjCLifetimeType() ||
2429 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002430 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002431 return false;
2432
2433 // Argument must be a pointer to __strong to __weak.
2434 QualType FromPointee;
2435 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2436 FromPointee = FromPointer->getPointeeType();
2437 else
2438 return false;
2439
2440 Qualifiers FromQuals = FromPointee.getQualifiers();
2441 if (!FromPointee->isObjCLifetimeType() ||
2442 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2443 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2444 return false;
2445
2446 // Make sure that we have compatible qualifiers.
2447 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2448 if (!ToQuals.compatiblyIncludes(FromQuals))
2449 return false;
2450
2451 // Remove qualifiers from the pointee type we're converting from; they
2452 // aren't used in the compatibility check belong, and we'll be adding back
2453 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2454 FromPointee = FromPointee.getUnqualifiedType();
2455
2456 // The unqualified form of the pointee types must be compatible.
2457 ToPointee = ToPointee.getUnqualifiedType();
2458 bool IncompatibleObjC;
2459 if (Context.typesAreCompatible(FromPointee, ToPointee))
2460 FromPointee = ToPointee;
2461 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2462 IncompatibleObjC))
2463 return false;
2464
2465 /// \brief Construct the type we're converting to, which is a pointer to
2466 /// __autoreleasing pointee.
2467 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2468 ConvertedType = Context.getPointerType(FromPointee);
2469 return true;
2470}
2471
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002472bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2473 QualType& ConvertedType) {
2474 QualType ToPointeeType;
2475 if (const BlockPointerType *ToBlockPtr =
2476 ToType->getAs<BlockPointerType>())
2477 ToPointeeType = ToBlockPtr->getPointeeType();
2478 else
2479 return false;
2480
2481 QualType FromPointeeType;
2482 if (const BlockPointerType *FromBlockPtr =
2483 FromType->getAs<BlockPointerType>())
2484 FromPointeeType = FromBlockPtr->getPointeeType();
2485 else
2486 return false;
2487 // We have pointer to blocks, check whether the only
2488 // differences in the argument and result types are in Objective-C
2489 // pointer conversions. If so, we permit the conversion.
2490
2491 const FunctionProtoType *FromFunctionType
2492 = FromPointeeType->getAs<FunctionProtoType>();
2493 const FunctionProtoType *ToFunctionType
2494 = ToPointeeType->getAs<FunctionProtoType>();
2495
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002496 if (!FromFunctionType || !ToFunctionType)
2497 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002498
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002499 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002500 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002501
2502 // Perform the quick checks that will tell us whether these
2503 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002504 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002505 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2506 return false;
2507
2508 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2509 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2510 if (FromEInfo != ToEInfo)
2511 return false;
2512
2513 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002514 if (Context.hasSameType(FromFunctionType->getReturnType(),
2515 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002516 // Okay, the types match exactly. Nothing to do.
2517 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002518 QualType RHS = FromFunctionType->getReturnType();
2519 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002520 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002521 !RHS.hasQualifiers() && LHS.hasQualifiers())
2522 LHS = LHS.getUnqualifiedType();
2523
2524 if (Context.hasSameType(RHS,LHS)) {
2525 // OK exact match.
2526 } else if (isObjCPointerConversion(RHS, LHS,
2527 ConvertedType, IncompatibleObjC)) {
2528 if (IncompatibleObjC)
2529 return false;
2530 // Okay, we have an Objective-C pointer conversion.
2531 }
2532 else
2533 return false;
2534 }
2535
2536 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002537 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002538 ArgIdx != NumArgs; ++ArgIdx) {
2539 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002540 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2541 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002542 if (Context.hasSameType(FromArgType, ToArgType)) {
2543 // Okay, the types match exactly. Nothing to do.
2544 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2545 ConvertedType, IncompatibleObjC)) {
2546 if (IncompatibleObjC)
2547 return false;
2548 // Okay, we have an Objective-C pointer conversion.
2549 } else
2550 // Argument types are too different. Abort.
2551 return false;
2552 }
John McCall18afab72016-03-01 00:49:02 +00002553 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2554 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002555 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002556
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002557 ConvertedType = ToType;
2558 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002559}
2560
Richard Trieucaff2472011-11-23 22:32:32 +00002561enum {
2562 ft_default,
2563 ft_different_class,
2564 ft_parameter_arity,
2565 ft_parameter_mismatch,
2566 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002567 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002568};
2569
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002570/// Attempts to get the FunctionProtoType from a Type. Handles
2571/// MemberFunctionPointers properly.
2572static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2573 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2574 return FPT;
2575
2576 if (auto *MPT = FromType->getAs<MemberPointerType>())
2577 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2578
2579 return nullptr;
2580}
2581
Richard Trieucaff2472011-11-23 22:32:32 +00002582/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2583/// function types. Catches different number of parameter, mismatch in
2584/// parameter types, and different return types.
2585void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2586 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002587 // If either type is not valid, include no extra info.
2588 if (FromType.isNull() || ToType.isNull()) {
2589 PDiag << ft_default;
2590 return;
2591 }
2592
Richard Trieucaff2472011-11-23 22:32:32 +00002593 // Get the function type from the pointers.
2594 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2595 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2596 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002597 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002598 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2599 << QualType(FromMember->getClass(), 0);
2600 return;
2601 }
2602 FromType = FromMember->getPointeeType();
2603 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002604 }
2605
Richard Trieu96ed5b62011-12-13 23:19:45 +00002606 if (FromType->isPointerType())
2607 FromType = FromType->getPointeeType();
2608 if (ToType->isPointerType())
2609 ToType = ToType->getPointeeType();
2610
2611 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002612 FromType = FromType.getNonReferenceType();
2613 ToType = ToType.getNonReferenceType();
2614
Richard Trieucaff2472011-11-23 22:32:32 +00002615 // Don't print extra info for non-specialized template functions.
2616 if (FromType->isInstantiationDependentType() &&
2617 !FromType->getAs<TemplateSpecializationType>()) {
2618 PDiag << ft_default;
2619 return;
2620 }
2621
Richard Trieu96ed5b62011-12-13 23:19:45 +00002622 // No extra info for same types.
2623 if (Context.hasSameType(FromType, ToType)) {
2624 PDiag << ft_default;
2625 return;
2626 }
2627
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002628 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2629 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002630
2631 // Both types need to be function types.
2632 if (!FromFunction || !ToFunction) {
2633 PDiag << ft_default;
2634 return;
2635 }
2636
Alp Toker9cacbab2014-01-20 20:26:09 +00002637 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2638 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2639 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002640 return;
2641 }
2642
2643 // Handle different parameter types.
2644 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002645 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002646 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002647 << ToFunction->getParamType(ArgPos)
2648 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002649 return;
2650 }
2651
2652 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002653 if (!Context.hasSameType(FromFunction->getReturnType(),
2654 ToFunction->getReturnType())) {
2655 PDiag << ft_return_type << ToFunction->getReturnType()
2656 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002657 return;
2658 }
2659
2660 unsigned FromQuals = FromFunction->getTypeQuals(),
2661 ToQuals = ToFunction->getTypeQuals();
2662 if (FromQuals != ToQuals) {
2663 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2664 return;
2665 }
2666
2667 // Unable to find a difference, so add no extra info.
2668 PDiag << ft_default;
2669}
2670
Alp Toker9cacbab2014-01-20 20:26:09 +00002671/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002672/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002673/// they have same number of arguments. If the parameters are different,
2674/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002675bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2676 const FunctionProtoType *NewType,
2677 unsigned *ArgPos) {
2678 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2679 N = NewType->param_type_begin(),
2680 E = OldType->param_type_end();
2681 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002682 if (!Context.hasSameType(O->getUnqualifiedType(),
2683 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002684 if (ArgPos)
2685 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002686 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002687 }
2688 }
2689 return true;
2690}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002691
Douglas Gregor39c16d42008-10-24 04:54:22 +00002692/// CheckPointerConversion - Check the pointer conversion from the
2693/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002694/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002695/// conversions for which IsPointerConversion has already returned
2696/// true. It returns true and produces a diagnostic if there was an
2697/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002698bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002699 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002700 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002701 bool IgnoreBaseAccess,
2702 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002703 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002704 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002705
John McCall8cb679e2010-11-15 09:13:47 +00002706 Kind = CK_BitCast;
2707
George Burgess IV60bc9722016-01-13 23:36:34 +00002708 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002709 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002710 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002711 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2712 DiagRuntimeBehavior(From->getExprLoc(), From,
2713 PDiag(diag::warn_impcast_bool_to_null_pointer)
2714 << ToType << From->getSourceRange());
2715 else if (!isUnevaluatedContext())
2716 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2717 << ToType << From->getSourceRange();
2718 }
John McCall9320b872011-09-09 05:25:32 +00002719 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2720 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002721 QualType FromPointeeType = FromPtrType->getPointeeType(),
2722 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002723
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002724 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2725 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002726 // We must have a derived-to-base conversion. Check an
2727 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002728 unsigned InaccessibleID = 0;
2729 unsigned AmbigiousID = 0;
2730 if (Diagnose) {
2731 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2732 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2733 }
2734 if (CheckDerivedToBaseConversion(
2735 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2736 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2737 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002738 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002740 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002741 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002742 }
David Majnemer6bf02822015-10-31 08:42:14 +00002743
George Burgess IV60bc9722016-01-13 23:36:34 +00002744 if (Diagnose && !IsCStyleOrFunctionalCast &&
2745 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002746 assert(getLangOpts().MSVCCompat &&
2747 "this should only be possible with MSVCCompat!");
2748 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2749 << From->getSourceRange();
2750 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002751 }
John McCall9320b872011-09-09 05:25:32 +00002752 } else if (const ObjCObjectPointerType *ToPtrType =
2753 ToType->getAs<ObjCObjectPointerType>()) {
2754 if (const ObjCObjectPointerType *FromPtrType =
2755 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002756 // Objective-C++ conversions are always okay.
2757 // FIXME: We should have a different class of conversions for the
2758 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002759 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002760 return false;
John McCall9320b872011-09-09 05:25:32 +00002761 } else if (FromType->isBlockPointerType()) {
2762 Kind = CK_BlockPointerToObjCPointerCast;
2763 } else {
2764 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002765 }
John McCall9320b872011-09-09 05:25:32 +00002766 } else if (ToType->isBlockPointerType()) {
2767 if (!FromType->isBlockPointerType())
2768 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002769 }
John McCall8cb679e2010-11-15 09:13:47 +00002770
2771 // We shouldn't fall into this case unless it's valid for other
2772 // reasons.
2773 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2774 Kind = CK_NullToPointer;
2775
Douglas Gregor39c16d42008-10-24 04:54:22 +00002776 return false;
2777}
2778
Sebastian Redl72b597d2009-01-25 19:43:20 +00002779/// IsMemberPointerConversion - Determines whether the conversion of the
2780/// expression From, which has the (possibly adjusted) type FromType, can be
2781/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2782/// If so, returns true and places the converted type (that might differ from
2783/// ToType in its cv-qualifiers at some level) into ConvertedType.
2784bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002786 bool InOverloadResolution,
2787 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002788 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002789 if (!ToTypePtr)
2790 return false;
2791
2792 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002793 if (From->isNullPointerConstant(Context,
2794 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2795 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002796 ConvertedType = ToType;
2797 return true;
2798 }
2799
2800 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002801 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002802 if (!FromTypePtr)
2803 return false;
2804
2805 // A pointer to member of B can be converted to a pointer to member of D,
2806 // where D is derived from B (C++ 4.11p2).
2807 QualType FromClass(FromTypePtr->getClass(), 0);
2808 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002809
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002810 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002811 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002812 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2813 ToClass.getTypePtr());
2814 return true;
2815 }
2816
2817 return false;
2818}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819
Sebastian Redl72b597d2009-01-25 19:43:20 +00002820/// CheckMemberPointerConversion - Check the member pointer conversion from the
2821/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002822/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002823/// for which IsMemberPointerConversion has already returned true. It returns
2824/// true and produces a diagnostic if there was an error, or returns false
2825/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002826bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002827 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002828 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002829 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002830 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002831 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002832 if (!FromPtrType) {
2833 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002835 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002836 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002837 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002838 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002839 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002840
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002841 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002842 assert(ToPtrType && "No member pointer cast has a target type "
2843 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002844
Sebastian Redled8f2002009-01-28 18:33:18 +00002845 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2846 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002847
Sebastian Redled8f2002009-01-28 18:33:18 +00002848 // FIXME: What about dependent types?
2849 assert(FromClass->isRecordType() && "Pointer into non-class.");
2850 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002851
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002852 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002853 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002854 bool DerivationOkay =
2855 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002856 assert(DerivationOkay &&
2857 "Should not have been called if derivation isn't OK.");
2858 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002859
Sebastian Redled8f2002009-01-28 18:33:18 +00002860 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2861 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002862 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2863 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2864 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2865 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002866 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002867
Douglas Gregor89ee6822009-02-28 01:32:25 +00002868 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002869 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2870 << FromClass << ToClass << QualType(VBase, 0)
2871 << From->getSourceRange();
2872 return true;
2873 }
2874
John McCall5b0829a2010-02-10 09:31:12 +00002875 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002876 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2877 Paths.front(),
2878 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002879
Anders Carlssond7923c62009-08-22 23:33:40 +00002880 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002881 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002882 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002883 return false;
2884}
2885
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002886/// Determine whether the lifetime conversion between the two given
2887/// qualifiers sets is nontrivial.
2888static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2889 Qualifiers ToQuals) {
2890 // Converting anything to const __unsafe_unretained is trivial.
2891 if (ToQuals.hasConst() &&
2892 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2893 return false;
2894
2895 return true;
2896}
2897
Douglas Gregor9a657932008-10-21 23:43:52 +00002898/// IsQualificationConversion - Determines whether the conversion from
2899/// an rvalue of type FromType to ToType is a qualification conversion
2900/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002901///
2902/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2903/// when the qualification conversion involves a change in the Objective-C
2904/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002905bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002907 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002908 FromType = Context.getCanonicalType(FromType);
2909 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002910 ObjCLifetimeConversion = false;
2911
Douglas Gregor9a657932008-10-21 23:43:52 +00002912 // If FromType and ToType are the same type, this is not a
2913 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002914 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002915 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002916
Douglas Gregor9a657932008-10-21 23:43:52 +00002917 // (C++ 4.4p4):
2918 // A conversion can add cv-qualifiers at levels other than the first
2919 // in multi-level pointers, subject to the following rules: [...]
2920 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002921 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002922 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002923 // Within each iteration of the loop, we check the qualifiers to
2924 // determine if this still looks like a qualification
2925 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002926 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002927 // until there are no more pointers or pointers-to-members left to
2928 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002929 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002930
Douglas Gregor90609aa2011-04-25 18:40:17 +00002931 Qualifiers FromQuals = FromType.getQualifiers();
2932 Qualifiers ToQuals = ToType.getQualifiers();
2933
John McCall31168b02011-06-15 23:02:42 +00002934 // Objective-C ARC:
2935 // Check Objective-C lifetime conversions.
2936 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2937 UnwrappedAnyPointer) {
2938 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002939 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2940 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002941 FromQuals.removeObjCLifetime();
2942 ToQuals.removeObjCLifetime();
2943 } else {
2944 // Qualification conversions cannot cast between different
2945 // Objective-C lifetime qualifiers.
2946 return false;
2947 }
2948 }
2949
Douglas Gregorf30053d2011-05-08 06:09:53 +00002950 // Allow addition/removal of GC attributes but not changing GC attributes.
2951 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2952 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2953 FromQuals.removeObjCGCAttr();
2954 ToQuals.removeObjCGCAttr();
2955 }
2956
Douglas Gregor9a657932008-10-21 23:43:52 +00002957 // -- for every j > 0, if const is in cv 1,j then const is in cv
2958 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002959 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002960 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002961
Douglas Gregor9a657932008-10-21 23:43:52 +00002962 // -- if the cv 1,j and cv 2,j are different, then const is in
2963 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002964 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002965 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002966 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002967
Douglas Gregor9a657932008-10-21 23:43:52 +00002968 // Keep track of whether all prior cv-qualifiers in the "to" type
2969 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002970 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002971 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002972 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002973
2974 // We are left with FromType and ToType being the pointee types
2975 // after unwrapping the original FromType and ToType the same number
2976 // of types. If we unwrapped any pointers, and if FromType and
2977 // ToType have the same unqualified type (since we checked
2978 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002979 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002980}
2981
Douglas Gregorc79862f2012-04-12 17:51:55 +00002982/// \brief - Determine whether this is a conversion from a scalar type to an
2983/// atomic type.
2984///
2985/// If successful, updates \c SCS's second and third steps in the conversion
2986/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002987static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2988 bool InOverloadResolution,
2989 StandardConversionSequence &SCS,
2990 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002991 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2992 if (!ToAtomic)
2993 return false;
2994
2995 StandardConversionSequence InnerSCS;
2996 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2997 InOverloadResolution, InnerSCS,
2998 CStyle, /*AllowObjCWritebackConversion=*/false))
2999 return false;
3000
3001 SCS.Second = InnerSCS.Second;
3002 SCS.setToType(1, InnerSCS.getToType(1));
3003 SCS.Third = InnerSCS.Third;
3004 SCS.QualificationIncludesObjCLifetime
3005 = InnerSCS.QualificationIncludesObjCLifetime;
3006 SCS.setToType(2, InnerSCS.getToType(2));
3007 return true;
3008}
3009
Sebastian Redle5417162012-03-27 18:33:03 +00003010static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3011 CXXConstructorDecl *Constructor,
3012 QualType Type) {
3013 const FunctionProtoType *CtorType =
3014 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003015 if (CtorType->getNumParams() > 0) {
3016 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003017 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3018 return true;
3019 }
3020 return false;
3021}
3022
Sebastian Redl82ace982012-02-11 23:51:08 +00003023static OverloadingResult
3024IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3025 CXXRecordDecl *To,
3026 UserDefinedConversionSequence &User,
3027 OverloadCandidateSet &CandidateSet,
3028 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003029 DeclContext::lookup_result R = S.LookupConstructors(To);
3030 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003031 Con != ConEnd; ++Con) {
3032 NamedDecl *D = *Con;
3033 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3034
3035 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003036 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003037 FunctionTemplateDecl *ConstructorTmpl
3038 = dyn_cast<FunctionTemplateDecl>(D);
3039 if (ConstructorTmpl)
3040 Constructor
3041 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3042 else
3043 Constructor = cast<CXXConstructorDecl>(D);
3044
3045 bool Usable = !Constructor->isInvalidDecl() &&
3046 S.isInitListConstructor(Constructor) &&
3047 (AllowExplicit || !Constructor->isExplicit());
3048 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003049 // If the first argument is (a reference to) the target type,
3050 // suppress conversions.
3051 bool SuppressUserConversions =
3052 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003053 if (ConstructorTmpl)
3054 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003055 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003056 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003057 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003058 else
3059 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003060 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003061 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003062 }
3063 }
3064
3065 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3066
3067 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003068 switch (auto Result =
3069 CandidateSet.BestViableFunction(S, From->getLocStart(),
3070 Best, true)) {
3071 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003072 case OR_Success: {
3073 // Record the standard conversion we used and the conversion function.
3074 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003075 QualType ThisType = Constructor->getThisType(S.Context);
3076 // Initializer lists don't have conversions as such.
3077 User.Before.setAsIdentityConversion();
3078 User.HadMultipleCandidates = HadMultipleCandidates;
3079 User.ConversionFunction = Constructor;
3080 User.FoundConversionFunction = Best->FoundDecl;
3081 User.After.setAsIdentityConversion();
3082 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3083 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003084 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003085 }
3086
3087 case OR_No_Viable_Function:
3088 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003089 case OR_Ambiguous:
3090 return OR_Ambiguous;
3091 }
3092
3093 llvm_unreachable("Invalid OverloadResult!");
3094}
3095
Douglas Gregor576e98c2009-01-30 23:27:23 +00003096/// Determines whether there is a user-defined conversion sequence
3097/// (C++ [over.ics.user]) that converts expression From to the type
3098/// ToType. If such a conversion exists, User will contain the
3099/// user-defined conversion sequence that performs such a conversion
3100/// and this routine will return true. Otherwise, this routine returns
3101/// false and User is unspecified.
3102///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003103/// \param AllowExplicit true if the conversion should consider C++0x
3104/// "explicit" conversion functions as well as non-explicit conversion
3105/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003106///
3107/// \param AllowObjCConversionOnExplicit true if the conversion should
3108/// allow an extra Objective-C pointer conversion on uses of explicit
3109/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003110static OverloadingResult
3111IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003112 UserDefinedConversionSequence &User,
3113 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003114 bool AllowExplicit,
3115 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003116 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003117
Douglas Gregor5ab11652010-04-17 22:01:05 +00003118 // Whether we will only visit constructors.
3119 bool ConstructorsOnly = false;
3120
3121 // If the type we are conversion to is a class type, enumerate its
3122 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003123 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003124 // C++ [over.match.ctor]p1:
3125 // When objects of class type are direct-initialized (8.5), or
3126 // copy-initialized from an expression of the same or a
3127 // derived class type (8.5), overload resolution selects the
3128 // constructor. [...] For copy-initialization, the candidate
3129 // functions are all the converting constructors (12.3.1) of
3130 // that class. The argument list is the expression-list within
3131 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003132 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003133 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003134 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003135 ConstructorsOnly = true;
3136
Richard Smithdb0ac552015-12-18 22:40:25 +00003137 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003138 // We're not going to find any constructors.
3139 } else if (CXXRecordDecl *ToRecordDecl
3140 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003141
3142 Expr **Args = &From;
3143 unsigned NumArgs = 1;
3144 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003145 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003146 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003147 OverloadingResult Result = IsInitializerListConstructorConversion(
3148 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3149 if (Result != OR_No_Viable_Function)
3150 return Result;
3151 // Never mind.
3152 CandidateSet.clear();
3153
3154 // If we're list-initializing, we pass the individual elements as
3155 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003156 Args = InitList->getInits();
3157 NumArgs = InitList->getNumInits();
3158 ListInitializing = true;
3159 }
3160
David Blaikieff7d47a2012-12-19 00:45:41 +00003161 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3162 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003163 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003164 NamedDecl *D = *Con;
3165 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3166
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003167 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003168 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003169 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003170 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003171 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003172 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003173 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3174 else
John McCalla0296f72010-03-19 07:35:19 +00003175 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003177 bool Usable = !Constructor->isInvalidDecl();
3178 if (ListInitializing)
3179 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3180 else
3181 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3182 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003183 bool SuppressUserConversions = !ConstructorsOnly;
3184 if (SuppressUserConversions && ListInitializing) {
3185 SuppressUserConversions = false;
3186 if (NumArgs == 1) {
3187 // If the first argument is (a reference to) the target type,
3188 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003189 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003191 }
3192 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003193 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003194 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003195 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003196 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003197 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003198 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003199 // Allow one user-defined conversion when user specifies a
3200 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003201 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003202 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003203 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003204 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003205 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003206 }
3207 }
3208
Douglas Gregor5ab11652010-04-17 22:01:05 +00003209 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003210 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003211 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003212 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003213 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003214 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003215 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003216 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3217 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003218 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3219 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003220 DeclAccessPair FoundDecl = I.getPair();
3221 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003222 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3223 if (isa<UsingShadowDecl>(D))
3224 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3225
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003226 CXXConversionDecl *Conv;
3227 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003228 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3229 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003230 else
John McCallda4458e2010-03-31 01:36:47 +00003231 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003232
3233 if (AllowExplicit || !Conv->isExplicit()) {
3234 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003235 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3236 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003237 CandidateSet,
3238 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003239 else
John McCall5c32be02010-08-24 20:38:10 +00003240 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003241 From, ToType, CandidateSet,
3242 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003243 }
3244 }
3245 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003246 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003247
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003248 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3249
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003250 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003251 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3252 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003253 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003254 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003255 // Record the standard conversion we used and the conversion function.
3256 if (CXXConstructorDecl *Constructor
3257 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3258 // C++ [over.ics.user]p1:
3259 // If the user-defined conversion is specified by a
3260 // constructor (12.3.1), the initial standard conversion
3261 // sequence converts the source type to the type required by
3262 // the argument of the constructor.
3263 //
3264 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003265 if (isa<InitListExpr>(From)) {
3266 // Initializer lists don't have conversions as such.
3267 User.Before.setAsIdentityConversion();
3268 } else {
3269 if (Best->Conversions[0].isEllipsis())
3270 User.EllipsisConversion = true;
3271 else {
3272 User.Before = Best->Conversions[0].Standard;
3273 User.EllipsisConversion = false;
3274 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003275 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003276 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003277 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003278 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003279 User.After.setAsIdentityConversion();
3280 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3281 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003282 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003283 }
3284 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003285 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3286 // C++ [over.ics.user]p1:
3287 //
3288 // [...] If the user-defined conversion is specified by a
3289 // conversion function (12.3.2), the initial standard
3290 // conversion sequence converts the source type to the
3291 // implicit object parameter of the conversion function.
3292 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003293 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003294 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003295 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003296 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003297
John McCall5c32be02010-08-24 20:38:10 +00003298 // C++ [over.ics.user]p2:
3299 // The second standard conversion sequence converts the
3300 // result of the user-defined conversion to the target type
3301 // for the sequence. Since an implicit conversion sequence
3302 // is an initialization, the special rules for
3303 // initialization by user-defined conversion apply when
3304 // selecting the best user-defined conversion for a
3305 // user-defined conversion sequence (see 13.3.3 and
3306 // 13.3.3.1).
3307 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003308 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003309 }
David Blaikie8a40f702012-01-17 06:56:22 +00003310 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003311
John McCall5c32be02010-08-24 20:38:10 +00003312 case OR_No_Viable_Function:
3313 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314
John McCall5c32be02010-08-24 20:38:10 +00003315 case OR_Ambiguous:
3316 return OR_Ambiguous;
3317 }
3318
David Blaikie8a40f702012-01-17 06:56:22 +00003319 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003322bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003323Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003324 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003325 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3326 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003328 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003329 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003330 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003331 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3332 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003333 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003334 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003335 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003336 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003337 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003338 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003339 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003340 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003343}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003344
Douglas Gregor2837aa22012-02-22 17:32:19 +00003345/// \brief Compare the user-defined conversion functions or constructors
3346/// of two user-defined conversion sequences to determine whether any ordering
3347/// is possible.
3348static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003349compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003350 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003351 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003352 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003353
Douglas Gregor2837aa22012-02-22 17:32:19 +00003354 // Objective-C++:
3355 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003356 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003357 // respectively, always prefer the conversion to a function pointer,
3358 // because the function pointer is more lightweight and is more likely
3359 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003360 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003361 if (!Conv1)
3362 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003363
Douglas Gregor2837aa22012-02-22 17:32:19 +00003364 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3365 if (!Conv2)
3366 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003367
Douglas Gregor2837aa22012-02-22 17:32:19 +00003368 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3369 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3370 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3371 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003372 return Block1 ? ImplicitConversionSequence::Worse
3373 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003374 }
3375
3376 return ImplicitConversionSequence::Indistinguishable;
3377}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003378
3379static bool hasDeprecatedStringLiteralToCharPtrConversion(
3380 const ImplicitConversionSequence &ICS) {
3381 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3382 (ICS.isUserDefined() &&
3383 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3384}
3385
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386/// CompareImplicitConversionSequences - Compare two implicit
3387/// conversion sequences to determine whether one is better than the
3388/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003389static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003390CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003391 const ImplicitConversionSequence& ICS1,
3392 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003393{
3394 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3395 // conversion sequences (as defined in 13.3.3.1)
3396 // -- a standard conversion sequence (13.3.3.1.1) is a better
3397 // conversion sequence than a user-defined conversion sequence or
3398 // an ellipsis conversion sequence, and
3399 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3400 // conversion sequence than an ellipsis conversion sequence
3401 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003402 //
John McCall0d1da222010-01-12 00:44:57 +00003403 // C++0x [over.best.ics]p10:
3404 // For the purpose of ranking implicit conversion sequences as
3405 // described in 13.3.3.2, the ambiguous conversion sequence is
3406 // treated as a user-defined sequence that is indistinguishable
3407 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003408
3409 // String literal to 'char *' conversion has been deprecated in C++03. It has
3410 // been removed from C++11. We still accept this conversion, if it happens at
3411 // the best viable function. Otherwise, this conversion is considered worse
3412 // than ellipsis conversion. Consider this as an extension; this is not in the
3413 // standard. For example:
3414 //
3415 // int &f(...); // #1
3416 // void f(char*); // #2
3417 // void g() { int &r = f("foo"); }
3418 //
3419 // In C++03, we pick #2 as the best viable function.
3420 // In C++11, we pick #1 as the best viable function, because ellipsis
3421 // conversion is better than string-literal to char* conversion (since there
3422 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3423 // convert arguments, #2 would be the best viable function in C++11.
3424 // If the best viable function has this conversion, a warning will be issued
3425 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3426
3427 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3428 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3429 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3430 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3431 ? ImplicitConversionSequence::Worse
3432 : ImplicitConversionSequence::Better;
3433
Douglas Gregor5ab11652010-04-17 22:01:05 +00003434 if (ICS1.getKindRank() < ICS2.getKindRank())
3435 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003436 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003437 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003438
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003439 // The following checks require both conversion sequences to be of
3440 // the same kind.
3441 if (ICS1.getKind() != ICS2.getKind())
3442 return ImplicitConversionSequence::Indistinguishable;
3443
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003444 ImplicitConversionSequence::CompareKind Result =
3445 ImplicitConversionSequence::Indistinguishable;
3446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003447 // Two implicit conversion sequences of the same form are
3448 // indistinguishable conversion sequences unless one of the
3449 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003450
3451 // List-initialization sequence L1 is a better conversion sequence than
3452 // list-initialization sequence L2 if:
3453 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3454 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003455 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003456 // and N1 is smaller than N2.,
3457 // even if one of the other rules in this paragraph would otherwise apply.
3458 if (!ICS1.isBad()) {
3459 if (ICS1.isStdInitializerListElement() &&
3460 !ICS2.isStdInitializerListElement())
3461 return ImplicitConversionSequence::Better;
3462 if (!ICS1.isStdInitializerListElement() &&
3463 ICS2.isStdInitializerListElement())
3464 return ImplicitConversionSequence::Worse;
3465 }
3466
John McCall0d1da222010-01-12 00:44:57 +00003467 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003468 // Standard conversion sequence S1 is a better conversion sequence than
3469 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003470 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003471 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003472 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003473 // User-defined conversion sequence U1 is a better conversion
3474 // sequence than another user-defined conversion sequence U2 if
3475 // they contain the same user-defined conversion function or
3476 // constructor and if the second standard conversion sequence of
3477 // U1 is better than the second standard conversion sequence of
3478 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003479 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003481 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003482 ICS1.UserDefined.After,
3483 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003484 else
3485 Result = compareConversionFunctions(S,
3486 ICS1.UserDefined.ConversionFunction,
3487 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003488 }
3489
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003490 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003491}
3492
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003493static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3494 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3495 Qualifiers Quals;
3496 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003500 return Context.hasSameUnqualifiedType(T1, T2);
3501}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003503// Per 13.3.3.2p3, compare the given standard conversion sequences to
3504// determine if one is a proper subset of the other.
3505static ImplicitConversionSequence::CompareKind
3506compareStandardConversionSubsets(ASTContext &Context,
3507 const StandardConversionSequence& SCS1,
3508 const StandardConversionSequence& SCS2) {
3509 ImplicitConversionSequence::CompareKind Result
3510 = ImplicitConversionSequence::Indistinguishable;
3511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003513 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003514 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3515 return ImplicitConversionSequence::Better;
3516 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3517 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003519 if (SCS1.Second != SCS2.Second) {
3520 if (SCS1.Second == ICK_Identity)
3521 Result = ImplicitConversionSequence::Better;
3522 else if (SCS2.Second == ICK_Identity)
3523 Result = ImplicitConversionSequence::Worse;
3524 else
3525 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003526 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003527 return ImplicitConversionSequence::Indistinguishable;
3528
3529 if (SCS1.Third == SCS2.Third) {
3530 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3531 : ImplicitConversionSequence::Indistinguishable;
3532 }
3533
3534 if (SCS1.Third == ICK_Identity)
3535 return Result == ImplicitConversionSequence::Worse
3536 ? ImplicitConversionSequence::Indistinguishable
3537 : ImplicitConversionSequence::Better;
3538
3539 if (SCS2.Third == ICK_Identity)
3540 return Result == ImplicitConversionSequence::Better
3541 ? ImplicitConversionSequence::Indistinguishable
3542 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003544 return ImplicitConversionSequence::Indistinguishable;
3545}
3546
Douglas Gregore696ebb2011-01-26 14:52:12 +00003547/// \brief Determine whether one of the given reference bindings is better
3548/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003549static bool
3550isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3551 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003552 // C++0x [over.ics.rank]p3b4:
3553 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3554 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003556 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003558 // reference*.
3559 //
3560 // FIXME: Rvalue references. We're going rogue with the above edits,
3561 // because the semantics in the current C++0x working paper (N3225 at the
3562 // time of this writing) break the standard definition of std::forward
3563 // and std::reference_wrapper when dealing with references to functions.
3564 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003565 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3566 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3567 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
Douglas Gregore696ebb2011-01-26 14:52:12 +00003569 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3570 SCS2.IsLvalueReference) ||
3571 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003572 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003573}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003575/// CompareStandardConversionSequences - Compare two standard
3576/// conversion sequences to determine whether one is better than the
3577/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003578static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003579CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003580 const StandardConversionSequence& SCS1,
3581 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003582{
3583 // Standard conversion sequence S1 is a better conversion sequence
3584 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3585
3586 // -- S1 is a proper subsequence of S2 (comparing the conversion
3587 // sequences in the canonical form defined by 13.3.3.1.1,
3588 // excluding any Lvalue Transformation; the identity conversion
3589 // sequence is considered to be a subsequence of any
3590 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003591 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003592 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003593 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003594
3595 // -- the rank of S1 is better than the rank of S2 (by the rules
3596 // defined below), or, if not that,
3597 ImplicitConversionRank Rank1 = SCS1.getRank();
3598 ImplicitConversionRank Rank2 = SCS2.getRank();
3599 if (Rank1 < Rank2)
3600 return ImplicitConversionSequence::Better;
3601 else if (Rank2 < Rank1)
3602 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003603
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003604 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3605 // are indistinguishable unless one of the following rules
3606 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003607
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003608 // A conversion that is not a conversion of a pointer, or
3609 // pointer to member, to bool is better than another conversion
3610 // that is such a conversion.
3611 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3612 return SCS2.isPointerConversionToBool()
3613 ? ImplicitConversionSequence::Better
3614 : ImplicitConversionSequence::Worse;
3615
Douglas Gregor5c407d92008-10-23 00:40:37 +00003616 // C++ [over.ics.rank]p4b2:
3617 //
3618 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003619 // conversion of B* to A* is better than conversion of B* to
3620 // void*, and conversion of A* to void* is better than conversion
3621 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003622 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003623 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003624 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003625 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003626 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3627 // Exactly one of the conversion sequences is a conversion to
3628 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003629 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3630 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003631 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3632 // Neither conversion sequence converts to a void pointer; compare
3633 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003634 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003635 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003636 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003637 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3638 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003639 // Both conversion sequences are conversions to void
3640 // pointers. Compare the source types to determine if there's an
3641 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003642 QualType FromType1 = SCS1.getFromType();
3643 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003644
3645 // Adjust the types we're converting from via the array-to-pointer
3646 // conversion, if we need to.
3647 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003648 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003649 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003650 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003651
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003652 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3653 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003654
Richard Smith0f59cb32015-12-18 21:45:41 +00003655 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003656 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003657 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003658 return ImplicitConversionSequence::Worse;
3659
3660 // Objective-C++: If one interface is more specific than the
3661 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003662 const ObjCObjectPointerType* FromObjCPtr1
3663 = FromType1->getAs<ObjCObjectPointerType>();
3664 const ObjCObjectPointerType* FromObjCPtr2
3665 = FromType2->getAs<ObjCObjectPointerType>();
3666 if (FromObjCPtr1 && FromObjCPtr2) {
3667 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3668 FromObjCPtr2);
3669 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3670 FromObjCPtr1);
3671 if (AssignLeft != AssignRight) {
3672 return AssignLeft? ImplicitConversionSequence::Better
3673 : ImplicitConversionSequence::Worse;
3674 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003675 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003676 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003677
3678 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3679 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003680 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003681 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003682 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003683
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003684 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003685 // Check for a better reference binding based on the kind of bindings.
3686 if (isBetterReferenceBindingKind(SCS1, SCS2))
3687 return ImplicitConversionSequence::Better;
3688 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3689 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690
Sebastian Redlb28b4072009-03-22 23:49:27 +00003691 // C++ [over.ics.rank]p3b4:
3692 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3693 // which the references refer are the same type except for
3694 // top-level cv-qualifiers, and the type to which the reference
3695 // initialized by S2 refers is more cv-qualified than the type
3696 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003697 QualType T1 = SCS1.getToType(2);
3698 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003699 T1 = S.Context.getCanonicalType(T1);
3700 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003701 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003702 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3703 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003704 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003705 // Objective-C++ ARC: If the references refer to objects with different
3706 // lifetimes, prefer bindings that don't change lifetime.
3707 if (SCS1.ObjCLifetimeConversionBinding !=
3708 SCS2.ObjCLifetimeConversionBinding) {
3709 return SCS1.ObjCLifetimeConversionBinding
3710 ? ImplicitConversionSequence::Worse
3711 : ImplicitConversionSequence::Better;
3712 }
3713
Chandler Carruth8e543b32010-12-12 08:17:55 +00003714 // If the type is an array type, promote the element qualifiers to the
3715 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003716 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003717 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003718 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003719 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003720 if (T2.isMoreQualifiedThan(T1))
3721 return ImplicitConversionSequence::Better;
3722 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003723 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003724 }
3725 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726
Francois Pichet08d2fa02011-09-18 21:37:37 +00003727 // In Microsoft mode, prefer an integral conversion to a
3728 // floating-to-integral conversion if the integral conversion
3729 // is between types of the same size.
3730 // For example:
3731 // void f(float);
3732 // void f(int);
3733 // int main {
3734 // long a;
3735 // f(a);
3736 // }
3737 // Here, MSVC will call f(int) instead of generating a compile error
3738 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003739 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3740 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003741 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003742 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003743 return ImplicitConversionSequence::Better;
3744
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003745 return ImplicitConversionSequence::Indistinguishable;
3746}
3747
3748/// CompareQualificationConversions - Compares two standard conversion
3749/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003750/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003751static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003752CompareQualificationConversions(Sema &S,
3753 const StandardConversionSequence& SCS1,
3754 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003755 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003756 // -- S1 and S2 differ only in their qualification conversion and
3757 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3758 // cv-qualification signature of type T1 is a proper subset of
3759 // the cv-qualification signature of type T2, and S1 is not the
3760 // deprecated string literal array-to-pointer conversion (4.2).
3761 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3762 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3763 return ImplicitConversionSequence::Indistinguishable;
3764
3765 // FIXME: the example in the standard doesn't use a qualification
3766 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003767 QualType T1 = SCS1.getToType(2);
3768 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003769 T1 = S.Context.getCanonicalType(T1);
3770 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003771 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003772 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3773 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003774
3775 // If the types are the same, we won't learn anything by unwrapped
3776 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003777 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003778 return ImplicitConversionSequence::Indistinguishable;
3779
Chandler Carruth607f38e2009-12-29 07:16:59 +00003780 // If the type is an array type, promote the element qualifiers to the type
3781 // for comparison.
3782 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003783 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003784 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003785 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003786
Mike Stump11289f42009-09-09 15:08:12 +00003787 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003788 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003789
3790 // Objective-C++ ARC:
3791 // Prefer qualification conversions not involving a change in lifetime
3792 // to qualification conversions that do not change lifetime.
3793 if (SCS1.QualificationIncludesObjCLifetime !=
3794 SCS2.QualificationIncludesObjCLifetime) {
3795 Result = SCS1.QualificationIncludesObjCLifetime
3796 ? ImplicitConversionSequence::Worse
3797 : ImplicitConversionSequence::Better;
3798 }
3799
John McCall5c32be02010-08-24 20:38:10 +00003800 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003801 // Within each iteration of the loop, we check the qualifiers to
3802 // determine if this still looks like a qualification
3803 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003804 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003805 // until there are no more pointers or pointers-to-members left
3806 // to unwrap. This essentially mimics what
3807 // IsQualificationConversion does, but here we're checking for a
3808 // strict subset of qualifiers.
3809 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3810 // The qualifiers are the same, so this doesn't tell us anything
3811 // about how the sequences rank.
3812 ;
3813 else if (T2.isMoreQualifiedThan(T1)) {
3814 // T1 has fewer qualifiers, so it could be the better sequence.
3815 if (Result == ImplicitConversionSequence::Worse)
3816 // Neither has qualifiers that are a subset of the other's
3817 // qualifiers.
3818 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003819
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003820 Result = ImplicitConversionSequence::Better;
3821 } else if (T1.isMoreQualifiedThan(T2)) {
3822 // T2 has fewer qualifiers, so it could be the better sequence.
3823 if (Result == ImplicitConversionSequence::Better)
3824 // Neither has qualifiers that are a subset of the other's
3825 // qualifiers.
3826 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003827
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003828 Result = ImplicitConversionSequence::Worse;
3829 } else {
3830 // Qualifiers are disjoint.
3831 return ImplicitConversionSequence::Indistinguishable;
3832 }
3833
3834 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003835 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003836 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003837 }
3838
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003839 // Check that the winning standard conversion sequence isn't using
3840 // the deprecated string literal array to pointer conversion.
3841 switch (Result) {
3842 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003843 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003844 Result = ImplicitConversionSequence::Indistinguishable;
3845 break;
3846
3847 case ImplicitConversionSequence::Indistinguishable:
3848 break;
3849
3850 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003851 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003852 Result = ImplicitConversionSequence::Indistinguishable;
3853 break;
3854 }
3855
3856 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003857}
3858
Douglas Gregor5c407d92008-10-23 00:40:37 +00003859/// CompareDerivedToBaseConversions - Compares two standard conversion
3860/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003861/// various kinds of derived-to-base conversions (C++
3862/// [over.ics.rank]p4b3). As part of these checks, we also look at
3863/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003864static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003865CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003866 const StandardConversionSequence& SCS1,
3867 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003868 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003869 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003870 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003871 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003872
3873 // Adjust the types we're converting from via the array-to-pointer
3874 // conversion, if we need to.
3875 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003876 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003877 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003878 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003879
3880 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003881 FromType1 = S.Context.getCanonicalType(FromType1);
3882 ToType1 = S.Context.getCanonicalType(ToType1);
3883 FromType2 = S.Context.getCanonicalType(FromType2);
3884 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003885
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003886 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003887 //
3888 // If class B is derived directly or indirectly from class A and
3889 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003890 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003891 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003892 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003893 SCS2.Second == ICK_Pointer_Conversion &&
3894 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3895 FromType1->isPointerType() && FromType2->isPointerType() &&
3896 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003897 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003898 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003899 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003900 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003901 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003902 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003903 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003904 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003905
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003906 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003907 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003908 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003909 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003910 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003911 return ImplicitConversionSequence::Worse;
3912 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003913
3914 // -- conversion of B* to A* is better than conversion of C* to A*,
3915 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003916 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003917 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003918 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003919 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003920 }
3921 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3922 SCS2.Second == ICK_Pointer_Conversion) {
3923 const ObjCObjectPointerType *FromPtr1
3924 = FromType1->getAs<ObjCObjectPointerType>();
3925 const ObjCObjectPointerType *FromPtr2
3926 = FromType2->getAs<ObjCObjectPointerType>();
3927 const ObjCObjectPointerType *ToPtr1
3928 = ToType1->getAs<ObjCObjectPointerType>();
3929 const ObjCObjectPointerType *ToPtr2
3930 = ToType2->getAs<ObjCObjectPointerType>();
3931
3932 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3933 // Apply the same conversion ranking rules for Objective-C pointer types
3934 // that we do for C++ pointers to class types. However, we employ the
3935 // Objective-C pseudo-subtyping relationship used for assignment of
3936 // Objective-C pointer types.
3937 bool FromAssignLeft
3938 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3939 bool FromAssignRight
3940 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3941 bool ToAssignLeft
3942 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3943 bool ToAssignRight
3944 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3945
3946 // A conversion to an a non-id object pointer type or qualified 'id'
3947 // type is better than a conversion to 'id'.
3948 if (ToPtr1->isObjCIdType() &&
3949 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3950 return ImplicitConversionSequence::Worse;
3951 if (ToPtr2->isObjCIdType() &&
3952 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3953 return ImplicitConversionSequence::Better;
3954
3955 // A conversion to a non-id object pointer type is better than a
3956 // conversion to a qualified 'id' type
3957 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3958 return ImplicitConversionSequence::Worse;
3959 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3960 return ImplicitConversionSequence::Better;
3961
3962 // A conversion to an a non-Class object pointer type or qualified 'Class'
3963 // type is better than a conversion to 'Class'.
3964 if (ToPtr1->isObjCClassType() &&
3965 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3966 return ImplicitConversionSequence::Worse;
3967 if (ToPtr2->isObjCClassType() &&
3968 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3969 return ImplicitConversionSequence::Better;
3970
3971 // A conversion to a non-Class object pointer type is better than a
3972 // conversion to a qualified 'Class' type.
3973 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3974 return ImplicitConversionSequence::Worse;
3975 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3976 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregor058d3de2011-01-31 18:51:41 +00003978 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3979 if (S.Context.hasSameType(FromType1, FromType2) &&
3980 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3981 (ToAssignLeft != ToAssignRight))
3982 return ToAssignLeft? ImplicitConversionSequence::Worse
3983 : ImplicitConversionSequence::Better;
3984
3985 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3986 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3987 (FromAssignLeft != FromAssignRight))
3988 return FromAssignLeft? ImplicitConversionSequence::Better
3989 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003990 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003991 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003992
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003993 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003994 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3995 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3996 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003998 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004000 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004002 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004004 ToType2->getAs<MemberPointerType>();
4005 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4006 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4007 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4008 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4009 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4010 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4011 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4012 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004013 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004014 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004015 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004016 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004017 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004018 return ImplicitConversionSequence::Better;
4019 }
4020 // conversion of B::* to C::* is better than conversion of A::* to C::*
4021 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004022 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004023 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004024 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004025 return ImplicitConversionSequence::Worse;
4026 }
4027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor5ab11652010-04-17 22:01:05 +00004029 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004030 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004031 // -- binding of an expression of type C to a reference of type
4032 // B& is better than binding an expression of type C to a
4033 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004034 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4035 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004036 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004037 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004038 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004039 return ImplicitConversionSequence::Worse;
4040 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004041
Douglas Gregor2fe98832008-11-03 19:09:14 +00004042 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004043 // -- binding of an expression of type B to a reference of type
4044 // A& is better than binding an expression of type C to a
4045 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004046 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4047 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004048 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004049 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004050 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004051 return ImplicitConversionSequence::Worse;
4052 }
4053 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004054
Douglas Gregor5c407d92008-10-23 00:40:37 +00004055 return ImplicitConversionSequence::Indistinguishable;
4056}
4057
Douglas Gregor45bb4832013-03-26 23:36:30 +00004058/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4059/// C++ class.
4060static bool isTypeValid(QualType T) {
4061 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4062 return !Record->isInvalidDecl();
4063
4064 return true;
4065}
4066
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004067/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4068/// determine whether they are reference-related,
4069/// reference-compatible, reference-compatible with added
4070/// qualification, or incompatible, for use in C++ initialization by
4071/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4072/// type, and the first type (T1) is the pointee type of the reference
4073/// type being initialized.
4074Sema::ReferenceCompareResult
4075Sema::CompareReferenceRelationship(SourceLocation Loc,
4076 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004077 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004078 bool &ObjCConversion,
4079 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004080 assert(!OrigT1->isReferenceType() &&
4081 "T1 must be the pointee type of the reference type");
4082 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4083
4084 QualType T1 = Context.getCanonicalType(OrigT1);
4085 QualType T2 = Context.getCanonicalType(OrigT2);
4086 Qualifiers T1Quals, T2Quals;
4087 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4088 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4089
4090 // C++ [dcl.init.ref]p4:
4091 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4092 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4093 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004094 DerivedToBase = false;
4095 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004096 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004097 if (UnqualT1 == UnqualT2) {
4098 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004099 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004100 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004101 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004102 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004103 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4104 UnqualT2->isObjCObjectOrInterfaceType() &&
4105 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4106 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004107 else
4108 return Ref_Incompatible;
4109
4110 // At this point, we know that T1 and T2 are reference-related (at
4111 // least).
4112
4113 // If the type is an array type, promote the element qualifiers to the type
4114 // for comparison.
4115 if (isa<ArrayType>(T1) && T1Quals)
4116 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4117 if (isa<ArrayType>(T2) && T2Quals)
4118 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4119
4120 // C++ [dcl.init.ref]p4:
4121 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4122 // reference-related to T2 and cv1 is the same cv-qualification
4123 // as, or greater cv-qualification than, cv2. For purposes of
4124 // overload resolution, cases for which cv1 is greater
4125 // cv-qualification than cv2 are identified as
4126 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004127 //
4128 // Note that we also require equivalence of Objective-C GC and address-space
4129 // qualifiers when performing these computations, so that e.g., an int in
4130 // address space 1 is not reference-compatible with an int in address
4131 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004132 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4133 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004134 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4135 ObjCLifetimeConversion = true;
4136
John McCall31168b02011-06-15 23:02:42 +00004137 T1Quals.removeObjCLifetime();
4138 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004139 }
4140
Douglas Gregord517d552011-04-28 17:56:11 +00004141 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004142 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004143 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004144 return Ref_Compatible_With_Added_Qualification;
4145 else
4146 return Ref_Related;
4147}
4148
Douglas Gregor836a7e82010-08-11 02:15:33 +00004149/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004150/// with DeclType. Return true if something definite is found.
4151static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004152FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4153 QualType DeclType, SourceLocation DeclLoc,
4154 Expr *Init, QualType T2, bool AllowRvalues,
4155 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004156 assert(T2->isRecordType() && "Can only find conversions of record types.");
4157 CXXRecordDecl *T2RecordDecl
4158 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4159
Richard Smith100b24a2014-04-17 01:52:14 +00004160 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004161 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4162 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004163 NamedDecl *D = *I;
4164 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4165 if (isa<UsingShadowDecl>(D))
4166 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4167
4168 FunctionTemplateDecl *ConvTemplate
4169 = dyn_cast<FunctionTemplateDecl>(D);
4170 CXXConversionDecl *Conv;
4171 if (ConvTemplate)
4172 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4173 else
4174 Conv = cast<CXXConversionDecl>(D);
4175
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004177 // explicit conversions, skip it.
4178 if (!AllowExplicit && Conv->isExplicit())
4179 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180
Douglas Gregor836a7e82010-08-11 02:15:33 +00004181 if (AllowRvalues) {
4182 bool DerivedToBase = false;
4183 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004184 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004185
4186 // If we are initializing an rvalue reference, don't permit conversion
4187 // functions that return lvalues.
4188 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4189 const ReferenceType *RefType
4190 = Conv->getConversionType()->getAs<LValueReferenceType>();
4191 if (RefType && !RefType->getPointeeType()->isFunctionType())
4192 continue;
4193 }
4194
Douglas Gregor836a7e82010-08-11 02:15:33 +00004195 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004196 S.CompareReferenceRelationship(
4197 DeclLoc,
4198 Conv->getConversionType().getNonReferenceType()
4199 .getUnqualifiedType(),
4200 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004201 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004202 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004203 continue;
4204 } else {
4205 // If the conversion function doesn't return a reference type,
4206 // it can't be considered for this conversion. An rvalue reference
4207 // is only acceptable if its referencee is a function type.
4208
4209 const ReferenceType *RefType =
4210 Conv->getConversionType()->getAs<ReferenceType>();
4211 if (!RefType ||
4212 (!RefType->isLValueReferenceType() &&
4213 !RefType->getPointeeType()->isFunctionType()))
4214 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004216
Douglas Gregor836a7e82010-08-11 02:15:33 +00004217 if (ConvTemplate)
4218 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004219 Init, DeclType, CandidateSet,
4220 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004221 else
4222 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004223 DeclType, CandidateSet,
4224 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004225 }
4226
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004227 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4228
Sebastian Redld92badf2010-06-30 18:13:39 +00004229 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004230 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004231 case OR_Success:
4232 // C++ [over.ics.ref]p1:
4233 //
4234 // [...] If the parameter binds directly to the result of
4235 // applying a conversion function to the argument
4236 // expression, the implicit conversion sequence is a
4237 // user-defined conversion sequence (13.3.3.1.2), with the
4238 // second standard conversion sequence either an identity
4239 // conversion or, if the conversion function returns an
4240 // entity of a type that is a derived class of the parameter
4241 // type, a derived-to-base Conversion.
4242 if (!Best->FinalConversion.DirectBinding)
4243 return false;
4244
4245 ICS.setUserDefined();
4246 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4247 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004248 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004249 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004250 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004251 ICS.UserDefined.EllipsisConversion = false;
4252 assert(ICS.UserDefined.After.ReferenceBinding &&
4253 ICS.UserDefined.After.DirectBinding &&
4254 "Expected a direct reference binding!");
4255 return true;
4256
4257 case OR_Ambiguous:
4258 ICS.setAmbiguous();
4259 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4260 Cand != CandidateSet.end(); ++Cand)
4261 if (Cand->Viable)
4262 ICS.Ambiguous.addConversion(Cand->Function);
4263 return true;
4264
4265 case OR_No_Viable_Function:
4266 case OR_Deleted:
4267 // There was no suitable conversion, or we found a deleted
4268 // conversion; continue with other checks.
4269 return false;
4270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
David Blaikie8a40f702012-01-17 06:56:22 +00004272 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004273}
4274
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004275/// \brief Compute an implicit conversion sequence for reference
4276/// initialization.
4277static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004278TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004279 SourceLocation DeclLoc,
4280 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004281 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004282 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4283
4284 // Most paths end in a failed conversion.
4285 ImplicitConversionSequence ICS;
4286 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4287
4288 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4289 QualType T2 = Init->getType();
4290
4291 // If the initializer is the address of an overloaded function, try
4292 // to resolve the overloaded function. If all goes well, T2 is the
4293 // type of the resulting function.
4294 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4295 DeclAccessPair Found;
4296 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4297 false, Found))
4298 T2 = Fn->getType();
4299 }
4300
4301 // Compute some basic properties of the types and the initializer.
4302 bool isRValRef = DeclType->isRValueReferenceType();
4303 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004304 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004305 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004306 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004307 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004308 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004309 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004311
Sebastian Redld92badf2010-06-30 18:13:39 +00004312 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004313 // A reference to type "cv1 T1" is initialized by an expression
4314 // of type "cv2 T2" as follows:
4315
Sebastian Redld92badf2010-06-30 18:13:39 +00004316 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004317 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004318 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4319 // reference-compatible with "cv2 T2," or
4320 //
4321 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4322 if (InitCategory.isLValue() &&
4323 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004324 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004325 // When a parameter of reference type binds directly (8.5.3)
4326 // to an argument expression, the implicit conversion sequence
4327 // is the identity conversion, unless the argument expression
4328 // has a type that is a derived class of the parameter type,
4329 // in which case the implicit conversion sequence is a
4330 // derived-to-base Conversion (13.3.3.1).
4331 ICS.setStandard();
4332 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004333 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4334 : ObjCConversion? ICK_Compatible_Conversion
4335 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004336 ICS.Standard.Third = ICK_Identity;
4337 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4338 ICS.Standard.setToType(0, T2);
4339 ICS.Standard.setToType(1, T1);
4340 ICS.Standard.setToType(2, T1);
4341 ICS.Standard.ReferenceBinding = true;
4342 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004343 ICS.Standard.IsLvalueReference = !isRValRef;
4344 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4345 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004346 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004347 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004348 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004349 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004350
Sebastian Redld92badf2010-06-30 18:13:39 +00004351 // Nothing more to do: the inaccessibility/ambiguity check for
4352 // derived-to-base conversions is suppressed when we're
4353 // computing the implicit conversion sequence (C++
4354 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004355 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004356 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004357
Sebastian Redld92badf2010-06-30 18:13:39 +00004358 // -- has a class type (i.e., T2 is a class type), where T1 is
4359 // not reference-related to T2, and can be implicitly
4360 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4361 // is reference-compatible with "cv3 T3" 92) (this
4362 // conversion is selected by enumerating the applicable
4363 // conversion functions (13.3.1.6) and choosing the best
4364 // one through overload resolution (13.3)),
4365 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004366 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004367 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004368 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4369 Init, T2, /*AllowRvalues=*/false,
4370 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004371 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004372 }
4373 }
4374
Sebastian Redld92badf2010-06-30 18:13:39 +00004375 // -- Otherwise, the reference shall be an lvalue reference to a
4376 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004377 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004378 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004379 return ICS;
4380
Douglas Gregorf143cd52011-01-24 16:14:37 +00004381 // -- If the initializer expression
4382 //
4383 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004384 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004385 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4386 (InitCategory.isXValue() ||
4387 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4388 (InitCategory.isLValue() && T2->isFunctionType()))) {
4389 ICS.setStandard();
4390 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004392 : ObjCConversion? ICK_Compatible_Conversion
4393 : ICK_Identity;
4394 ICS.Standard.Third = ICK_Identity;
4395 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4396 ICS.Standard.setToType(0, T2);
4397 ICS.Standard.setToType(1, T1);
4398 ICS.Standard.setToType(2, T1);
4399 ICS.Standard.ReferenceBinding = true;
4400 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4401 // binding unless we're binding to a class prvalue.
4402 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4403 // allow the use of rvalue references in C++98/03 for the benefit of
4404 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004406 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004407 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004408 ICS.Standard.IsLvalueReference = !isRValRef;
4409 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004411 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004412 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004413 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004414 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004416 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregorf143cd52011-01-24 16:14:37 +00004418 // -- has a class type (i.e., T2 is a class type), where T1 is not
4419 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420 // an xvalue, class prvalue, or function lvalue of type
4421 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004422 // "cv3 T3",
4423 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004425 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004427 // class subobject).
4428 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004429 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004430 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4431 Init, T2, /*AllowRvalues=*/true,
4432 AllowExplicit)) {
4433 // In the second case, if the reference is an rvalue reference
4434 // and the second standard conversion sequence of the
4435 // user-defined conversion sequence includes an lvalue-to-rvalue
4436 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004438 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4439 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4440
Douglas Gregor95273c32011-01-21 16:36:05 +00004441 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Richard Smith19172c42014-07-14 02:28:44 +00004444 // A temporary of function type cannot be created; don't even try.
4445 if (T1->isFunctionType())
4446 return ICS;
4447
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004448 // -- Otherwise, a temporary of type "cv1 T1" is created and
4449 // initialized from the initializer expression using the
4450 // rules for a non-reference copy initialization (8.5). The
4451 // reference is then bound to the temporary. If T1 is
4452 // reference-related to T2, cv1 must be the same
4453 // cv-qualification as, or greater cv-qualification than,
4454 // cv2; otherwise, the program is ill-formed.
4455 if (RefRelationship == Sema::Ref_Related) {
4456 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4457 // we would be reference-compatible or reference-compatible with
4458 // added qualification. But that wasn't the case, so the reference
4459 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004460 //
4461 // Note that we only want to check address spaces and cvr-qualifiers here.
4462 // ObjC GC and lifetime qualifiers aren't important.
4463 Qualifiers T1Quals = T1.getQualifiers();
4464 Qualifiers T2Quals = T2.getQualifiers();
4465 T1Quals.removeObjCGCAttr();
4466 T1Quals.removeObjCLifetime();
4467 T2Quals.removeObjCGCAttr();
4468 T2Quals.removeObjCLifetime();
4469 if (!T1Quals.compatiblyIncludes(T2Quals))
4470 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004471 }
4472
4473 // If at least one of the types is a class type, the types are not
4474 // related, and we aren't allowed any user conversions, the
4475 // reference binding fails. This case is important for breaking
4476 // recursion, since TryImplicitConversion below will attempt to
4477 // create a temporary through the use of a copy constructor.
4478 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4479 (T1->isRecordType() || T2->isRecordType()))
4480 return ICS;
4481
Douglas Gregorcba72b12011-01-21 05:18:22 +00004482 // If T1 is reference-related to T2 and the reference is an rvalue
4483 // reference, the initializer expression shall not be an lvalue.
4484 if (RefRelationship >= Sema::Ref_Related &&
4485 isRValRef && Init->Classify(S.Context).isLValue())
4486 return ICS;
4487
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004488 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004489 // When a parameter of reference type is not bound directly to
4490 // an argument expression, the conversion sequence is the one
4491 // required to convert the argument expression to the
4492 // underlying type of the reference according to
4493 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4494 // to copy-initializing a temporary of the underlying type with
4495 // the argument expression. Any difference in top-level
4496 // cv-qualification is subsumed by the initialization itself
4497 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004498 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4499 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004500 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004501 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004502 /*AllowObjCWritebackConversion=*/false,
4503 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004504
4505 // Of course, that's still a reference binding.
4506 if (ICS.isStandard()) {
4507 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004508 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004509 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004510 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004511 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004512 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004513 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004514 const ReferenceType *LValRefType =
4515 ICS.UserDefined.ConversionFunction->getReturnType()
4516 ->getAs<LValueReferenceType>();
4517
4518 // C++ [over.ics.ref]p3:
4519 // Except for an implicit object parameter, for which see 13.3.1, a
4520 // standard conversion sequence cannot be formed if it requires [...]
4521 // binding an rvalue reference to an lvalue other than a function
4522 // lvalue.
4523 // Note that the function case is not possible here.
4524 if (DeclType->isRValueReferenceType() && LValRefType) {
4525 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4526 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4527 // reference to an rvalue!
4528 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4529 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004530 }
Richard Smith19172c42014-07-14 02:28:44 +00004531
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004532 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004533 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004534 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004535 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4536 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004537 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4538 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004539 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004540
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004541 return ICS;
4542}
4543
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004544static ImplicitConversionSequence
4545TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4546 bool SuppressUserConversions,
4547 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004548 bool AllowObjCWritebackConversion,
4549 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004550
4551/// TryListConversion - Try to copy-initialize a value of type ToType from the
4552/// initializer list From.
4553static ImplicitConversionSequence
4554TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4555 bool SuppressUserConversions,
4556 bool InOverloadResolution,
4557 bool AllowObjCWritebackConversion) {
4558 // C++11 [over.ics.list]p1:
4559 // When an argument is an initializer list, it is not an expression and
4560 // special rules apply for converting it to a parameter type.
4561
4562 ImplicitConversionSequence Result;
4563 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4564
Sebastian Redl09edce02012-01-23 22:09:39 +00004565 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004566 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004567 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004568 return Result;
4569
Larisse Voufo19d08672015-01-27 18:47:05 +00004570 // Per DR1467:
4571 // If the parameter type is a class X and the initializer list has a single
4572 // element of type cv U, where U is X or a class derived from X, the
4573 // implicit conversion sequence is the one required to convert the element
4574 // to the parameter type.
4575 //
4576 // Otherwise, if the parameter type is a character array [... ]
4577 // and the initializer list has a single element that is an
4578 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4579 // implicit conversion sequence is the identity conversion.
4580 if (From->getNumInits() == 1) {
4581 if (ToType->isRecordType()) {
4582 QualType InitType = From->getInit(0)->getType();
4583 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004584 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004585 return TryCopyInitialization(S, From->getInit(0), ToType,
4586 SuppressUserConversions,
4587 InOverloadResolution,
4588 AllowObjCWritebackConversion);
4589 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004590 // FIXME: Check the other conditions here: array of character type,
4591 // initializer is a string literal.
4592 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004593 InitializedEntity Entity =
4594 InitializedEntity::InitializeParameter(S.Context, ToType,
4595 /*Consumed=*/false);
4596 if (S.CanPerformCopyInitialization(Entity, From)) {
4597 Result.setStandard();
4598 Result.Standard.setAsIdentityConversion();
4599 Result.Standard.setFromType(ToType);
4600 Result.Standard.setAllToTypes(ToType);
4601 return Result;
4602 }
4603 }
4604 }
4605
4606 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004607 // C++11 [over.ics.list]p2:
4608 // If the parameter type is std::initializer_list<X> or "array of X" and
4609 // all the elements can be implicitly converted to X, the implicit
4610 // conversion sequence is the worst conversion necessary to convert an
4611 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004612 //
4613 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004614 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004615 // list has exactly N elements or if it has fewer than N elements and X is
4616 // default-constructible, and if all the elements of the initializer list
4617 // can be implicitly converted to X, the implicit conversion sequence is
4618 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004619 //
4620 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004621 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004622 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004623 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004624 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004625 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004626 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004627 if (!X.isNull()) {
4628 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4629 Expr *Init = From->getInit(i);
4630 ImplicitConversionSequence ICS =
4631 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4632 InOverloadResolution,
4633 AllowObjCWritebackConversion);
4634 // If a single element isn't convertible, fail.
4635 if (ICS.isBad()) {
4636 Result = ICS;
4637 break;
4638 }
4639 // Otherwise, look for the worst conversion.
4640 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004641 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4642 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004643 ImplicitConversionSequence::Worse)
4644 Result = ICS;
4645 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004646
4647 // For an empty list, we won't have computed any conversion sequence.
4648 // Introduce the identity conversion sequence.
4649 if (From->getNumInits() == 0) {
4650 Result.setStandard();
4651 Result.Standard.setAsIdentityConversion();
4652 Result.Standard.setFromType(ToType);
4653 Result.Standard.setAllToTypes(ToType);
4654 }
4655
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004656 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004657 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004658 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004659
Larisse Voufo19d08672015-01-27 18:47:05 +00004660 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004661 // C++11 [over.ics.list]p3:
4662 // Otherwise, if the parameter is a non-aggregate class X and overload
4663 // resolution chooses a single best constructor [...] the implicit
4664 // conversion sequence is a user-defined conversion sequence. If multiple
4665 // constructors are viable but none is better than the others, the
4666 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004667 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4668 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004669 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4670 /*AllowExplicit=*/false,
4671 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004672 AllowObjCWritebackConversion,
4673 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004674 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004675
Larisse Voufo19d08672015-01-27 18:47:05 +00004676 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004677 // C++11 [over.ics.list]p4:
4678 // Otherwise, if the parameter has an aggregate type which can be
4679 // initialized from the initializer list [...] the implicit conversion
4680 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004681 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004682 // Type is an aggregate, argument is an init list. At this point it comes
4683 // down to checking whether the initialization works.
4684 // FIXME: Find out whether this parameter is consumed or not.
4685 InitializedEntity Entity =
4686 InitializedEntity::InitializeParameter(S.Context, ToType,
4687 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004688 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004689 Result.setUserDefined();
4690 Result.UserDefined.Before.setAsIdentityConversion();
4691 // Initializer lists don't have a type.
4692 Result.UserDefined.Before.setFromType(QualType());
4693 Result.UserDefined.Before.setAllToTypes(QualType());
4694
4695 Result.UserDefined.After.setAsIdentityConversion();
4696 Result.UserDefined.After.setFromType(ToType);
4697 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004698 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004699 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004700 return Result;
4701 }
4702
Larisse Voufo19d08672015-01-27 18:47:05 +00004703 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004704 // C++11 [over.ics.list]p5:
4705 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004706 if (ToType->isReferenceType()) {
4707 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4708 // mention initializer lists in any way. So we go by what list-
4709 // initialization would do and try to extrapolate from that.
4710
4711 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4712
4713 // If the initializer list has a single element that is reference-related
4714 // to the parameter type, we initialize the reference from that.
4715 if (From->getNumInits() == 1) {
4716 Expr *Init = From->getInit(0);
4717
4718 QualType T2 = Init->getType();
4719
4720 // If the initializer is the address of an overloaded function, try
4721 // to resolve the overloaded function. If all goes well, T2 is the
4722 // type of the resulting function.
4723 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4724 DeclAccessPair Found;
4725 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4726 Init, ToType, false, Found))
4727 T2 = Fn->getType();
4728 }
4729
4730 // Compute some basic properties of the types and the initializer.
4731 bool dummy1 = false;
4732 bool dummy2 = false;
4733 bool dummy3 = false;
4734 Sema::ReferenceCompareResult RefRelationship
4735 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4736 dummy2, dummy3);
4737
Richard Smith4d2bbd72013-09-06 01:22:42 +00004738 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004739 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4740 SuppressUserConversions,
4741 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004742 }
Sebastian Redldf888642011-12-03 14:54:30 +00004743 }
4744
4745 // Otherwise, we bind the reference to a temporary created from the
4746 // initializer list.
4747 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4748 InOverloadResolution,
4749 AllowObjCWritebackConversion);
4750 if (Result.isFailure())
4751 return Result;
4752 assert(!Result.isEllipsis() &&
4753 "Sub-initialization cannot result in ellipsis conversion.");
4754
4755 // Can we even bind to a temporary?
4756 if (ToType->isRValueReferenceType() ||
4757 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4758 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4759 Result.UserDefined.After;
4760 SCS.ReferenceBinding = true;
4761 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4762 SCS.BindsToRvalue = true;
4763 SCS.BindsToFunctionLvalue = false;
4764 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4765 SCS.ObjCLifetimeConversionBinding = false;
4766 } else
4767 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4768 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004769 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004770 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004771
Larisse Voufo19d08672015-01-27 18:47:05 +00004772 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004773 // C++11 [over.ics.list]p6:
4774 // Otherwise, if the parameter type is not a class:
4775 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004776 // - if the initializer list has one element that is not itself an
4777 // initializer list, the implicit conversion sequence is the one
4778 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004779 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004780 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004781 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4782 SuppressUserConversions,
4783 InOverloadResolution,
4784 AllowObjCWritebackConversion);
4785 // - if the initializer list has no elements, the implicit conversion
4786 // sequence is the identity conversion.
4787 else if (NumInits == 0) {
4788 Result.setStandard();
4789 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004790 Result.Standard.setFromType(ToType);
4791 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004792 }
4793 return Result;
4794 }
4795
Larisse Voufo19d08672015-01-27 18:47:05 +00004796 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004797 // C++11 [over.ics.list]p7:
4798 // In all cases other than those enumerated above, no conversion is possible
4799 return Result;
4800}
4801
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004802/// TryCopyInitialization - Try to copy-initialize a value of type
4803/// ToType from the expression From. Return the implicit conversion
4804/// sequence required to pass this argument, which may be a bad
4805/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004806/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004807/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004808static ImplicitConversionSequence
4809TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004811 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004812 bool AllowObjCWritebackConversion,
4813 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004814 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4815 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4816 InOverloadResolution,AllowObjCWritebackConversion);
4817
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004818 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004819 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004820 /*FIXME:*/From->getLocStart(),
4821 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004822 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004823
John McCall5c32be02010-08-24 20:38:10 +00004824 return TryImplicitConversion(S, From, ToType,
4825 SuppressUserConversions,
4826 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004827 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004828 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004829 AllowObjCWritebackConversion,
4830 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004831}
4832
Anna Zaks1b068122011-07-28 19:46:48 +00004833static bool TryCopyInitialization(const CanQualType FromQTy,
4834 const CanQualType ToQTy,
4835 Sema &S,
4836 SourceLocation Loc,
4837 ExprValueKind FromVK) {
4838 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4839 ImplicitConversionSequence ICS =
4840 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4841
4842 return !ICS.isBad();
4843}
4844
Douglas Gregor436424c2008-11-18 23:14:02 +00004845/// TryObjectArgumentInitialization - Try to initialize the object
4846/// parameter of the given member function (@c Method) from the
4847/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004848static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004849TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004850 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004851 CXXMethodDecl *Method,
4852 CXXRecordDecl *ActingContext) {
4853 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004854 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4855 // const volatile object.
4856 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4857 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004858 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004859
4860 // Set up the conversion sequence as a "bad" conversion, to allow us
4861 // to exit early.
4862 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004863
4864 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004865 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004866 FromType = PT->getPointeeType();
4867
Douglas Gregor02824322011-01-26 19:30:28 +00004868 // When we had a pointer, it's implicitly dereferenced, so we
4869 // better have an lvalue.
4870 assert(FromClassification.isLValue());
4871 }
4872
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004873 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004874
Douglas Gregor02824322011-01-26 19:30:28 +00004875 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004877 // parameter is
4878 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004879 // - "lvalue reference to cv X" for functions declared without a
4880 // ref-qualifier or with the & ref-qualifier
4881 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004882 // ref-qualifier
4883 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004885 // cv-qualification on the member function declaration.
4886 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004888 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004889 // (C++ [over.match.funcs]p5). We perform a simplified version of
4890 // reference binding here, that allows class rvalues to bind to
4891 // non-constant references.
4892
Douglas Gregor02824322011-01-26 19:30:28 +00004893 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004894 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004896 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004897 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004898 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004899 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004900 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004901 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004902
4903 // Check that we have either the same type or a derived type. It
4904 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004905 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004906 ImplicitConversionKind SecondKind;
4907 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4908 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004909 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004910 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004911 else {
John McCall65eb8792010-02-25 01:37:24 +00004912 ICS.setBad(BadConversionSequence::unrelated_class,
4913 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004914 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004915 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004916
Douglas Gregor02824322011-01-26 19:30:28 +00004917 // Check the ref-qualifier.
4918 switch (Method->getRefQualifier()) {
4919 case RQ_None:
4920 // Do nothing; we don't care about lvalueness or rvalueness.
4921 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregor02824322011-01-26 19:30:28 +00004923 case RQ_LValue:
4924 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4925 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004927 ImplicitParamType);
4928 return ICS;
4929 }
4930 break;
4931
4932 case RQ_RValue:
4933 if (!FromClassification.isRValue()) {
4934 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004936 ImplicitParamType);
4937 return ICS;
4938 }
4939 break;
4940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Douglas Gregor436424c2008-11-18 23:14:02 +00004942 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004943 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004944 ICS.Standard.setAsIdentityConversion();
4945 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004946 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004947 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004948 ICS.Standard.ReferenceBinding = true;
4949 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004950 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004951 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004952 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4953 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4954 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004955 return ICS;
4956}
4957
4958/// PerformObjectArgumentInitialization - Perform initialization of
4959/// the implicit object parameter for the given Method with the given
4960/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004961ExprResult
4962Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004964 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004965 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004966 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004967 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004968 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004969
Douglas Gregor02824322011-01-26 19:30:28 +00004970 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004971 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004972 FromRecordType = PT->getPointeeType();
4973 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004974 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004975 } else {
4976 FromRecordType = From->getType();
4977 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004978 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004979 }
4980
John McCall6e9f8f62009-12-03 04:06:58 +00004981 // Note that we always use the true parent context when performing
4982 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004983 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004984 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4985 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004986 if (ICS.isBad()) {
4987 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4988 Qualifiers FromQs = FromRecordType.getQualifiers();
4989 Qualifiers ToQs = DestType.getQualifiers();
4990 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4991 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004992 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004993 diag::err_member_function_call_bad_cvr)
4994 << Method->getDeclName() << FromRecordType << (CVR - 1)
4995 << From->getSourceRange();
4996 Diag(Method->getLocation(), diag::note_previous_decl)
4997 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004998 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004999 }
5000 }
5001
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005002 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005003 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005004 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005005 }
Mike Stump11289f42009-09-09 15:08:12 +00005006
John Wiegley01296292011-04-08 18:41:53 +00005007 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5008 ExprResult FromRes =
5009 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5010 if (FromRes.isInvalid())
5011 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005012 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005013 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005014
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005015 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005016 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005017 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005018 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005019}
5020
Douglas Gregor5fb53972009-01-14 15:45:31 +00005021/// TryContextuallyConvertToBool - Attempt to contextually convert the
5022/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005023static ImplicitConversionSequence
5024TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005025 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005026 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005027 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005028 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005029 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005030 /*AllowObjCWritebackConversion=*/false,
5031 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005032}
5033
5034/// PerformContextuallyConvertToBool - Perform a contextual conversion
5035/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005036ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005037 if (checkPlaceholderForOverload(*this, From))
5038 return ExprError();
5039
John McCall5c32be02010-08-24 20:38:10 +00005040 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005041 if (!ICS.isBad())
5042 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Fariborz Jahanian76197412009-11-18 18:26:29 +00005044 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005045 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005046 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005047 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005048 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005049}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050
Richard Smithf8379a02012-01-18 23:55:52 +00005051/// Check that the specified conversion is permitted in a converted constant
5052/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5053/// is acceptable.
5054static bool CheckConvertedConstantConversions(Sema &S,
5055 StandardConversionSequence &SCS) {
5056 // Since we know that the target type is an integral or unscoped enumeration
5057 // type, most conversion kinds are impossible. All possible First and Third
5058 // conversions are fine.
5059 switch (SCS.Second) {
5060 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005061 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005062 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005063 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005064 return true;
5065
5066 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005067 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005068 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5069 // conversion, so we allow it in a converted constant expression.
5070 //
5071 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5072 // a lot of popular code. We should at least add a warning for this
5073 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005074 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5075 SCS.getToType(2)->isBooleanType();
5076
Richard Smith410cc892014-11-26 03:26:53 +00005077 case ICK_Pointer_Conversion:
5078 case ICK_Pointer_Member:
5079 // C++1z: null pointer conversions and null member pointer conversions are
5080 // only permitted if the source type is std::nullptr_t.
5081 return SCS.getFromType()->isNullPtrType();
5082
5083 case ICK_Floating_Promotion:
5084 case ICK_Complex_Promotion:
5085 case ICK_Floating_Conversion:
5086 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005087 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005088 case ICK_Compatible_Conversion:
5089 case ICK_Derived_To_Base:
5090 case ICK_Vector_Conversion:
5091 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005092 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005093 case ICK_Block_Pointer_Conversion:
5094 case ICK_TransparentUnionConversion:
5095 case ICK_Writeback_Conversion:
5096 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005097 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005098 return false;
5099
5100 case ICK_Lvalue_To_Rvalue:
5101 case ICK_Array_To_Pointer:
5102 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005103 llvm_unreachable("found a first conversion kind in Second");
5104
Richard Smithf8379a02012-01-18 23:55:52 +00005105 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005106 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005107
5108 case ICK_Num_Conversion_Kinds:
5109 break;
5110 }
5111
5112 llvm_unreachable("unknown conversion kind");
5113}
5114
5115/// CheckConvertedConstantExpression - Check that the expression From is a
5116/// converted constant expression of type T, perform the conversion and produce
5117/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005118static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5119 QualType T, APValue &Value,
5120 Sema::CCEKind CCE,
5121 bool RequireInt) {
5122 assert(S.getLangOpts().CPlusPlus11 &&
5123 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005124
Richard Smith410cc892014-11-26 03:26:53 +00005125 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005126 return ExprError();
5127
Richard Smith410cc892014-11-26 03:26:53 +00005128 // C++1z [expr.const]p3:
5129 // A converted constant expression of type T is an expression,
5130 // implicitly converted to type T, where the converted
5131 // expression is a constant expression and the implicit conversion
5132 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005133 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005134 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005135 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005136 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005137 /*AllowObjcWritebackConversion=*/false,
5138 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005139 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005140 switch (ICS.getKind()) {
5141 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005142 SCS = &ICS.Standard;
5143 break;
5144 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005145 // We are converting to a non-class type, so the Before sequence
5146 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005147 SCS = &ICS.UserDefined.After;
5148 break;
5149 case ImplicitConversionSequence::AmbiguousConversion:
5150 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005151 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5152 return S.Diag(From->getLocStart(),
5153 diag::err_typecheck_converted_constant_expression)
5154 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005155 return ExprError();
5156
5157 case ImplicitConversionSequence::EllipsisConversion:
5158 llvm_unreachable("ellipsis conversion in converted constant expression");
5159 }
5160
Richard Smith410cc892014-11-26 03:26:53 +00005161 // Check that we would only use permitted conversions.
5162 if (!CheckConvertedConstantConversions(S, *SCS)) {
5163 return S.Diag(From->getLocStart(),
5164 diag::err_typecheck_converted_constant_expression_disallowed)
5165 << From->getType() << From->getSourceRange() << T;
5166 }
5167 // [...] and where the reference binding (if any) binds directly.
5168 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5169 return S.Diag(From->getLocStart(),
5170 diag::err_typecheck_converted_constant_expression_indirect)
5171 << From->getType() << From->getSourceRange() << T;
5172 }
5173
5174 ExprResult Result =
5175 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005176 if (Result.isInvalid())
5177 return Result;
5178
5179 // Check for a narrowing implicit conversion.
5180 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005181 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005182 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005183 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005184 case NK_Variable_Narrowing:
5185 // Implicit conversion to a narrower type, and the value is not a constant
5186 // expression. We'll diagnose this in a moment.
5187 case NK_Not_Narrowing:
5188 break;
5189
5190 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005191 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005192 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005193 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005194 break;
5195
5196 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005197 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005198 << CCE << /*Constant*/0 << From->getType() << T;
5199 break;
5200 }
5201
5202 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005203 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005204 Expr::EvalResult Eval;
5205 Eval.Diag = &Notes;
5206
Richard Smith410cc892014-11-26 03:26:53 +00005207 if ((T->isReferenceType()
5208 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5209 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5210 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005211 // The expression can't be folded, so we can't keep it at this position in
5212 // the AST.
5213 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005214 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005215 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005216
5217 if (Notes.empty()) {
5218 // It's a constant expression.
5219 return Result;
5220 }
Richard Smithf8379a02012-01-18 23:55:52 +00005221 }
5222
5223 // It's not a constant expression. Produce an appropriate diagnostic.
5224 if (Notes.size() == 1 &&
5225 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005226 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005227 else {
Richard Smith410cc892014-11-26 03:26:53 +00005228 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005229 << CCE << From->getSourceRange();
5230 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005231 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005232 }
Richard Smith410cc892014-11-26 03:26:53 +00005233 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005234}
5235
Richard Smith410cc892014-11-26 03:26:53 +00005236ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5237 APValue &Value, CCEKind CCE) {
5238 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5239}
5240
5241ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5242 llvm::APSInt &Value,
5243 CCEKind CCE) {
5244 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5245
5246 APValue V;
5247 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5248 if (!R.isInvalid())
5249 Value = V.getInt();
5250 return R;
5251}
5252
5253
John McCallfec112d2011-09-09 06:11:02 +00005254/// dropPointerConversions - If the given standard conversion sequence
5255/// involves any pointer conversions, remove them. This may change
5256/// the result type of the conversion sequence.
5257static void dropPointerConversion(StandardConversionSequence &SCS) {
5258 if (SCS.Second == ICK_Pointer_Conversion) {
5259 SCS.Second = ICK_Identity;
5260 SCS.Third = ICK_Identity;
5261 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5262 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005263}
John McCall5c32be02010-08-24 20:38:10 +00005264
John McCallfec112d2011-09-09 06:11:02 +00005265/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5266/// convert the expression From to an Objective-C pointer type.
5267static ImplicitConversionSequence
5268TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5269 // Do an implicit conversion to 'id'.
5270 QualType Ty = S.Context.getObjCIdType();
5271 ImplicitConversionSequence ICS
5272 = TryImplicitConversion(S, From, Ty,
5273 // FIXME: Are these flags correct?
5274 /*SuppressUserConversions=*/false,
5275 /*AllowExplicit=*/true,
5276 /*InOverloadResolution=*/false,
5277 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005278 /*AllowObjCWritebackConversion=*/false,
5279 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005280
5281 // Strip off any final conversions to 'id'.
5282 switch (ICS.getKind()) {
5283 case ImplicitConversionSequence::BadConversion:
5284 case ImplicitConversionSequence::AmbiguousConversion:
5285 case ImplicitConversionSequence::EllipsisConversion:
5286 break;
5287
5288 case ImplicitConversionSequence::UserDefinedConversion:
5289 dropPointerConversion(ICS.UserDefined.After);
5290 break;
5291
5292 case ImplicitConversionSequence::StandardConversion:
5293 dropPointerConversion(ICS.Standard);
5294 break;
5295 }
5296
5297 return ICS;
5298}
5299
5300/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5301/// conversion of the expression From to an Objective-C pointer type.
5302ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005303 if (checkPlaceholderForOverload(*this, From))
5304 return ExprError();
5305
John McCall8b07ec22010-05-15 11:32:37 +00005306 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005307 ImplicitConversionSequence ICS =
5308 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005309 if (!ICS.isBad())
5310 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005311 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005312}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005313
Richard Smith8dd34252012-02-04 07:07:42 +00005314/// Determine whether the provided type is an integral type, or an enumeration
5315/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005316bool Sema::ICEConvertDiagnoser::match(QualType T) {
5317 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5318 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005319}
5320
Larisse Voufo236bec22013-06-10 06:50:24 +00005321static ExprResult
5322diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5323 Sema::ContextualImplicitConverter &Converter,
5324 QualType T, UnresolvedSetImpl &ViableConversions) {
5325
5326 if (Converter.Suppress)
5327 return ExprError();
5328
5329 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5330 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5331 CXXConversionDecl *Conv =
5332 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5333 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5334 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5335 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005336 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005337}
5338
5339static bool
5340diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5341 Sema::ContextualImplicitConverter &Converter,
5342 QualType T, bool HadMultipleCandidates,
5343 UnresolvedSetImpl &ExplicitConversions) {
5344 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5345 DeclAccessPair Found = ExplicitConversions[0];
5346 CXXConversionDecl *Conversion =
5347 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5348
5349 // The user probably meant to invoke the given explicit
5350 // conversion; use it.
5351 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5352 std::string TypeStr;
5353 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5354
5355 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5356 << FixItHint::CreateInsertion(From->getLocStart(),
5357 "static_cast<" + TypeStr + ">(")
5358 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005359 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005360 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5361
5362 // If we aren't in a SFINAE context, build a call to the
5363 // explicit conversion function.
5364 if (SemaRef.isSFINAEContext())
5365 return true;
5366
Craig Topperc3ec1492014-05-26 06:22:03 +00005367 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005368 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5369 HadMultipleCandidates);
5370 if (Result.isInvalid())
5371 return true;
5372 // Record usage of conversion in an implicit cast.
5373 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005374 CK_UserDefinedConversion, Result.get(),
5375 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005376 }
5377 return false;
5378}
5379
5380static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5381 Sema::ContextualImplicitConverter &Converter,
5382 QualType T, bool HadMultipleCandidates,
5383 DeclAccessPair &Found) {
5384 CXXConversionDecl *Conversion =
5385 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005386 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005387
5388 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5389 if (!Converter.SuppressConversion) {
5390 if (SemaRef.isSFINAEContext())
5391 return true;
5392
5393 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5394 << From->getSourceRange();
5395 }
5396
5397 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5398 HadMultipleCandidates);
5399 if (Result.isInvalid())
5400 return true;
5401 // Record usage of conversion in an implicit cast.
5402 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005403 CK_UserDefinedConversion, Result.get(),
5404 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 return false;
5406}
5407
5408static ExprResult finishContextualImplicitConversion(
5409 Sema &SemaRef, SourceLocation Loc, Expr *From,
5410 Sema::ContextualImplicitConverter &Converter) {
5411 if (!Converter.match(From->getType()) && !Converter.Suppress)
5412 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5413 << From->getSourceRange();
5414
5415 return SemaRef.DefaultLvalueConversion(From);
5416}
5417
5418static void
5419collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5420 UnresolvedSetImpl &ViableConversions,
5421 OverloadCandidateSet &CandidateSet) {
5422 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5423 DeclAccessPair FoundDecl = ViableConversions[I];
5424 NamedDecl *D = FoundDecl.getDecl();
5425 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5426 if (isa<UsingShadowDecl>(D))
5427 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5428
5429 CXXConversionDecl *Conv;
5430 FunctionTemplateDecl *ConvTemplate;
5431 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5432 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5433 else
5434 Conv = cast<CXXConversionDecl>(D);
5435
5436 if (ConvTemplate)
5437 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005438 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5439 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005440 else
5441 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005442 ToType, CandidateSet,
5443 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005444 }
5445}
5446
Richard Smithccc11812013-05-21 19:05:48 +00005447/// \brief Attempt to convert the given expression to a type which is accepted
5448/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005449///
Richard Smithccc11812013-05-21 19:05:48 +00005450/// This routine will attempt to convert an expression of class type to a
5451/// type accepted by the specified converter. In C++11 and before, the class
5452/// must have a single non-explicit conversion function converting to a matching
5453/// type. In C++1y, there can be multiple such conversion functions, but only
5454/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005455///
Douglas Gregor4799d032010-06-30 00:20:43 +00005456/// \param Loc The source location of the construct that requires the
5457/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005458///
James Dennett18348b62012-06-22 08:52:37 +00005459/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005460///
Richard Smithccc11812013-05-21 19:05:48 +00005461/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005462///
Douglas Gregor4799d032010-06-30 00:20:43 +00005463/// \returns The expression, converted to an integral or enumeration type if
5464/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005465ExprResult Sema::PerformContextualImplicitConversion(
5466 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005467 // We can't perform any more checking for type-dependent expressions.
5468 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005469 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470
Eli Friedman1da70392012-01-26 00:26:18 +00005471 // Process placeholders immediately.
5472 if (From->hasPlaceholderType()) {
5473 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005474 if (result.isInvalid())
5475 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005476 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005477 }
5478
Richard Smithccc11812013-05-21 19:05:48 +00005479 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005480 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005481 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005482 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005483
5484 // FIXME: Check for missing '()' if T is a function type?
5485
Richard Smithccc11812013-05-21 19:05:48 +00005486 // We can only perform contextual implicit conversions on objects of class
5487 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005488 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005489 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005490 if (!Converter.Suppress)
5491 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005492 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005495 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005496 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005497 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005498 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005499
5500 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005501 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005502
Craig Toppere14c0f82014-03-12 04:55:44 +00005503 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005504 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005505 }
Richard Smithccc11812013-05-21 19:05:48 +00005506 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005507
Richard Smithdb0ac552015-12-18 22:40:25 +00005508 if (Converter.Suppress ? !isCompleteType(Loc, T)
5509 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005510 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005512 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005513 UnresolvedSet<4>
5514 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005515 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005516 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005517 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Larisse Voufo236bec22013-06-10 06:50:24 +00005519 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005520 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005521
Larisse Voufo236bec22013-06-10 06:50:24 +00005522 // To check that there is only one target type, in C++1y:
5523 QualType ToType;
5524 bool HasUniqueTargetType = true;
5525
5526 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005527 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005528 NamedDecl *D = (*I)->getUnderlyingDecl();
5529 CXXConversionDecl *Conversion;
5530 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5531 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005532 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005533 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5534 else
5535 continue; // C++11 does not consider conversion operator templates(?).
5536 } else
5537 Conversion = cast<CXXConversionDecl>(D);
5538
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005539 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005540 "Conversion operator templates are considered potentially "
5541 "viable in C++1y");
5542
5543 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5544 if (Converter.match(CurToType) || ConvTemplate) {
5545
5546 if (Conversion->isExplicit()) {
5547 // FIXME: For C++1y, do we need this restriction?
5548 // cf. diagnoseNoViableConversion()
5549 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005550 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005551 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005552 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005553 if (ToType.isNull())
5554 ToType = CurToType.getUnqualifiedType();
5555 else if (HasUniqueTargetType &&
5556 (CurToType.getUnqualifiedType() != ToType))
5557 HasUniqueTargetType = false;
5558 }
5559 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005560 }
Richard Smith8dd34252012-02-04 07:07:42 +00005561 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005564 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005565 // C++1y [conv]p6:
5566 // ... An expression e of class type E appearing in such a context
5567 // is said to be contextually implicitly converted to a specified
5568 // type T and is well-formed if and only if e can be implicitly
5569 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005570 // for conversion functions whose return type is cv T or reference to
5571 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Larisse Voufo236bec22013-06-10 06:50:24 +00005574 // If no unique T is found:
5575 if (ToType.isNull()) {
5576 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5577 HadMultipleCandidates,
5578 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005579 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005580 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005582
Larisse Voufo236bec22013-06-10 06:50:24 +00005583 // If more than one unique Ts are found:
5584 if (!HasUniqueTargetType)
5585 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5586 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587
Larisse Voufo236bec22013-06-10 06:50:24 +00005588 // If one unique T is found:
5589 // First, build a candidate set from the previously recorded
5590 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005591 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005592 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5593 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594
Larisse Voufo236bec22013-06-10 06:50:24 +00005595 // Then, perform overload resolution over the candidate set.
5596 OverloadCandidateSet::iterator Best;
5597 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5598 case OR_Success: {
5599 // Apply this conversion.
5600 DeclAccessPair Found =
5601 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5602 if (recordConversion(*this, Loc, From, Converter, T,
5603 HadMultipleCandidates, Found))
5604 return ExprError();
5605 break;
5606 }
5607 case OR_Ambiguous:
5608 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5609 ViableConversions);
5610 case OR_No_Viable_Function:
5611 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5612 HadMultipleCandidates,
5613 ExplicitConversions))
5614 return ExprError();
5615 // fall through 'OR_Deleted' case.
5616 case OR_Deleted:
5617 // We'll complain below about a non-integral condition type.
5618 break;
5619 }
5620 } else {
5621 switch (ViableConversions.size()) {
5622 case 0: {
5623 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5624 HadMultipleCandidates,
5625 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005626 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Larisse Voufo236bec22013-06-10 06:50:24 +00005628 // We'll complain below about a non-integral condition type.
5629 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005630 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005631 case 1: {
5632 // Apply this conversion.
5633 DeclAccessPair Found = ViableConversions[0];
5634 if (recordConversion(*this, Loc, From, Converter, T,
5635 HadMultipleCandidates, Found))
5636 return ExprError();
5637 break;
5638 }
5639 default:
5640 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5641 ViableConversions);
5642 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
Larisse Voufo236bec22013-06-10 06:50:24 +00005645 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005646}
5647
Richard Smith100b24a2014-04-17 01:52:14 +00005648/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5649/// an acceptable non-member overloaded operator for a call whose
5650/// arguments have types T1 (and, if non-empty, T2). This routine
5651/// implements the check in C++ [over.match.oper]p3b2 concerning
5652/// enumeration types.
5653static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5654 FunctionDecl *Fn,
5655 ArrayRef<Expr *> Args) {
5656 QualType T1 = Args[0]->getType();
5657 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5658
5659 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5660 return true;
5661
5662 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5663 return true;
5664
5665 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5666 if (Proto->getNumParams() < 1)
5667 return false;
5668
5669 if (T1->isEnumeralType()) {
5670 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5671 if (Context.hasSameUnqualifiedType(T1, ArgType))
5672 return true;
5673 }
5674
5675 if (Proto->getNumParams() < 2)
5676 return false;
5677
5678 if (!T2.isNull() && T2->isEnumeralType()) {
5679 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5680 if (Context.hasSameUnqualifiedType(T2, ArgType))
5681 return true;
5682 }
5683
5684 return false;
5685}
5686
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005687/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005688/// candidate functions, using the given function call arguments. If
5689/// @p SuppressUserConversions, then don't allow user-defined
5690/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005691///
James Dennett2a4d13c2012-06-15 07:13:21 +00005692/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005693/// based on an incomplete set of function arguments. This feature is used by
5694/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005695void
5696Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005697 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005698 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005699 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005700 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005701 bool PartialOverloading,
5702 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005703 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005704 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005705 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005706 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005707 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005708
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005710 if (!isa<CXXConstructorDecl>(Method)) {
5711 // If we get here, it's because we're calling a member function
5712 // that is named without a member access expression (e.g.,
5713 // "this->f") that was either written explicitly or created
5714 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005715 // function, e.g., X::f(). We use an empty type for the implied
5716 // object argument (C++ [over.call.func]p3), and the acting context
5717 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005718 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005720 Args, CandidateSet, SuppressUserConversions,
5721 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005722 return;
5723 }
5724 // We treat a constructor like a non-member function, since its object
5725 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005726 }
5727
Douglas Gregorff7028a2009-11-13 23:59:09 +00005728 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005729 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005730
Richard Smith100b24a2014-04-17 01:52:14 +00005731 // C++ [over.match.oper]p3:
5732 // if no operand has a class type, only those non-member functions in the
5733 // lookup set that have a first parameter of type T1 or "reference to
5734 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5735 // is a right operand) a second parameter of type T2 or "reference to
5736 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5737 // candidate functions.
5738 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5739 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5740 return;
5741
Richard Smith8b86f2d2013-11-04 01:48:18 +00005742 // C++11 [class.copy]p11: [DR1402]
5743 // A defaulted move constructor that is defined as deleted is ignored by
5744 // overload resolution.
5745 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5746 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5747 Constructor->isMoveConstructor())
5748 return;
5749
Douglas Gregor27381f32009-11-23 12:27:39 +00005750 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005751 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005752
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005753 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005754 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005755 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005756 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005757 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005758 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005759 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005760 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
John McCall578a1f82014-12-14 01:46:53 +00005762 if (Constructor) {
5763 // C++ [class.copy]p3:
5764 // A member function template is never instantiated to perform the copy
5765 // of a class object to an object of its class type.
5766 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005767 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005768 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005769 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5770 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005771 Candidate.Viable = false;
5772 Candidate.FailureKind = ovl_fail_illegal_constructor;
5773 return;
5774 }
5775 }
5776
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005777 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005778
5779 // (C++ 13.3.2p2): A candidate function having fewer than m
5780 // parameters is viable only if it has an ellipsis in its parameter
5781 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005782 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005783 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005784 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005785 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005786 return;
5787 }
5788
5789 // (C++ 13.3.2p2): A candidate function having more than m parameters
5790 // is viable only if the (m+1)st parameter has a default argument
5791 // (8.3.6). For the purposes of overload resolution, the
5792 // parameter list is truncated on the right, so that there are
5793 // exactly m parameters.
5794 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005795 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005796 // Not enough arguments.
5797 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005798 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005799 return;
5800 }
5801
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005802 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005803 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005804 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005805 // Skip the check for callers that are implicit members, because in this
5806 // case we may not yet know what the member's target is; the target is
5807 // inferred for the member automatically, based on the bases and fields of
5808 // the class.
5809 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005810 Candidate.Viable = false;
5811 Candidate.FailureKind = ovl_fail_bad_target;
5812 return;
5813 }
5814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005815 // Determine the implicit conversion sequences for each of the
5816 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005817 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005818 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005819 // (C++ 13.3.2p3): for F to be a viable function, there shall
5820 // exist for each argument an implicit conversion sequence
5821 // (13.3.3.1) that converts that argument to the corresponding
5822 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005823 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005824 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005825 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005826 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005827 /*InOverloadResolution=*/true,
5828 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005829 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005830 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005831 if (Candidate.Conversions[ArgIdx].isBad()) {
5832 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005833 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005834 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005835 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005836 } else {
5837 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5838 // argument for which there is no corresponding parameter is
5839 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005840 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005841 }
5842 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005843
5844 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5845 Candidate.Viable = false;
5846 Candidate.FailureKind = ovl_fail_enable_if;
5847 Candidate.DeductionFailure.Data = FailedAttr;
5848 return;
5849 }
5850}
5851
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005852ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005853 bool IsInstance) {
5854 SmallVector<ObjCMethodDecl*, 4> Methods;
5855 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5856 return nullptr;
5857
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005858 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5859 bool Match = true;
5860 ObjCMethodDecl *Method = Methods[b];
5861 unsigned NumNamedArgs = Sel.getNumArgs();
5862 // Method might have more arguments than selector indicates. This is due
5863 // to addition of c-style arguments in method.
5864 if (Method->param_size() > NumNamedArgs)
5865 NumNamedArgs = Method->param_size();
5866 if (Args.size() < NumNamedArgs)
5867 continue;
5868
5869 for (unsigned i = 0; i < NumNamedArgs; i++) {
5870 // We can't do any type-checking on a type-dependent argument.
5871 if (Args[i]->isTypeDependent()) {
5872 Match = false;
5873 break;
5874 }
5875
5876 ParmVarDecl *param = Method->parameters()[i];
5877 Expr *argExpr = Args[i];
5878 assert(argExpr && "SelectBestMethod(): missing expression");
5879
5880 // Strip the unbridged-cast placeholder expression off unless it's
5881 // a consumed argument.
5882 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5883 !param->hasAttr<CFConsumedAttr>())
5884 argExpr = stripARCUnbridgedCast(argExpr);
5885
5886 // If the parameter is __unknown_anytype, move on to the next method.
5887 if (param->getType() == Context.UnknownAnyTy) {
5888 Match = false;
5889 break;
5890 }
George Burgess IV45461812015-10-11 20:13:20 +00005891
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005892 ImplicitConversionSequence ConversionState
5893 = TryCopyInitialization(*this, argExpr, param->getType(),
5894 /*SuppressUserConversions*/false,
5895 /*InOverloadResolution=*/true,
5896 /*AllowObjCWritebackConversion=*/
5897 getLangOpts().ObjCAutoRefCount,
5898 /*AllowExplicit*/false);
5899 if (ConversionState.isBad()) {
5900 Match = false;
5901 break;
5902 }
5903 }
5904 // Promote additional arguments to variadic methods.
5905 if (Match && Method->isVariadic()) {
5906 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5907 if (Args[i]->isTypeDependent()) {
5908 Match = false;
5909 break;
5910 }
5911 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5912 nullptr);
5913 if (Arg.isInvalid()) {
5914 Match = false;
5915 break;
5916 }
5917 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005918 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005919 // Check for extra arguments to non-variadic methods.
5920 if (Args.size() != NumNamedArgs)
5921 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005922 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5923 // Special case when selectors have no argument. In this case, select
5924 // one with the most general result type of 'id'.
5925 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5926 QualType ReturnT = Methods[b]->getReturnType();
5927 if (ReturnT->isObjCIdType())
5928 return Methods[b];
5929 }
5930 }
5931 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005932
5933 if (Match)
5934 return Method;
5935 }
5936 return nullptr;
5937}
5938
George Burgess IV2a6150d2015-10-16 01:17:38 +00005939// specific_attr_iterator iterates over enable_if attributes in reverse, and
5940// enable_if is order-sensitive. As a result, we need to reverse things
5941// sometimes. Size of 4 elements is arbitrary.
5942static SmallVector<EnableIfAttr *, 4>
5943getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5944 SmallVector<EnableIfAttr *, 4> Result;
5945 if (!Function->hasAttrs())
5946 return Result;
5947
5948 const auto &FuncAttrs = Function->getAttrs();
5949 for (Attr *Attr : FuncAttrs)
5950 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5951 Result.push_back(EnableIf);
5952
5953 std::reverse(Result.begin(), Result.end());
5954 return Result;
5955}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005956
5957EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5958 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005959 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5960 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005961 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005962
5963 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005964 SmallVector<Expr *, 16> ConvertedArgs;
5965 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005966 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005967
5968 // Convert the arguments.
George Burgess IVe96abf72016-02-24 22:31:14 +00005969 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5970 ExprResult R;
5971 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005972 !cast<CXXMethodDecl>(Function)->isStatic() &&
5973 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005974 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00005975 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5976 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005977 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00005978 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5979 Context, Function->getParamDecl(I)),
5980 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005981 }
George Burgess IVe96abf72016-02-24 22:31:14 +00005982
5983 if (R.isInvalid()) {
5984 InitializationFailed = true;
5985 break;
5986 }
5987
5988 ContainsValueDependentExpr |= R.get()->isValueDependent();
5989 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005990 }
5991
5992 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005993 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005994
Nick Lewyckye283c552015-08-25 22:33:16 +00005995 // Push default arguments if needed.
5996 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5997 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5998 ParmVarDecl *P = Function->getParamDecl(i);
5999 ExprResult R = PerformCopyInitialization(
6000 InitializedEntity::InitializeParameter(Context,
6001 Function->getParamDecl(i)),
6002 SourceLocation(),
6003 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6004 : P->getDefaultArg());
6005 if (R.isInvalid()) {
6006 InitializationFailed = true;
6007 break;
6008 }
6009 ContainsValueDependentExpr |= R.get()->isValueDependent();
6010 ConvertedArgs.push_back(R.get());
6011 }
6012
6013 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006014 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006015 }
6016
George Burgess IV2a6150d2015-10-16 01:17:38 +00006017 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006018 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006019 if (EIA->getCond()->isValueDependent()) {
6020 // Don't even try now, we'll examine it after instantiation.
6021 continue;
6022 }
6023
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006024 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006025 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6026 if (!ContainsValueDependentExpr)
6027 return EIA;
6028 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006029 return EIA;
6030 }
6031 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006032 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006033}
6034
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006035/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006036/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006037void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006038 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006039 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006040 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006041 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006042 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006043 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006044 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6045 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006046 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006047 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006048 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006049 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006050 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006051 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006052 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006053 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006054 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006055 } else {
John McCalla0296f72010-03-19 07:35:19 +00006056 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006057 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6058 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006059 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006060 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006061 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006062 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006063 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006064 CandidateSet, SuppressUserConversions,
6065 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006066 else
John McCalla0296f72010-03-19 07:35:19 +00006067 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006068 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006069 CandidateSet, SuppressUserConversions,
6070 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006071 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006072 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006073}
6074
John McCallf0f1cf02009-11-17 07:50:12 +00006075/// AddMethodCandidate - Adds a named decl (which is some kind of
6076/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006077void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006078 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006079 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006080 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006081 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006082 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006083 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006084 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006085
6086 if (isa<UsingShadowDecl>(Decl))
6087 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088
John McCallf0f1cf02009-11-17 07:50:12 +00006089 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6090 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6091 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006092 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006093 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006094 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006095 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006096 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006097 } else {
John McCalla0296f72010-03-19 07:35:19 +00006098 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006099 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006100 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006101 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006102 }
6103}
6104
Douglas Gregor436424c2008-11-18 23:14:02 +00006105/// AddMethodCandidate - Adds the given C++ member function to the set
6106/// of candidate functions, using the given function call arguments
6107/// and the object argument (@c Object). For example, in a call
6108/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6109/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6110/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006111/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006112void
John McCalla0296f72010-03-19 07:35:19 +00006113Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006114 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006115 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006116 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006117 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006118 bool SuppressUserConversions,
6119 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006120 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006121 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006122 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006123 assert(!isa<CXXConstructorDecl>(Method) &&
6124 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006125
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006126 if (!CandidateSet.isNewCandidate(Method))
6127 return;
6128
Richard Smith8b86f2d2013-11-04 01:48:18 +00006129 // C++11 [class.copy]p23: [DR1402]
6130 // A defaulted move assignment operator that is defined as deleted is
6131 // ignored by overload resolution.
6132 if (Method->isDefaulted() && Method->isDeleted() &&
6133 Method->isMoveAssignmentOperator())
6134 return;
6135
Douglas Gregor27381f32009-11-23 12:27:39 +00006136 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006137 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006138
Douglas Gregor436424c2008-11-18 23:14:02 +00006139 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006140 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006141 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006142 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006143 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006144 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006145 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006146
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006147 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006148
6149 // (C++ 13.3.2p2): A candidate function having fewer than m
6150 // parameters is viable only if it has an ellipsis in its parameter
6151 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006152 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6153 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006154 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006155 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006156 return;
6157 }
6158
6159 // (C++ 13.3.2p2): A candidate function having more than m parameters
6160 // is viable only if the (m+1)st parameter has a default argument
6161 // (8.3.6). For the purposes of overload resolution, the
6162 // parameter list is truncated on the right, so that there are
6163 // exactly m parameters.
6164 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006165 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006166 // Not enough arguments.
6167 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006168 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006169 return;
6170 }
6171
6172 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006173
John McCall6e9f8f62009-12-03 04:06:58 +00006174 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006175 // The implicit object argument is ignored.
6176 Candidate.IgnoreObjectArgument = true;
6177 else {
6178 // Determine the implicit conversion sequence for the object
6179 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006180 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6181 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6182 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006183 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006184 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006185 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006186 return;
6187 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006188 }
6189
Eli Bendersky291a57e2014-09-25 23:59:08 +00006190 // (CUDA B.1): Check for invalid calls between targets.
6191 if (getLangOpts().CUDA)
6192 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6193 if (CheckCUDATarget(Caller, Method)) {
6194 Candidate.Viable = false;
6195 Candidate.FailureKind = ovl_fail_bad_target;
6196 return;
6197 }
6198
Douglas Gregor436424c2008-11-18 23:14:02 +00006199 // Determine the implicit conversion sequences for each of the
6200 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006201 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006202 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006203 // (C++ 13.3.2p3): for F to be a viable function, there shall
6204 // exist for each argument an implicit conversion sequence
6205 // (13.3.3.1) that converts that argument to the corresponding
6206 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006207 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006208 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006209 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006210 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006211 /*InOverloadResolution=*/true,
6212 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006213 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006214 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006215 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006216 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006217 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006218 }
6219 } else {
6220 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6221 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006222 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006223 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006224 }
6225 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006226
6227 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6228 Candidate.Viable = false;
6229 Candidate.FailureKind = ovl_fail_enable_if;
6230 Candidate.DeductionFailure.Data = FailedAttr;
6231 return;
6232 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006233}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234
Douglas Gregor97628d62009-08-21 00:16:32 +00006235/// \brief Add a C++ member function template as a candidate to the candidate
6236/// set, using template argument deduction to produce an appropriate member
6237/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006238void
Douglas Gregor97628d62009-08-21 00:16:32 +00006239Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006240 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006241 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006242 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006243 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006244 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006245 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006246 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006247 bool SuppressUserConversions,
6248 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006249 if (!CandidateSet.isNewCandidate(MethodTmpl))
6250 return;
6251
Douglas Gregor97628d62009-08-21 00:16:32 +00006252 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006253 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006254 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006255 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006256 // candidate functions in the usual way.113) A given name can refer to one
6257 // or more function templates and also to a set of overloaded non-template
6258 // functions. In such a case, the candidate functions generated from each
6259 // function template are combined with the set of non-template candidate
6260 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006261 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006262 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006263 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006264 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006265 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006266 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006267 Candidate.FoundDecl = FoundDecl;
6268 Candidate.Function = MethodTmpl->getTemplatedDecl();
6269 Candidate.Viable = false;
6270 Candidate.FailureKind = ovl_fail_bad_deduction;
6271 Candidate.IsSurrogate = false;
6272 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006273 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006275 Info);
6276 return;
6277 }
Mike Stump11289f42009-09-09 15:08:12 +00006278
Douglas Gregor97628d62009-08-21 00:16:32 +00006279 // Add the function template specialization produced by template argument
6280 // deduction as a candidate.
6281 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006282 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006283 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006284 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006285 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006286 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006287}
6288
Douglas Gregor05155d82009-08-21 23:19:43 +00006289/// \brief Add a C++ function template specialization as a candidate
6290/// in the candidate set, using template argument deduction to produce
6291/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006292void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006293Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006294 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006295 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006296 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006297 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006298 bool SuppressUserConversions,
6299 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006300 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6301 return;
6302
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006303 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006304 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006305 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006306 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006307 // candidate functions in the usual way.113) A given name can refer to one
6308 // or more function templates and also to a set of overloaded non-template
6309 // functions. In such a case, the candidate functions generated from each
6310 // function template are combined with the set of non-template candidate
6311 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006312 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006313 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006314 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006315 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006316 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006317 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006318 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006319 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6320 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006321 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006322 Candidate.IsSurrogate = false;
6323 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006324 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006325 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006326 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006327 return;
6328 }
Mike Stump11289f42009-09-09 15:08:12 +00006329
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006330 // Add the function template specialization produced by template argument
6331 // deduction as a candidate.
6332 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006333 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006334 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006335}
Mike Stump11289f42009-09-09 15:08:12 +00006336
Douglas Gregor4b60a152013-11-07 22:34:54 +00006337/// Determine whether this is an allowable conversion from the result
6338/// of an explicit conversion operator to the expected type, per C++
6339/// [over.match.conv]p1 and [over.match.ref]p1.
6340///
6341/// \param ConvType The return type of the conversion function.
6342///
6343/// \param ToType The type we are converting to.
6344///
6345/// \param AllowObjCPointerConversion Allow a conversion from one
6346/// Objective-C pointer to another.
6347///
6348/// \returns true if the conversion is allowable, false otherwise.
6349static bool isAllowableExplicitConversion(Sema &S,
6350 QualType ConvType, QualType ToType,
6351 bool AllowObjCPointerConversion) {
6352 QualType ToNonRefType = ToType.getNonReferenceType();
6353
6354 // Easy case: the types are the same.
6355 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6356 return true;
6357
6358 // Allow qualification conversions.
6359 bool ObjCLifetimeConversion;
6360 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6361 ObjCLifetimeConversion))
6362 return true;
6363
6364 // If we're not allowed to consider Objective-C pointer conversions,
6365 // we're done.
6366 if (!AllowObjCPointerConversion)
6367 return false;
6368
6369 // Is this an Objective-C pointer conversion?
6370 bool IncompatibleObjC = false;
6371 QualType ConvertedType;
6372 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6373 IncompatibleObjC);
6374}
6375
Douglas Gregora1f013e2008-11-07 22:36:19 +00006376/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006377/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006378/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006379/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006380/// (which may or may not be the same type as the type that the
6381/// conversion function produces).
6382void
6383Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006384 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006385 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006386 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006387 OverloadCandidateSet& CandidateSet,
6388 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006389 assert(!Conversion->getDescribedFunctionTemplate() &&
6390 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006391 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006392 if (!CandidateSet.isNewCandidate(Conversion))
6393 return;
6394
Richard Smith2a7d4812013-05-04 07:00:32 +00006395 // If the conversion function has an undeduced return type, trigger its
6396 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006397 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006398 if (DeduceReturnType(Conversion, From->getExprLoc()))
6399 return;
6400 ConvType = Conversion->getConversionType().getNonReferenceType();
6401 }
6402
Richard Smith089c3162013-09-21 21:55:46 +00006403 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6404 // operator is only a candidate if its return type is the target type or
6405 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006406 if (Conversion->isExplicit() &&
6407 !isAllowableExplicitConversion(*this, ConvType, ToType,
6408 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006409 return;
6410
Douglas Gregor27381f32009-11-23 12:27:39 +00006411 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006412 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006413
Douglas Gregora1f013e2008-11-07 22:36:19 +00006414 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006415 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006416 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006417 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006418 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006419 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006420 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006421 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006422 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006423 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006424 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006425
Douglas Gregor6affc782010-08-19 15:37:02 +00006426 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427 // For conversion functions, the function is considered to be a member of
6428 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006429 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006430 //
6431 // Determine the implicit conversion sequence for the implicit
6432 // object parameter.
6433 QualType ImplicitParamType = From->getType();
6434 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6435 ImplicitParamType = FromPtrType->getPointeeType();
6436 CXXRecordDecl *ConversionContext
6437 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
Richard Smith0f59cb32015-12-18 21:45:41 +00006439 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6440 *this, CandidateSet.getLocation(), From->getType(),
6441 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006442
John McCall0d1da222010-01-12 00:44:57 +00006443 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006444 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006445 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006446 return;
6447 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006448
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006449 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006450 // derived to base as such conversions are given Conversion Rank. They only
6451 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6452 QualType FromCanon
6453 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6454 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006455 if (FromCanon == ToCanon ||
6456 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006457 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006458 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006459 return;
6460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006461
Douglas Gregora1f013e2008-11-07 22:36:19 +00006462 // To determine what the conversion from the result of calling the
6463 // conversion function to the type we're eventually trying to
6464 // convert to (ToType), we need to synthesize a call to the
6465 // conversion function and attempt copy initialization from it. This
6466 // makes sure that we get the right semantics with respect to
6467 // lvalues/rvalues and the type. Fortunately, we can allocate this
6468 // call on the stack and we don't need its arguments to be
6469 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006470 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006471 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006472 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6473 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006474 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006475 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006476
Richard Smith48d24642011-07-13 22:53:21 +00006477 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006478 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006479 Candidate.Viable = false;
6480 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6481 return;
6482 }
6483
Richard Smith48d24642011-07-13 22:53:21 +00006484 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006485
Mike Stump11289f42009-09-09 15:08:12 +00006486 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006487 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6488 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006489 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006490 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006491 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006492 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006493 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006494 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006495 /*InOverloadResolution=*/false,
6496 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006497
John McCall0d1da222010-01-12 00:44:57 +00006498 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006499 case ImplicitConversionSequence::StandardConversion:
6500 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006501
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006502 // C++ [over.ics.user]p3:
6503 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006504 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006505 // shall have exact match rank.
6506 if (Conversion->getPrimaryTemplate() &&
6507 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006510 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
Douglas Gregorcba72b12011-01-21 05:18:22 +00006513 // C++0x [dcl.init.ref]p5:
6514 // In the second case, if the reference is an rvalue reference and
6515 // the second standard conversion sequence of the user-defined
6516 // conversion sequence includes an lvalue-to-rvalue conversion, the
6517 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006518 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006519 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6520 Candidate.Viable = false;
6521 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006522 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006523 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006524 break;
6525
6526 case ImplicitConversionSequence::BadConversion:
6527 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006528 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006529 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006530
6531 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006532 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006533 "Can only end up with a standard conversion sequence or failure");
6534 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006535
Craig Topper5fc8fc22014-08-27 06:28:36 +00006536 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006537 Candidate.Viable = false;
6538 Candidate.FailureKind = ovl_fail_enable_if;
6539 Candidate.DeductionFailure.Data = FailedAttr;
6540 return;
6541 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006542}
6543
Douglas Gregor05155d82009-08-21 23:19:43 +00006544/// \brief Adds a conversion function template specialization
6545/// candidate to the overload set, using template argument deduction
6546/// to deduce the template arguments of the conversion function
6547/// template from the type that we are converting to (C++
6548/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006549void
Douglas Gregor05155d82009-08-21 23:19:43 +00006550Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006551 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006552 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006553 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006554 OverloadCandidateSet &CandidateSet,
6555 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006556 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6557 "Only conversion function templates permitted here");
6558
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006559 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6560 return;
6561
Craig Toppere6706e42012-09-19 02:26:47 +00006562 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006563 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006564 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006565 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006566 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006567 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006568 Candidate.FoundDecl = FoundDecl;
6569 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6570 Candidate.Viable = false;
6571 Candidate.FailureKind = ovl_fail_bad_deduction;
6572 Candidate.IsSurrogate = false;
6573 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006574 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006575 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006576 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006577 return;
6578 }
Mike Stump11289f42009-09-09 15:08:12 +00006579
Douglas Gregor05155d82009-08-21 23:19:43 +00006580 // Add the conversion function template specialization produced by
6581 // template argument deduction as a candidate.
6582 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006583 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006584 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006585}
6586
Douglas Gregorab7897a2008-11-19 22:57:39 +00006587/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6588/// converts the given @c Object to a function pointer via the
6589/// conversion function @c Conversion, and then attempts to call it
6590/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6591/// the type of function that we'll eventually be calling.
6592void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006593 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006594 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006595 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006596 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006597 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006598 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006599 if (!CandidateSet.isNewCandidate(Conversion))
6600 return;
6601
Douglas Gregor27381f32009-11-23 12:27:39 +00006602 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006603 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006604
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006605 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006606 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006607 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006608 Candidate.Surrogate = Conversion;
6609 Candidate.Viable = true;
6610 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006611 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006612 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006613
6614 // Determine the implicit conversion sequence for the implicit
6615 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006616 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6617 *this, CandidateSet.getLocation(), Object->getType(),
6618 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006619 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006620 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006621 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006622 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006623 return;
6624 }
6625
6626 // The first conversion is actually a user-defined conversion whose
6627 // first conversion is ObjectInit's standard conversion (which is
6628 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006629 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006630 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006631 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006632 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006633 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006634 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006635 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006636 = Candidate.Conversions[0].UserDefined.Before;
6637 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6638
Mike Stump11289f42009-09-09 15:08:12 +00006639 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006640 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006641
6642 // (C++ 13.3.2p2): A candidate function having fewer than m
6643 // parameters is viable only if it has an ellipsis in its parameter
6644 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006645 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006646 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006647 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006648 return;
6649 }
6650
6651 // Function types don't have any default arguments, so just check if
6652 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006653 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006654 // Not enough arguments.
6655 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006656 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006657 return;
6658 }
6659
6660 // Determine the implicit conversion sequences for each of the
6661 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006662 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006663 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006664 // (C++ 13.3.2p3): for F to be a viable function, there shall
6665 // exist for each argument an implicit conversion sequence
6666 // (13.3.3.1) that converts that argument to the corresponding
6667 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006668 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006669 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006670 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006671 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006672 /*InOverloadResolution=*/false,
6673 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006674 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006675 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006676 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006677 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006678 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006679 }
6680 } else {
6681 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6682 // argument for which there is no corresponding parameter is
6683 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006684 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006685 }
6686 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006687
Craig Topper5fc8fc22014-08-27 06:28:36 +00006688 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006689 Candidate.Viable = false;
6690 Candidate.FailureKind = ovl_fail_enable_if;
6691 Candidate.DeductionFailure.Data = FailedAttr;
6692 return;
6693 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006694}
6695
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006696/// \brief Add overload candidates for overloaded operators that are
6697/// member functions.
6698///
6699/// Add the overloaded operator candidates that are member functions
6700/// for the operator Op that was used in an operator expression such
6701/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6702/// CandidateSet will store the added overload candidates. (C++
6703/// [over.match.oper]).
6704void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6705 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006706 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006707 OverloadCandidateSet& CandidateSet,
6708 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006709 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6710
6711 // C++ [over.match.oper]p3:
6712 // For a unary operator @ with an operand of a type whose
6713 // cv-unqualified version is T1, and for a binary operator @ with
6714 // a left operand of a type whose cv-unqualified version is T1 and
6715 // a right operand of a type whose cv-unqualified version is T2,
6716 // three sets of candidate functions, designated member
6717 // candidates, non-member candidates and built-in candidates, are
6718 // constructed as follows:
6719 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006720
Richard Smith0feaf0c2013-04-20 12:41:22 +00006721 // -- If T1 is a complete class type or a class currently being
6722 // defined, the set of member candidates is the result of the
6723 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6724 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006725 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006726 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006727 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006728 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006729 // If the type is neither complete nor being defined, bail out now.
6730 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006731 return;
Mike Stump11289f42009-09-09 15:08:12 +00006732
John McCall27b18f82009-11-17 02:14:36 +00006733 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6734 LookupQualifiedName(Operators, T1Rec->getDecl());
6735 Operators.suppressDiagnostics();
6736
Mike Stump11289f42009-09-09 15:08:12 +00006737 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006738 OperEnd = Operators.end();
6739 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006740 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006741 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006742 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006743 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006744 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006745 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006746 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006747}
6748
Douglas Gregora11693b2008-11-12 17:17:38 +00006749/// AddBuiltinCandidate - Add a candidate for a built-in
6750/// operator. ResultTy and ParamTys are the result and parameter types
6751/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006752/// arguments being passed to the candidate. IsAssignmentOperator
6753/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006754/// operator. NumContextualBoolArguments is the number of arguments
6755/// (at the beginning of the argument list) that will be contextually
6756/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006757void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006758 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006759 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006760 bool IsAssignmentOperator,
6761 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006762 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006764
Douglas Gregora11693b2008-11-12 17:17:38 +00006765 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006766 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006767 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6768 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006769 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006770 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006771 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006772 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006773 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6774
6775 // Determine the implicit conversion sequences for each of the
6776 // arguments.
6777 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006778 Candidate.ExplicitCallArguments = Args.size();
6779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006780 // C++ [over.match.oper]p4:
6781 // For the built-in assignment operators, conversions of the
6782 // left operand are restricted as follows:
6783 // -- no temporaries are introduced to hold the left operand, and
6784 // -- no user-defined conversions are applied to the left
6785 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006786 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006787 //
6788 // We block these conversions by turning off user-defined
6789 // conversions, since that is the only way that initialization of
6790 // a reference to a non-class type can occur from something that
6791 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006792 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006793 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006794 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006795 Candidate.Conversions[ArgIdx]
6796 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006797 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006798 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006799 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006800 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006801 /*InOverloadResolution=*/false,
6802 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006803 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006804 }
John McCall0d1da222010-01-12 00:44:57 +00006805 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006806 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006807 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006808 break;
6809 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006810 }
6811}
6812
Craig Toppercd7b0332013-07-01 06:29:40 +00006813namespace {
6814
Douglas Gregora11693b2008-11-12 17:17:38 +00006815/// BuiltinCandidateTypeSet - A set of types that will be used for the
6816/// candidate operator functions for built-in operators (C++
6817/// [over.built]). The types are separated into pointer types and
6818/// enumeration types.
6819class BuiltinCandidateTypeSet {
6820 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006821 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006822
6823 /// PointerTypes - The set of pointer types that will be used in the
6824 /// built-in candidates.
6825 TypeSet PointerTypes;
6826
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006827 /// MemberPointerTypes - The set of member pointer types that will be
6828 /// used in the built-in candidates.
6829 TypeSet MemberPointerTypes;
6830
Douglas Gregora11693b2008-11-12 17:17:38 +00006831 /// EnumerationTypes - The set of enumeration types that will be
6832 /// used in the built-in candidates.
6833 TypeSet EnumerationTypes;
6834
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006835 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006836 /// candidates.
6837 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006838
6839 /// \brief A flag indicating non-record types are viable candidates
6840 bool HasNonRecordTypes;
6841
6842 /// \brief A flag indicating whether either arithmetic or enumeration types
6843 /// were present in the candidate set.
6844 bool HasArithmeticOrEnumeralTypes;
6845
Douglas Gregor80af3132011-05-21 23:15:46 +00006846 /// \brief A flag indicating whether the nullptr type was present in the
6847 /// candidate set.
6848 bool HasNullPtrType;
6849
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006850 /// Sema - The semantic analysis instance where we are building the
6851 /// candidate type set.
6852 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006853
Douglas Gregora11693b2008-11-12 17:17:38 +00006854 /// Context - The AST context in which we will build the type sets.
6855 ASTContext &Context;
6856
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006857 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6858 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006859 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006860
6861public:
6862 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006863 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006864
Mike Stump11289f42009-09-09 15:08:12 +00006865 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006866 : HasNonRecordTypes(false),
6867 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006868 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006869 SemaRef(SemaRef),
6870 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006871
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006872 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006873 SourceLocation Loc,
6874 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006875 bool AllowExplicitConversions,
6876 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006877
6878 /// pointer_begin - First pointer type found;
6879 iterator pointer_begin() { return PointerTypes.begin(); }
6880
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006881 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006882 iterator pointer_end() { return PointerTypes.end(); }
6883
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006884 /// member_pointer_begin - First member pointer type found;
6885 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6886
6887 /// member_pointer_end - Past the last member pointer type found;
6888 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6889
Douglas Gregora11693b2008-11-12 17:17:38 +00006890 /// enumeration_begin - First enumeration type found;
6891 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6892
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006893 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006894 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006896 iterator vector_begin() { return VectorTypes.begin(); }
6897 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006898
6899 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6900 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006901 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006902};
6903
Craig Toppercd7b0332013-07-01 06:29:40 +00006904} // end anonymous namespace
6905
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006906/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006907/// the set of pointer types along with any more-qualified variants of
6908/// that type. For example, if @p Ty is "int const *", this routine
6909/// will add "int const *", "int const volatile *", "int const
6910/// restrict *", and "int const volatile restrict *" to the set of
6911/// pointer types. Returns true if the add of @p Ty itself succeeded,
6912/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006913///
6914/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006915bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006916BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6917 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006918
Douglas Gregora11693b2008-11-12 17:17:38 +00006919 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006920 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006921 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006923 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006924 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006925 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006926 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006927 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6928 PointeeTy = PTy->getPointeeType();
6929 buildObjCPtr = true;
6930 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006931 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006932 }
6933
Sebastian Redl4990a632009-11-18 20:39:26 +00006934 // Don't add qualified variants of arrays. For one, they're not allowed
6935 // (the qualifier would sink to the element type), and for another, the
6936 // only overload situation where it matters is subscript or pointer +- int,
6937 // and those shouldn't have qualifier variants anyway.
6938 if (PointeeTy->isArrayType())
6939 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006940
John McCall8ccfcb52009-09-24 19:53:00 +00006941 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006942 bool hasVolatile = VisibleQuals.hasVolatile();
6943 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944
John McCall8ccfcb52009-09-24 19:53:00 +00006945 // Iterate through all strict supersets of BaseCVR.
6946 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6947 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006948 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006949 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006950
6951 // Skip over restrict if no restrict found anywhere in the types, or if
6952 // the type cannot be restrict-qualified.
6953 if ((CVR & Qualifiers::Restrict) &&
6954 (!hasRestrict ||
6955 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6956 continue;
6957
6958 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006959 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006960
6961 // Build qualified pointer type.
6962 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006963 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006964 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006965 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006966 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6967
6968 // Insert qualified pointer type.
6969 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006970 }
6971
6972 return true;
6973}
6974
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006975/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6976/// to the set of pointer types along with any more-qualified variants of
6977/// that type. For example, if @p Ty is "int const *", this routine
6978/// will add "int const *", "int const volatile *", "int const
6979/// restrict *", and "int const volatile restrict *" to the set of
6980/// pointer types. Returns true if the add of @p Ty itself succeeded,
6981/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006982///
6983/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006984bool
6985BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6986 QualType Ty) {
6987 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006988 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006989 return false;
6990
John McCall8ccfcb52009-09-24 19:53:00 +00006991 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6992 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006993
John McCall8ccfcb52009-09-24 19:53:00 +00006994 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006995 // Don't add qualified variants of arrays. For one, they're not allowed
6996 // (the qualifier would sink to the element type), and for another, the
6997 // only overload situation where it matters is subscript or pointer +- int,
6998 // and those shouldn't have qualifier variants anyway.
6999 if (PointeeTy->isArrayType())
7000 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007001 const Type *ClassTy = PointerTy->getClass();
7002
7003 // Iterate through all strict supersets of the pointee type's CVR
7004 // qualifiers.
7005 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7006 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7007 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008
John McCall8ccfcb52009-09-24 19:53:00 +00007009 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007010 MemberPointerTypes.insert(
7011 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007012 }
7013
7014 return true;
7015}
7016
Douglas Gregora11693b2008-11-12 17:17:38 +00007017/// AddTypesConvertedFrom - Add each of the types to which the type @p
7018/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007019/// primarily interested in pointer types and enumeration types. We also
7020/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007021/// AllowUserConversions is true if we should look at the conversion
7022/// functions of a class type, and AllowExplicitConversions if we
7023/// should also include the explicit conversion functions of a class
7024/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007025void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007026BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007027 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007028 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007029 bool AllowExplicitConversions,
7030 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007031 // Only deal with canonical types.
7032 Ty = Context.getCanonicalType(Ty);
7033
7034 // Look through reference types; they aren't part of the type of an
7035 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007036 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007037 Ty = RefTy->getPointeeType();
7038
John McCall33ddac02011-01-19 10:06:00 +00007039 // If we're dealing with an array type, decay to the pointer.
7040 if (Ty->isArrayType())
7041 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7042
7043 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007044 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007045
Chandler Carruth00a38332010-12-13 01:44:01 +00007046 // Flag if we ever add a non-record type.
7047 const RecordType *TyRec = Ty->getAs<RecordType>();
7048 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7049
Chandler Carruth00a38332010-12-13 01:44:01 +00007050 // Flag if we encounter an arithmetic type.
7051 HasArithmeticOrEnumeralTypes =
7052 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7053
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007054 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7055 PointerTypes.insert(Ty);
7056 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007057 // Insert our type, and its more-qualified variants, into the set
7058 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007059 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007060 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007061 } else if (Ty->isMemberPointerType()) {
7062 // Member pointers are far easier, since the pointee can't be converted.
7063 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7064 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007065 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007066 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007067 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007068 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007069 // We treat vector types as arithmetic types in many contexts as an
7070 // extension.
7071 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007072 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007073 } else if (Ty->isNullPtrType()) {
7074 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007075 } else if (AllowUserConversions && TyRec) {
7076 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007077 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007078 return;
Mike Stump11289f42009-09-09 15:08:12 +00007079
Chandler Carruth00a38332010-12-13 01:44:01 +00007080 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007081 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007082 if (isa<UsingShadowDecl>(D))
7083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007084
Chandler Carruth00a38332010-12-13 01:44:01 +00007085 // Skip conversion function templates; they don't tell us anything
7086 // about which builtin types we can convert to.
7087 if (isa<FunctionTemplateDecl>(D))
7088 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007089
Chandler Carruth00a38332010-12-13 01:44:01 +00007090 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7091 if (AllowExplicitConversions || !Conv->isExplicit()) {
7092 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7093 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007094 }
7095 }
7096 }
7097}
7098
Douglas Gregor84605ae2009-08-24 13:43:27 +00007099/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7100/// the volatile- and non-volatile-qualified assignment operators for the
7101/// given type to the candidate set.
7102static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7103 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007104 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007105 OverloadCandidateSet &CandidateSet) {
7106 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007107
Douglas Gregor84605ae2009-08-24 13:43:27 +00007108 // T& operator=(T&, T)
7109 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7110 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007112 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007113
Douglas Gregor84605ae2009-08-24 13:43:27 +00007114 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7115 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007116 ParamTypes[0]
7117 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007118 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007119 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007120 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007121 }
7122}
Mike Stump11289f42009-09-09 15:08:12 +00007123
Sebastian Redl1054fae2009-10-25 17:03:50 +00007124/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7125/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007126static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7127 Qualifiers VRQuals;
7128 const RecordType *TyRec;
7129 if (const MemberPointerType *RHSMPType =
7130 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007131 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007132 else
7133 TyRec = ArgExpr->getType()->getAs<RecordType>();
7134 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007135 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007136 VRQuals.addVolatile();
7137 VRQuals.addRestrict();
7138 return VRQuals;
7139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007142 if (!ClassDecl->hasDefinition())
7143 return VRQuals;
7144
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007145 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007146 if (isa<UsingShadowDecl>(D))
7147 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7148 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007149 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7150 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7151 CanTy = ResTypeRef->getPointeeType();
7152 // Need to go down the pointer/mempointer chain and add qualifiers
7153 // as see them.
7154 bool done = false;
7155 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007156 if (CanTy.isRestrictQualified())
7157 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007158 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7159 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007160 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007161 CanTy->getAs<MemberPointerType>())
7162 CanTy = ResTypeMPtr->getPointeeType();
7163 else
7164 done = true;
7165 if (CanTy.isVolatileQualified())
7166 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007167 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7168 return VRQuals;
7169 }
7170 }
7171 }
7172 return VRQuals;
7173}
John McCall52872982010-11-13 05:51:15 +00007174
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007175namespace {
John McCall52872982010-11-13 05:51:15 +00007176
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007177/// \brief Helper class to manage the addition of builtin operator overload
7178/// candidates. It provides shared state and utility methods used throughout
7179/// the process, as well as a helper method to add each group of builtin
7180/// operator overloads from the standard to a candidate set.
7181class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007182 // Common instance state available to all overload candidate addition methods.
7183 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007184 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007185 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007186 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007187 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007188 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007189
Chandler Carruthc6586e52010-12-12 10:35:00 +00007190 // Define some constants used to index and iterate over the arithemetic types
7191 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007192 // The "promoted arithmetic types" are the arithmetic
7193 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007194 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007195 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007196 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007197 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007198 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007199 LastPromotedArithmeticType = 11;
7200 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007201
Chandler Carruthc6586e52010-12-12 10:35:00 +00007202 /// \brief Get the canonical type for a given arithmetic type index.
7203 CanQualType getArithmeticType(unsigned index) {
7204 assert(index < NumArithmeticTypes);
7205 static CanQualType ASTContext::* const
7206 ArithmeticTypes[NumArithmeticTypes] = {
7207 // Start of promoted types.
7208 &ASTContext::FloatTy,
7209 &ASTContext::DoubleTy,
7210 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007211
Chandler Carruthc6586e52010-12-12 10:35:00 +00007212 // Start of integral types.
7213 &ASTContext::IntTy,
7214 &ASTContext::LongTy,
7215 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007216 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007217 &ASTContext::UnsignedIntTy,
7218 &ASTContext::UnsignedLongTy,
7219 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007220 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007221 // End of promoted types.
7222
7223 &ASTContext::BoolTy,
7224 &ASTContext::CharTy,
7225 &ASTContext::WCharTy,
7226 &ASTContext::Char16Ty,
7227 &ASTContext::Char32Ty,
7228 &ASTContext::SignedCharTy,
7229 &ASTContext::ShortTy,
7230 &ASTContext::UnsignedCharTy,
7231 &ASTContext::UnsignedShortTy,
7232 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007233 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007234 };
7235 return S.Context.*ArithmeticTypes[index];
7236 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007238 /// \brief Gets the canonical type resulting from the usual arithemetic
7239 /// converions for the given arithmetic types.
7240 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7241 // Accelerator table for performing the usual arithmetic conversions.
7242 // The rules are basically:
7243 // - if either is floating-point, use the wider floating-point
7244 // - if same signedness, use the higher rank
7245 // - if same size, use unsigned of the higher rank
7246 // - use the larger type
7247 // These rules, together with the axiom that higher ranks are
7248 // never smaller, are sufficient to precompute all of these results
7249 // *except* when dealing with signed types of higher rank.
7250 // (we could precompute SLL x UI for all known platforms, but it's
7251 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007252 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007253 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007254 Dep=-1,
7255 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007256 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007257 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007258 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007259/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7260/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7261/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7262/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7263/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7264/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7265/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7266/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7267/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7268/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7269/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007270 };
7271
7272 assert(L < LastPromotedArithmeticType);
7273 assert(R < LastPromotedArithmeticType);
7274 int Idx = ConversionsTable[L][R];
7275
7276 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007277 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007278
7279 // Slow path: we need to compare widths.
7280 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007281 CanQualType LT = getArithmeticType(L),
7282 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007283 unsigned LW = S.Context.getIntWidth(LT),
7284 RW = S.Context.getIntWidth(RT);
7285
7286 // If they're different widths, use the signed type.
7287 if (LW > RW) return LT;
7288 else if (LW < RW) return RT;
7289
7290 // Otherwise, use the unsigned type of the signed type's rank.
7291 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7292 assert(L == SLL || R == SLL);
7293 return S.Context.UnsignedLongLongTy;
7294 }
7295
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007296 /// \brief Helper method to factor out the common pattern of adding overloads
7297 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007298 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007299 bool HasVolatile,
7300 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007301 QualType ParamTypes[2] = {
7302 S.Context.getLValueReferenceType(CandidateTy),
7303 S.Context.IntTy
7304 };
7305
7306 // Non-volatile version.
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
7312 // Use a heuristic to reduce number of builtin candidates in the set:
7313 // add volatile version only if there are conversions to a volatile type.
7314 if (HasVolatile) {
7315 ParamTypes[0] =
7316 S.Context.getLValueReferenceType(
7317 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007318 if (Args.size() == 1)
7319 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007320 else
Richard Smithe54c3072013-05-05 15:51:06 +00007321 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007323
7324 // Add restrict version only if there are conversions to a restrict type
7325 // and our candidate type is a non-restrict-qualified pointer.
7326 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7327 !CandidateTy.isRestrictQualified()) {
7328 ParamTypes[0]
7329 = S.Context.getLValueReferenceType(
7330 S.Context.getCVRQualifiedType(CandidateTy, 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 if (HasVolatile) {
7337 ParamTypes[0]
7338 = S.Context.getLValueReferenceType(
7339 S.Context.getCVRQualifiedType(CandidateTy,
7340 (Qualifiers::Volatile |
7341 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007342 if (Args.size() == 1)
7343 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007344 else
Richard Smithe54c3072013-05-05 15:51:06 +00007345 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007346 }
7347 }
7348
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007349 }
7350
7351public:
7352 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007353 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007354 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007355 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007356 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007358 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007359 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007360 HasArithmeticOrEnumeralCandidateType(
7361 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007362 CandidateTypes(CandidateTypes),
7363 CandidateSet(CandidateSet) {
7364 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007365 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007366 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007367 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007368 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007369 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007370 assert(getArithmeticType(FirstPromotedArithmeticType)
7371 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007372 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007373 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007374 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007375 "Invalid last promoted arithmetic type");
7376 }
7377
7378 // C++ [over.built]p3:
7379 //
7380 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7381 // is either volatile or empty, there exist candidate operator
7382 // functions of the form
7383 //
7384 // VQ T& operator++(VQ T&);
7385 // T operator++(VQ T&, int);
7386 //
7387 // C++ [over.built]p4:
7388 //
7389 // For every pair (T, VQ), where T is an arithmetic type other
7390 // than bool, and VQ is either volatile or empty, there exist
7391 // candidate operator functions of the form
7392 //
7393 // VQ T& operator--(VQ T&);
7394 // T operator--(VQ T&, int);
7395 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007396 if (!HasArithmeticOrEnumeralCandidateType)
7397 return;
7398
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007399 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7400 Arith < NumArithmeticTypes; ++Arith) {
7401 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007402 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007403 VisibleTypeConversionsQuals.hasVolatile(),
7404 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007405 }
7406 }
7407
7408 // C++ [over.built]p5:
7409 //
7410 // For every pair (T, VQ), where T is a cv-qualified or
7411 // cv-unqualified object type, and VQ is either volatile or
7412 // empty, there exist candidate operator functions of the form
7413 //
7414 // T*VQ& operator++(T*VQ&);
7415 // T*VQ& operator--(T*VQ&);
7416 // T* operator++(T*VQ&, int);
7417 // T* operator--(T*VQ&, int);
7418 void addPlusPlusMinusMinusPointerOverloads() {
7419 for (BuiltinCandidateTypeSet::iterator
7420 Ptr = CandidateTypes[0].pointer_begin(),
7421 PtrEnd = CandidateTypes[0].pointer_end();
7422 Ptr != PtrEnd; ++Ptr) {
7423 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007424 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 continue;
7426
7427 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007428 (!(*Ptr).isVolatileQualified() &&
7429 VisibleTypeConversionsQuals.hasVolatile()),
7430 (!(*Ptr).isRestrictQualified() &&
7431 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007432 }
7433 }
7434
7435 // C++ [over.built]p6:
7436 // For every cv-qualified or cv-unqualified object type T, there
7437 // exist candidate operator functions of the form
7438 //
7439 // T& operator*(T*);
7440 //
7441 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007443 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007444 // T& operator*(T*);
7445 void addUnaryStarPointerOverloads() {
7446 for (BuiltinCandidateTypeSet::iterator
7447 Ptr = CandidateTypes[0].pointer_begin(),
7448 PtrEnd = CandidateTypes[0].pointer_end();
7449 Ptr != PtrEnd; ++Ptr) {
7450 QualType ParamTy = *Ptr;
7451 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007452 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7453 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454
Douglas Gregor02824322011-01-26 19:30:28 +00007455 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7456 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7457 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007458
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007460 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 }
7462 }
7463
7464 // C++ [over.built]p9:
7465 // For every promoted arithmetic type T, there exist candidate
7466 // operator functions of the form
7467 //
7468 // T operator+(T);
7469 // T operator-(T);
7470 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007471 if (!HasArithmeticOrEnumeralCandidateType)
7472 return;
7473
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 for (unsigned Arith = FirstPromotedArithmeticType;
7475 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007476 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007477 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007478 }
7479
7480 // Extension: We also add these operators for vector types.
7481 for (BuiltinCandidateTypeSet::iterator
7482 Vec = CandidateTypes[0].vector_begin(),
7483 VecEnd = CandidateTypes[0].vector_end();
7484 Vec != VecEnd; ++Vec) {
7485 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007486 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007487 }
7488 }
7489
7490 // C++ [over.built]p8:
7491 // For every type T, there exist candidate operator functions of
7492 // the form
7493 //
7494 // T* operator+(T*);
7495 void addUnaryPlusPointerOverloads() {
7496 for (BuiltinCandidateTypeSet::iterator
7497 Ptr = CandidateTypes[0].pointer_begin(),
7498 PtrEnd = CandidateTypes[0].pointer_end();
7499 Ptr != PtrEnd; ++Ptr) {
7500 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007501 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007502 }
7503 }
7504
7505 // C++ [over.built]p10:
7506 // For every promoted integral type T, there exist candidate
7507 // operator functions of the form
7508 //
7509 // T operator~(T);
7510 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007511 if (!HasArithmeticOrEnumeralCandidateType)
7512 return;
7513
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 for (unsigned Int = FirstPromotedIntegralType;
7515 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007516 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007517 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007518 }
7519
7520 // Extension: We also add this operator for vector types.
7521 for (BuiltinCandidateTypeSet::iterator
7522 Vec = CandidateTypes[0].vector_begin(),
7523 VecEnd = CandidateTypes[0].vector_end();
7524 Vec != VecEnd; ++Vec) {
7525 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007526 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007527 }
7528 }
7529
7530 // C++ [over.match.oper]p16:
7531 // For every pointer to member type T, there exist candidate operator
7532 // functions of the form
7533 //
7534 // bool operator==(T,T);
7535 // bool operator!=(T,T);
7536 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7537 /// Set of (canonical) types that we've already handled.
7538 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7539
Richard Smithe54c3072013-05-05 15:51:06 +00007540 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007541 for (BuiltinCandidateTypeSet::iterator
7542 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7543 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7544 MemPtr != MemPtrEnd;
7545 ++MemPtr) {
7546 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007547 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007548 continue;
7549
7550 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007551 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007552 }
7553 }
7554 }
7555
7556 // C++ [over.built]p15:
7557 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007558 // For every T, where T is an enumeration type, a pointer type, or
7559 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007560 //
7561 // bool operator<(T, T);
7562 // bool operator>(T, T);
7563 // bool operator<=(T, T);
7564 // bool operator>=(T, T);
7565 // bool operator==(T, T);
7566 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007567 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007568 // C++ [over.match.oper]p3:
7569 // [...]the built-in candidates include all of the candidate operator
7570 // functions defined in 13.6 that, compared to the given operator, [...]
7571 // do not have the same parameter-type-list as any non-template non-member
7572 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007573 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007574 // Note that in practice, this only affects enumeration types because there
7575 // aren't any built-in candidates of record type, and a user-defined operator
7576 // must have an operand of record or enumeration type. Also, the only other
7577 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007578 // cannot be overloaded for enumeration types, so this is the only place
7579 // where we must suppress candidates like this.
7580 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7581 UserDefinedBinaryOperators;
7582
Richard Smithe54c3072013-05-05 15:51:06 +00007583 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007584 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7585 CandidateTypes[ArgIdx].enumeration_end()) {
7586 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7587 CEnd = CandidateSet.end();
7588 C != CEnd; ++C) {
7589 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7590 continue;
7591
Eli Friedman14f082b2012-09-18 21:52:24 +00007592 if (C->Function->isFunctionTemplateSpecialization())
7593 continue;
7594
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007595 QualType FirstParamType =
7596 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7597 QualType SecondParamType =
7598 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7599
7600 // Skip if either parameter isn't of enumeral type.
7601 if (!FirstParamType->isEnumeralType() ||
7602 !SecondParamType->isEnumeralType())
7603 continue;
7604
7605 // Add this operator to the set of known user-defined operators.
7606 UserDefinedBinaryOperators.insert(
7607 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7608 S.Context.getCanonicalType(SecondParamType)));
7609 }
7610 }
7611 }
7612
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 /// Set of (canonical) types that we've already handled.
7614 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7615
Richard Smithe54c3072013-05-05 15:51:06 +00007616 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007617 for (BuiltinCandidateTypeSet::iterator
7618 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7619 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7620 Ptr != PtrEnd; ++Ptr) {
7621 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007622 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 continue;
7624
7625 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007626 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 }
7628 for (BuiltinCandidateTypeSet::iterator
7629 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7630 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7631 Enum != EnumEnd; ++Enum) {
7632 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7633
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007634 // Don't add the same builtin candidate twice, or if a user defined
7635 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007636 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007637 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7638 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639 continue;
7640
7641 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007642 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007644
7645 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7646 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007647 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007648 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007649 NullPtrTy))) {
7650 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007651 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007652 CandidateSet);
7653 }
7654 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 }
7656 }
7657
7658 // C++ [over.built]p13:
7659 //
7660 // For every cv-qualified or cv-unqualified object type T
7661 // there exist candidate operator functions of the form
7662 //
7663 // T* operator+(T*, ptrdiff_t);
7664 // T& operator[](T*, ptrdiff_t); [BELOW]
7665 // T* operator-(T*, ptrdiff_t);
7666 // T* operator+(ptrdiff_t, T*);
7667 // T& operator[](ptrdiff_t, T*); [BELOW]
7668 //
7669 // C++ [over.built]p14:
7670 //
7671 // For every T, where T is a pointer to object type, there
7672 // exist candidate operator functions of the form
7673 //
7674 // ptrdiff_t operator-(T, T);
7675 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7676 /// Set of (canonical) types that we've already handled.
7677 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7678
7679 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007680 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007681 S.Context.getPointerDiffType(),
7682 S.Context.getPointerDiffType(),
7683 };
7684 for (BuiltinCandidateTypeSet::iterator
7685 Ptr = CandidateTypes[Arg].pointer_begin(),
7686 PtrEnd = CandidateTypes[Arg].pointer_end();
7687 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007688 QualType PointeeTy = (*Ptr)->getPointeeType();
7689 if (!PointeeTy->isObjectType())
7690 continue;
7691
Eric Christopher9207a522015-08-21 16:24:01 +00007692 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 if (Arg == 0 || Op == OO_Plus) {
7694 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7695 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007696 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007697 }
7698 if (Op == OO_Minus) {
7699 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007700 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007701 continue;
7702
7703 QualType ParamTypes[2] = { *Ptr, *Ptr };
7704 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007705 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 }
7707 }
7708 }
7709 }
7710
7711 // C++ [over.built]p12:
7712 //
7713 // For every pair of promoted arithmetic types L and R, there
7714 // exist candidate operator functions of the form
7715 //
7716 // LR operator*(L, R);
7717 // LR operator/(L, R);
7718 // LR operator+(L, R);
7719 // LR operator-(L, R);
7720 // bool operator<(L, R);
7721 // bool operator>(L, R);
7722 // bool operator<=(L, R);
7723 // bool operator>=(L, R);
7724 // bool operator==(L, R);
7725 // bool operator!=(L, R);
7726 //
7727 // where LR is the result of the usual arithmetic conversions
7728 // between types L and R.
7729 //
7730 // C++ [over.built]p24:
7731 //
7732 // For every pair of promoted arithmetic types L and R, there exist
7733 // candidate operator functions of the form
7734 //
7735 // LR operator?(bool, L, R);
7736 //
7737 // where LR is the result of the usual arithmetic conversions
7738 // between types L and R.
7739 // Our candidates ignore the first parameter.
7740 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007741 if (!HasArithmeticOrEnumeralCandidateType)
7742 return;
7743
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007744 for (unsigned Left = FirstPromotedArithmeticType;
7745 Left < LastPromotedArithmeticType; ++Left) {
7746 for (unsigned Right = FirstPromotedArithmeticType;
7747 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007748 QualType LandR[2] = { getArithmeticType(Left),
7749 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 QualType Result =
7751 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007752 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007753 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754 }
7755 }
7756
7757 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7758 // conditional operator for vector types.
7759 for (BuiltinCandidateTypeSet::iterator
7760 Vec1 = CandidateTypes[0].vector_begin(),
7761 Vec1End = CandidateTypes[0].vector_end();
7762 Vec1 != Vec1End; ++Vec1) {
7763 for (BuiltinCandidateTypeSet::iterator
7764 Vec2 = CandidateTypes[1].vector_begin(),
7765 Vec2End = CandidateTypes[1].vector_end();
7766 Vec2 != Vec2End; ++Vec2) {
7767 QualType LandR[2] = { *Vec1, *Vec2 };
7768 QualType Result = S.Context.BoolTy;
7769 if (!isComparison) {
7770 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7771 Result = *Vec1;
7772 else
7773 Result = *Vec2;
7774 }
7775
Richard Smithe54c3072013-05-05 15:51:06 +00007776 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007777 }
7778 }
7779 }
7780
7781 // C++ [over.built]p17:
7782 //
7783 // For every pair of promoted integral types L and R, there
7784 // exist candidate operator functions of the form
7785 //
7786 // LR operator%(L, R);
7787 // LR operator&(L, R);
7788 // LR operator^(L, R);
7789 // LR operator|(L, R);
7790 // L operator<<(L, R);
7791 // L operator>>(L, R);
7792 //
7793 // where LR is the result of the usual arithmetic conversions
7794 // between types L and R.
7795 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007796 if (!HasArithmeticOrEnumeralCandidateType)
7797 return;
7798
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 for (unsigned Left = FirstPromotedIntegralType;
7800 Left < LastPromotedIntegralType; ++Left) {
7801 for (unsigned Right = FirstPromotedIntegralType;
7802 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007803 QualType LandR[2] = { getArithmeticType(Left),
7804 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007805 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7806 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007807 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007808 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 }
7810 }
7811 }
7812
7813 // C++ [over.built]p20:
7814 //
7815 // For every pair (T, VQ), where T is an enumeration or
7816 // pointer to member type and VQ is either volatile or
7817 // empty, there exist candidate operator functions of the form
7818 //
7819 // VQ T& operator=(VQ T&, T);
7820 void addAssignmentMemberPointerOrEnumeralOverloads() {
7821 /// Set of (canonical) types that we've already handled.
7822 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7823
7824 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7825 for (BuiltinCandidateTypeSet::iterator
7826 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7827 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7828 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007829 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007830 continue;
7831
Richard Smithe54c3072013-05-05 15:51:06 +00007832 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833 }
7834
7835 for (BuiltinCandidateTypeSet::iterator
7836 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7837 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7838 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007839 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007840 continue;
7841
Richard Smithe54c3072013-05-05 15:51:06 +00007842 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007843 }
7844 }
7845 }
7846
7847 // C++ [over.built]p19:
7848 //
7849 // For every pair (T, VQ), where T is any type and VQ is either
7850 // volatile or empty, there exist candidate operator functions
7851 // of the form
7852 //
7853 // T*VQ& operator=(T*VQ&, T*);
7854 //
7855 // C++ [over.built]p21:
7856 //
7857 // For every pair (T, VQ), where T is a cv-qualified or
7858 // cv-unqualified object type and VQ is either volatile or
7859 // empty, there exist candidate operator functions of the form
7860 //
7861 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7862 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7863 void addAssignmentPointerOverloads(bool isEqualOp) {
7864 /// Set of (canonical) types that we've already handled.
7865 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7866
7867 for (BuiltinCandidateTypeSet::iterator
7868 Ptr = CandidateTypes[0].pointer_begin(),
7869 PtrEnd = CandidateTypes[0].pointer_end();
7870 Ptr != PtrEnd; ++Ptr) {
7871 // If this is operator=, keep track of the builtin candidates we added.
7872 if (isEqualOp)
7873 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007874 else if (!(*Ptr)->getPointeeType()->isObjectType())
7875 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007876
7877 // non-volatile version
7878 QualType ParamTypes[2] = {
7879 S.Context.getLValueReferenceType(*Ptr),
7880 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7881 };
Richard Smithe54c3072013-05-05 15:51:06 +00007882 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007883 /*IsAssigmentOperator=*/ isEqualOp);
7884
Douglas Gregor5bee2582012-06-04 00:15:09 +00007885 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7886 VisibleTypeConversionsQuals.hasVolatile();
7887 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 // volatile version
7889 ParamTypes[0] =
7890 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007891 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007892 /*IsAssigmentOperator=*/isEqualOp);
7893 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007894
7895 if (!(*Ptr).isRestrictQualified() &&
7896 VisibleTypeConversionsQuals.hasRestrict()) {
7897 // restrict version
7898 ParamTypes[0]
7899 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007900 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007901 /*IsAssigmentOperator=*/isEqualOp);
7902
7903 if (NeedVolatile) {
7904 // volatile restrict version
7905 ParamTypes[0]
7906 = S.Context.getLValueReferenceType(
7907 S.Context.getCVRQualifiedType(*Ptr,
7908 (Qualifiers::Volatile |
7909 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007910 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007911 /*IsAssigmentOperator=*/isEqualOp);
7912 }
7913 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007914 }
7915
7916 if (isEqualOp) {
7917 for (BuiltinCandidateTypeSet::iterator
7918 Ptr = CandidateTypes[1].pointer_begin(),
7919 PtrEnd = CandidateTypes[1].pointer_end();
7920 Ptr != PtrEnd; ++Ptr) {
7921 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007922 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007923 continue;
7924
Chandler Carruth8e543b32010-12-12 08:17:55 +00007925 QualType ParamTypes[2] = {
7926 S.Context.getLValueReferenceType(*Ptr),
7927 *Ptr,
7928 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007929
7930 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007931 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932 /*IsAssigmentOperator=*/true);
7933
Douglas Gregor5bee2582012-06-04 00:15:09 +00007934 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7935 VisibleTypeConversionsQuals.hasVolatile();
7936 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 // volatile version
7938 ParamTypes[0] =
7939 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007940 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7941 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007942 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007943
7944 if (!(*Ptr).isRestrictQualified() &&
7945 VisibleTypeConversionsQuals.hasRestrict()) {
7946 // restrict version
7947 ParamTypes[0]
7948 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7950 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007951
7952 if (NeedVolatile) {
7953 // volatile restrict version
7954 ParamTypes[0]
7955 = S.Context.getLValueReferenceType(
7956 S.Context.getCVRQualifiedType(*Ptr,
7957 (Qualifiers::Volatile |
7958 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7960 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007961 }
7962 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007963 }
7964 }
7965 }
7966
7967 // C++ [over.built]p18:
7968 //
7969 // For every triple (L, VQ, R), where L is an arithmetic type,
7970 // VQ is either volatile or empty, and R is a promoted
7971 // arithmetic type, there exist candidate operator functions of
7972 // the form
7973 //
7974 // VQ L& operator=(VQ L&, R);
7975 // VQ L& operator*=(VQ L&, R);
7976 // VQ L& operator/=(VQ L&, R);
7977 // VQ L& operator+=(VQ L&, R);
7978 // VQ L& operator-=(VQ L&, R);
7979 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007980 if (!HasArithmeticOrEnumeralCandidateType)
7981 return;
7982
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7984 for (unsigned Right = FirstPromotedArithmeticType;
7985 Right < LastPromotedArithmeticType; ++Right) {
7986 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007987 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007988
7989 // Add this built-in operator as a candidate (VQ is empty).
7990 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007991 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 /*IsAssigmentOperator=*/isEqualOp);
7994
7995 // Add this built-in operator as a candidate (VQ is 'volatile').
7996 if (VisibleTypeConversionsQuals.hasVolatile()) {
7997 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007998 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007999 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008001 /*IsAssigmentOperator=*/isEqualOp);
8002 }
8003 }
8004 }
8005
8006 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8007 for (BuiltinCandidateTypeSet::iterator
8008 Vec1 = CandidateTypes[0].vector_begin(),
8009 Vec1End = CandidateTypes[0].vector_end();
8010 Vec1 != Vec1End; ++Vec1) {
8011 for (BuiltinCandidateTypeSet::iterator
8012 Vec2 = CandidateTypes[1].vector_begin(),
8013 Vec2End = CandidateTypes[1].vector_end();
8014 Vec2 != Vec2End; ++Vec2) {
8015 QualType ParamTypes[2];
8016 ParamTypes[1] = *Vec2;
8017 // Add this built-in operator as a candidate (VQ is empty).
8018 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008019 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008020 /*IsAssigmentOperator=*/isEqualOp);
8021
8022 // Add this built-in operator as a candidate (VQ is 'volatile').
8023 if (VisibleTypeConversionsQuals.hasVolatile()) {
8024 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8025 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008026 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008027 /*IsAssigmentOperator=*/isEqualOp);
8028 }
8029 }
8030 }
8031 }
8032
8033 // C++ [over.built]p22:
8034 //
8035 // For every triple (L, VQ, R), where L is an integral type, VQ
8036 // is either volatile or empty, and R is a promoted integral
8037 // type, there exist candidate operator functions of the form
8038 //
8039 // VQ L& operator%=(VQ L&, R);
8040 // VQ L& operator<<=(VQ L&, R);
8041 // VQ L& operator>>=(VQ L&, R);
8042 // VQ L& operator&=(VQ L&, R);
8043 // VQ L& operator^=(VQ L&, R);
8044 // VQ L& operator|=(VQ L&, R);
8045 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008046 if (!HasArithmeticOrEnumeralCandidateType)
8047 return;
8048
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008049 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8050 for (unsigned Right = FirstPromotedIntegralType;
8051 Right < LastPromotedIntegralType; ++Right) {
8052 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008053 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054
8055 // Add this built-in operator as a candidate (VQ is empty).
8056 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008057 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008058 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 if (VisibleTypeConversionsQuals.hasVolatile()) {
8060 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008061 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8063 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008064 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008065 }
8066 }
8067 }
8068 }
8069
8070 // C++ [over.operator]p23:
8071 //
8072 // There also exist candidate operator functions of the form
8073 //
8074 // bool operator!(bool);
8075 // bool operator&&(bool, bool);
8076 // bool operator||(bool, bool);
8077 void addExclaimOverload() {
8078 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008079 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 /*IsAssignmentOperator=*/false,
8081 /*NumContextualBoolArguments=*/1);
8082 }
8083 void addAmpAmpOrPipePipeOverload() {
8084 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008085 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 /*IsAssignmentOperator=*/false,
8087 /*NumContextualBoolArguments=*/2);
8088 }
8089
8090 // C++ [over.built]p13:
8091 //
8092 // For every cv-qualified or cv-unqualified object type T there
8093 // exist candidate operator functions of the form
8094 //
8095 // T* operator+(T*, ptrdiff_t); [ABOVE]
8096 // T& operator[](T*, ptrdiff_t);
8097 // T* operator-(T*, ptrdiff_t); [ABOVE]
8098 // T* operator+(ptrdiff_t, T*); [ABOVE]
8099 // T& operator[](ptrdiff_t, T*);
8100 void addSubscriptOverloads() {
8101 for (BuiltinCandidateTypeSet::iterator
8102 Ptr = CandidateTypes[0].pointer_begin(),
8103 PtrEnd = CandidateTypes[0].pointer_end();
8104 Ptr != PtrEnd; ++Ptr) {
8105 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8106 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008107 if (!PointeeType->isObjectType())
8108 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008110 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8111
8112 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008113 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008114 }
8115
8116 for (BuiltinCandidateTypeSet::iterator
8117 Ptr = CandidateTypes[1].pointer_begin(),
8118 PtrEnd = CandidateTypes[1].pointer_end();
8119 Ptr != PtrEnd; ++Ptr) {
8120 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8121 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008122 if (!PointeeType->isObjectType())
8123 continue;
8124
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008125 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8126
8127 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008128 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008129 }
8130 }
8131
8132 // C++ [over.built]p11:
8133 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8134 // C1 is the same type as C2 or is a derived class of C2, T is an object
8135 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8136 // there exist candidate operator functions of the form
8137 //
8138 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8139 //
8140 // where CV12 is the union of CV1 and CV2.
8141 void addArrowStarOverloads() {
8142 for (BuiltinCandidateTypeSet::iterator
8143 Ptr = CandidateTypes[0].pointer_begin(),
8144 PtrEnd = CandidateTypes[0].pointer_end();
8145 Ptr != PtrEnd; ++Ptr) {
8146 QualType C1Ty = (*Ptr);
8147 QualType C1;
8148 QualifierCollector Q1;
8149 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8150 if (!isa<RecordType>(C1))
8151 continue;
8152 // heuristic to reduce number of builtin candidates in the set.
8153 // Add volatile/restrict version only if there are conversions to a
8154 // volatile/restrict type.
8155 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8156 continue;
8157 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8158 continue;
8159 for (BuiltinCandidateTypeSet::iterator
8160 MemPtr = CandidateTypes[1].member_pointer_begin(),
8161 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8162 MemPtr != MemPtrEnd; ++MemPtr) {
8163 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8164 QualType C2 = QualType(mptr->getClass(), 0);
8165 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008166 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 break;
8168 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8169 // build CV12 T&
8170 QualType T = mptr->getPointeeType();
8171 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8172 T.isVolatileQualified())
8173 continue;
8174 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8175 T.isRestrictQualified())
8176 continue;
8177 T = Q1.apply(S.Context, T);
8178 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008179 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008180 }
8181 }
8182 }
8183
8184 // Note that we don't consider the first argument, since it has been
8185 // contextually converted to bool long ago. The candidates below are
8186 // therefore added as binary.
8187 //
8188 // C++ [over.built]p25:
8189 // For every type T, where T is a pointer, pointer-to-member, or scoped
8190 // enumeration type, there exist candidate operator functions of the form
8191 //
8192 // T operator?(bool, T, T);
8193 //
8194 void addConditionalOperatorOverloads() {
8195 /// Set of (canonical) types that we've already handled.
8196 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8197
8198 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8199 for (BuiltinCandidateTypeSet::iterator
8200 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8201 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8202 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008203 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008204 continue;
8205
8206 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008207 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 }
8209
8210 for (BuiltinCandidateTypeSet::iterator
8211 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8212 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8213 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008214 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008215 continue;
8216
8217 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008218 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008219 }
8220
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008221 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008222 for (BuiltinCandidateTypeSet::iterator
8223 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8224 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8225 Enum != EnumEnd; ++Enum) {
8226 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8227 continue;
8228
David Blaikie82e95a32014-11-19 07:49:47 +00008229 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008230 continue;
8231
8232 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008233 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008234 }
8235 }
8236 }
8237 }
8238};
8239
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008240} // end anonymous namespace
8241
8242/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8243/// operator overloads to the candidate set (C++ [over.built]), based
8244/// on the operator @p Op and the arguments given. For example, if the
8245/// operator is a binary '+', this routine might add "int
8246/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008247void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8248 SourceLocation OpLoc,
8249 ArrayRef<Expr *> Args,
8250 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008251 // Find all of the types that the arguments can convert to, but only
8252 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008253 // that make use of these types. Also record whether we encounter non-record
8254 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008255 Qualifiers VisibleTypeConversionsQuals;
8256 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008257 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008258 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008259
8260 bool HasNonRecordCandidateType = false;
8261 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008262 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008263 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008264 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008265 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8266 OpLoc,
8267 true,
8268 (Op == OO_Exclaim ||
8269 Op == OO_AmpAmp ||
8270 Op == OO_PipePipe),
8271 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008272 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8273 CandidateTypes[ArgIdx].hasNonRecordTypes();
8274 HasArithmeticOrEnumeralCandidateType =
8275 HasArithmeticOrEnumeralCandidateType ||
8276 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008277 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008278
Chandler Carruth00a38332010-12-13 01:44:01 +00008279 // Exit early when no non-record types have been added to the candidate set
8280 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008281 //
8282 // We can't exit early for !, ||, or &&, since there we have always have
8283 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008284 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008285 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008286 return;
8287
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008288 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008289 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008290 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008291 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008292 CandidateTypes, CandidateSet);
8293
8294 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008295 switch (Op) {
8296 case OO_None:
8297 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008298 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008299
Chandler Carruth5184de02010-12-12 08:51:33 +00008300 case OO_New:
8301 case OO_Delete:
8302 case OO_Array_New:
8303 case OO_Array_Delete:
8304 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008305 llvm_unreachable(
8306 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008307
8308 case OO_Comma:
8309 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008310 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008311 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008312 // -- For the operator ',', the unary operator '&', the
8313 // operator '->', or the operator 'co_await', the
8314 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008315 break;
8316
8317 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008318 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008319 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008320 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008321
8322 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008323 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008324 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008325 } else {
8326 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8328 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008329 break;
8330
Chandler Carruth5184de02010-12-12 08:51:33 +00008331 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008332 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008333 OpBuilder.addUnaryStarPointerOverloads();
8334 else
8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8336 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337
Chandler Carruth5184de02010-12-12 08:51:33 +00008338 case OO_Slash:
8339 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008340 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008341
8342 case OO_PlusPlus:
8343 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008344 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8345 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008346 break;
8347
Douglas Gregor84605ae2009-08-24 13:43:27 +00008348 case OO_EqualEqual:
8349 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008350 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008351 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008352
Douglas Gregora11693b2008-11-12 17:17:38 +00008353 case OO_Less:
8354 case OO_Greater:
8355 case OO_LessEqual:
8356 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008357 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008358 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8359 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008360
Douglas Gregora11693b2008-11-12 17:17:38 +00008361 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008362 case OO_Caret:
8363 case OO_Pipe:
8364 case OO_LessLess:
8365 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008366 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008367 break;
8368
Chandler Carruth5184de02010-12-12 08:51:33 +00008369 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008370 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008371 // C++ [over.match.oper]p3:
8372 // -- For the operator ',', the unary operator '&', or the
8373 // operator '->', the built-in candidates set is empty.
8374 break;
8375
8376 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8377 break;
8378
8379 case OO_Tilde:
8380 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8381 break;
8382
Douglas Gregora11693b2008-11-12 17:17:38 +00008383 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008384 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008385 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008386
8387 case OO_PlusEqual:
8388 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008389 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008390 // Fall through.
8391
8392 case OO_StarEqual:
8393 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008394 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008395 break;
8396
8397 case OO_PercentEqual:
8398 case OO_LessLessEqual:
8399 case OO_GreaterGreaterEqual:
8400 case OO_AmpEqual:
8401 case OO_CaretEqual:
8402 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008404 break;
8405
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008406 case OO_Exclaim:
8407 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008408 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008409
Douglas Gregora11693b2008-11-12 17:17:38 +00008410 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008411 case OO_PipePipe:
8412 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008413 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008414
8415 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008416 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008417 break;
8418
8419 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008420 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008421 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008422
8423 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008424 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008425 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8426 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008427 }
8428}
8429
Douglas Gregore254f902009-02-04 00:32:51 +00008430/// \brief Add function candidates found via argument-dependent lookup
8431/// to the set of overloading candidates.
8432///
8433/// This routine performs argument-dependent name lookup based on the
8434/// given function name (which may also be an operator name) and adds
8435/// all of the overload candidates found by ADL to the overload
8436/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008437void
Douglas Gregore254f902009-02-04 00:32:51 +00008438Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008439 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008440 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008441 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008442 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008443 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008444 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008445
John McCall91f61fc2010-01-26 06:04:06 +00008446 // FIXME: This approach for uniquing ADL results (and removing
8447 // redundant candidates from the set) relies on pointer-equality,
8448 // which means we need to key off the canonical decl. However,
8449 // always going back to the canonical decl might not get us the
8450 // right set of default arguments. What default arguments are
8451 // we supposed to consider on ADL candidates, anyway?
8452
Douglas Gregorcabea402009-09-22 15:41:20 +00008453 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008454 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008455
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008456 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008457 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8458 CandEnd = CandidateSet.end();
8459 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008460 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008461 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008462 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008463 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008464 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008465
8466 // For each of the ADL candidates we found, add it to the overload
8467 // set.
John McCall8fe68082010-01-26 07:16:45 +00008468 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008469 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008470 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008471 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008472 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008473
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008474 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8475 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008476 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008477 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008478 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008479 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008480 }
Douglas Gregore254f902009-02-04 00:32:51 +00008481}
8482
George Burgess IV2a6150d2015-10-16 01:17:38 +00008483// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8484// Cand2 for overloading. This function assumes that all of the enable_if attrs
8485// on Cand1 and Cand2 have conditions that evaluate to true.
8486//
8487// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8488// Cand1's first N enable_if attributes have precisely the same conditions as
8489// Cand2's first N enable_if attributes (where N = the number of enable_if
8490// attributes on Cand2), and Cand1 has more than N enable_if attributes.
George Burgess IV6da4c202016-03-23 02:33:58 +00008491static bool hasBetterEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
George Burgess IV2a6150d2015-10-16 01:17:38 +00008492 const FunctionDecl *Cand2) {
8493
8494 // FIXME: The next several lines are just
8495 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8496 // instead of reverse order which is how they're stored in the AST.
8497 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8498 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8499
8500 // Candidate 1 is better if it has strictly more attributes and
8501 // the common sequence is identical.
8502 if (Cand1Attrs.size() <= Cand2Attrs.size())
8503 return false;
8504
8505 auto Cand1I = Cand1Attrs.begin();
8506 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8507 for (auto &Cand2A : Cand2Attrs) {
8508 Cand1ID.clear();
8509 Cand2ID.clear();
8510
8511 auto &Cand1A = *Cand1I++;
8512 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8513 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8514 if (Cand1ID != Cand2ID)
8515 return false;
8516 }
8517
8518 return true;
8519}
8520
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008521/// isBetterOverloadCandidate - Determines whether the first overload
8522/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008523bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8524 const OverloadCandidate &Cand2,
8525 SourceLocation Loc,
8526 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008527 // Define viable functions to be better candidates than non-viable
8528 // functions.
8529 if (!Cand2.Viable)
8530 return Cand1.Viable;
8531 else if (!Cand1.Viable)
8532 return false;
8533
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008534 // C++ [over.match.best]p1:
8535 //
8536 // -- if F is a static member function, ICS1(F) is defined such
8537 // that ICS1(F) is neither better nor worse than ICS1(G) for
8538 // any function G, and, symmetrically, ICS1(G) is neither
8539 // better nor worse than ICS1(F).
8540 unsigned StartArg = 0;
8541 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8542 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008543
Douglas Gregord3cb3562009-07-07 23:38:56 +00008544 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008545 // A viable function F1 is defined to be a better function than another
8546 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008547 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008548 unsigned NumArgs = Cand1.NumConversions;
8549 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008550 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008551 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008552 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008553 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008554 Cand2.Conversions[ArgIdx])) {
8555 case ImplicitConversionSequence::Better:
8556 // Cand1 has a better conversion sequence.
8557 HasBetterConversion = true;
8558 break;
8559
8560 case ImplicitConversionSequence::Worse:
8561 // Cand1 can't be better than Cand2.
8562 return false;
8563
8564 case ImplicitConversionSequence::Indistinguishable:
8565 // Do nothing.
8566 break;
8567 }
8568 }
8569
Mike Stump11289f42009-09-09 15:08:12 +00008570 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008571 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008572 if (HasBetterConversion)
8573 return true;
8574
Douglas Gregora1f013e2008-11-07 22:36:19 +00008575 // -- the context is an initialization by user-defined conversion
8576 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8577 // from the return type of F1 to the destination type (i.e.,
8578 // the type of the entity being initialized) is a better
8579 // conversion sequence than the standard conversion sequence
8580 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008581 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008582 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008583 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008584 // First check whether we prefer one of the conversion functions over the
8585 // other. This only distinguishes the results in non-standard, extension
8586 // cases such as the conversion from a lambda closure type to a function
8587 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008588 ImplicitConversionSequence::CompareKind Result =
8589 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8590 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008591 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008592 Cand1.FinalConversion,
8593 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008594
Richard Smithec2748a2014-05-17 04:36:39 +00008595 if (Result != ImplicitConversionSequence::Indistinguishable)
8596 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008597
8598 // FIXME: Compare kind of reference binding if conversion functions
8599 // convert to a reference type used in direct reference binding, per
8600 // C++14 [over.match.best]p1 section 2 bullet 3.
8601 }
8602
8603 // -- F1 is a non-template function and F2 is a function template
8604 // specialization, or, if not that,
8605 bool Cand1IsSpecialization = Cand1.Function &&
8606 Cand1.Function->getPrimaryTemplate();
8607 bool Cand2IsSpecialization = Cand2.Function &&
8608 Cand2.Function->getPrimaryTemplate();
8609 if (Cand1IsSpecialization != Cand2IsSpecialization)
8610 return Cand2IsSpecialization;
8611
8612 // -- F1 and F2 are function template specializations, and the function
8613 // template for F1 is more specialized than the template for F2
8614 // according to the partial ordering rules described in 14.5.5.2, or,
8615 // if not that,
8616 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8617 if (FunctionTemplateDecl *BetterTemplate
8618 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8619 Cand2.Function->getPrimaryTemplate(),
8620 Loc,
8621 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8622 : TPOC_Call,
8623 Cand1.ExplicitCallArguments,
8624 Cand2.ExplicitCallArguments))
8625 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008626 }
8627
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008628 // Check for enable_if value-based overload resolution.
8629 if (Cand1.Function && Cand2.Function &&
8630 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008631 Cand2.Function->hasAttr<EnableIfAttr>()))
8632 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008633
Artem Belevich94a55e82015-09-22 17:22:59 +00008634 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8635 Cand1.Function && Cand2.Function) {
8636 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8637 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8638 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8639 }
8640
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008641 bool HasPS1 = Cand1.Function != nullptr &&
8642 functionHasPassObjectSizeParams(Cand1.Function);
8643 bool HasPS2 = Cand2.Function != nullptr &&
8644 functionHasPassObjectSizeParams(Cand2.Function);
8645 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008646}
8647
Richard Smith2dbe4042015-11-04 19:26:32 +00008648/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008649/// name lookup and overload resolution. This applies when the same internal/no
8650/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008651/// the same header). In such a case, we don't consider the declarations to
8652/// declare the same entity, but we also don't want lookups with both
8653/// declarations visible to be ambiguous in some cases (this happens when using
8654/// a modularized libstdc++).
8655bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8656 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008657 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8658 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8659 if (!VA || !VB)
8660 return false;
8661
8662 // The declarations must be declaring the same name as an internal linkage
8663 // entity in different modules.
8664 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8665 VB->getDeclContext()->getRedeclContext()) ||
8666 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8667 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8668 VA->isExternallyVisible() || VB->isExternallyVisible())
8669 return false;
8670
8671 // Check that the declarations appear to be equivalent.
8672 //
8673 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8674 // For constants and functions, we should check the initializer or body is
8675 // the same. For non-constant variables, we shouldn't allow it at all.
8676 if (Context.hasSameType(VA->getType(), VB->getType()))
8677 return true;
8678
8679 // Enum constants within unnamed enumerations will have different types, but
8680 // may still be similar enough to be interchangeable for our purposes.
8681 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8682 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8683 // Only handle anonymous enums. If the enumerations were named and
8684 // equivalent, they would have been merged to the same type.
8685 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8686 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8687 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8688 !Context.hasSameType(EnumA->getIntegerType(),
8689 EnumB->getIntegerType()))
8690 return false;
8691 // Allow this only if the value is the same for both enumerators.
8692 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8693 }
8694 }
8695
8696 // Nothing else is sufficiently similar.
8697 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008698}
8699
8700void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8701 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8702 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8703
8704 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8705 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8706 << !M << (M ? M->getFullModuleName() : "");
8707
8708 for (auto *E : Equiv) {
8709 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8710 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8711 << !M << (M ? M->getFullModuleName() : "");
8712 }
Richard Smith896c66e2015-10-21 07:13:52 +00008713}
8714
Mike Stump11289f42009-09-09 15:08:12 +00008715/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008716/// within an overload candidate set.
8717///
James Dennettffad8b72012-06-22 08:10:18 +00008718/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008719/// which overload resolution occurs.
8720///
James Dennettffad8b72012-06-22 08:10:18 +00008721/// \param Best If overload resolution was successful or found a deleted
8722/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008723///
8724/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008725OverloadingResult
8726OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008727 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008728 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008729 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8730 std::transform(begin(), end(), std::back_inserter(Candidates),
8731 [](OverloadCandidate &Cand) { return &Cand; });
8732
8733 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8734 // but accepted by both clang and NVCC. However during a particular
8735 // compilation mode only one call variant is viable. We need to
8736 // exclude non-viable overload candidates from consideration based
8737 // only on their host/device attributes. Specifically, if one
8738 // candidate call is WrongSide and the other is SameSide, we ignore
8739 // the WrongSide candidate.
8740 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) {
8741 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8742 bool ContainsSameSideCandidate =
8743 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8744 return Cand->Function &&
8745 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8746 Sema::CFP_SameSide;
8747 });
8748 if (ContainsSameSideCandidate) {
8749 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8750 return Cand->Function &&
8751 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8752 Sema::CFP_WrongSide;
8753 };
8754 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8755 IsWrongSideCandidate),
8756 Candidates.end());
8757 }
8758 }
8759
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008760 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008761 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008762 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008763 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008764 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008765 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008766 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008767
8768 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008769 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008770 return OR_No_Viable_Function;
8771
Richard Smith2dbe4042015-11-04 19:26:32 +00008772 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008773
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008774 // Make sure that this function is better than every other viable
8775 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008776 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008777 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008778 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008779 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008780 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008781 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8782 Cand->Function)) {
8783 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008784 continue;
8785 }
8786
John McCall5c32be02010-08-24 20:38:10 +00008787 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008788 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008789 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008790 }
Mike Stump11289f42009-09-09 15:08:12 +00008791
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008792 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008793 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008794 (Best->Function->isDeleted() ||
8795 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008796 return OR_Deleted;
8797
Richard Smith2dbe4042015-11-04 19:26:32 +00008798 if (!EquivalentCands.empty())
8799 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8800 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008801
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008802 return OR_Success;
8803}
8804
John McCall53262c92010-01-12 02:15:36 +00008805namespace {
8806
8807enum OverloadCandidateKind {
8808 oc_function,
8809 oc_method,
8810 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008811 oc_function_template,
8812 oc_method_template,
8813 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008814 oc_implicit_default_constructor,
8815 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008816 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008817 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008818 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008819 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008820};
8821
John McCalle1ac8d12010-01-13 00:25:19 +00008822OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8823 FunctionDecl *Fn,
8824 std::string &Description) {
8825 bool isTemplate = false;
8826
8827 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8828 isTemplate = true;
8829 Description = S.getTemplateArgumentBindingsText(
8830 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8831 }
John McCallfd0b2f82010-01-06 09:43:14 +00008832
8833 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008834 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008835 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008836
Sebastian Redl08905022011-02-05 19:23:19 +00008837 if (Ctor->getInheritedConstructor())
8838 return oc_implicit_inherited_constructor;
8839
Alexis Hunt119c10e2011-05-25 23:16:36 +00008840 if (Ctor->isDefaultConstructor())
8841 return oc_implicit_default_constructor;
8842
8843 if (Ctor->isMoveConstructor())
8844 return oc_implicit_move_constructor;
8845
8846 assert(Ctor->isCopyConstructor() &&
8847 "unexpected sort of implicit constructor");
8848 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008849 }
8850
8851 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8852 // This actually gets spelled 'candidate function' for now, but
8853 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008854 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008855 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008856
Alexis Hunt119c10e2011-05-25 23:16:36 +00008857 if (Meth->isMoveAssignmentOperator())
8858 return oc_implicit_move_assignment;
8859
Douglas Gregor12695102012-02-10 08:36:38 +00008860 if (Meth->isCopyAssignmentOperator())
8861 return oc_implicit_copy_assignment;
8862
8863 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8864 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008865 }
8866
John McCalle1ac8d12010-01-13 00:25:19 +00008867 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008868}
8869
Larisse Voufo98b20f12013-07-19 23:00:19 +00008870void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008871 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8872 if (!Ctor) return;
8873
8874 Ctor = Ctor->getInheritedConstructor();
8875 if (!Ctor) return;
8876
8877 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8878}
8879
John McCall53262c92010-01-12 02:15:36 +00008880} // end anonymous namespace
8881
George Burgess IV5f21c712015-10-12 19:57:04 +00008882static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8883 const FunctionDecl *FD) {
8884 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8885 bool AlwaysTrue;
8886 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8887 return false;
8888 if (!AlwaysTrue)
8889 return false;
8890 }
8891 return true;
8892}
8893
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008894/// \brief Returns true if we can take the address of the function.
8895///
8896/// \param Complain - If true, we'll emit a diagnostic
8897/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8898/// we in overload resolution?
8899/// \param Loc - The location of the statement we're complaining about. Ignored
8900/// if we're not complaining, or if we're in overload resolution.
8901static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8902 bool Complain,
8903 bool InOverloadResolution,
8904 SourceLocation Loc) {
8905 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8906 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008907 if (InOverloadResolution)
8908 S.Diag(FD->getLocStart(),
8909 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8910 else
8911 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8912 }
8913 return false;
8914 }
8915
8916 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8917 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8918 if (I == FD->param_end())
8919 return true;
8920
8921 if (Complain) {
8922 // Add one to ParamNo because it's user-facing
8923 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8924 if (InOverloadResolution)
8925 S.Diag(FD->getLocation(),
8926 diag::note_ovl_candidate_has_pass_object_size_params)
8927 << ParamNo;
8928 else
8929 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8930 << FD << ParamNo;
8931 }
8932 return false;
8933}
8934
8935static bool checkAddressOfCandidateIsAvailable(Sema &S,
8936 const FunctionDecl *FD) {
8937 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8938 /*InOverloadResolution=*/true,
8939 /*Loc=*/SourceLocation());
8940}
8941
8942bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8943 bool Complain,
8944 SourceLocation Loc) {
8945 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8946 /*InOverloadResolution=*/false,
8947 Loc);
8948}
8949
John McCall53262c92010-01-12 02:15:36 +00008950// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008951void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8952 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008953 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8954 return;
8955
John McCalle1ac8d12010-01-13 00:25:19 +00008956 std::string FnDesc;
8957 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008958 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8959 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008960
8961 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008962 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008963 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008964}
8965
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008966// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008967// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008968void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8969 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008970 assert(OverloadedExpr->getType() == Context.OverloadTy);
8971
8972 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8973 OverloadExpr *OvlExpr = Ovl.Expression;
8974
8975 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8976 IEnd = OvlExpr->decls_end();
8977 I != IEnd; ++I) {
8978 if (FunctionTemplateDecl *FunTmpl =
8979 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008980 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8981 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008982 } else if (FunctionDecl *Fun
8983 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008984 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008985 }
8986 }
8987}
8988
John McCall0d1da222010-01-12 00:44:57 +00008989/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8990/// "lead" diagnostic; it will be given two arguments, the source and
8991/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008992void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8993 Sema &S,
8994 SourceLocation CaretLoc,
8995 const PartialDiagnostic &PDiag) const {
8996 S.Diag(CaretLoc, PDiag)
8997 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008998 // FIXME: The note limiting machinery is borrowed from
8999 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9000 // refactoring here.
9001 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9002 unsigned CandsShown = 0;
9003 AmbiguousConversionSequence::const_iterator I, E;
9004 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9005 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9006 break;
9007 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00009008 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00009009 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009010 if (I != E)
9011 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009012}
9013
Richard Smith17c00b42014-11-12 01:24:00 +00009014static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009015 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009016 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9017 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009018 assert(Cand->Function && "for now, candidate must be a function");
9019 FunctionDecl *Fn = Cand->Function;
9020
9021 // There's a conversion slot for the object argument if this is a
9022 // non-constructor method. Note that 'I' corresponds the
9023 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009024 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009025 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009026 if (I == 0)
9027 isObjectArgument = true;
9028 else
9029 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009030 }
9031
John McCalle1ac8d12010-01-13 00:25:19 +00009032 std::string FnDesc;
9033 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9034
John McCall6a61b522010-01-13 09:16:55 +00009035 Expr *FromExpr = Conv.Bad.FromExpr;
9036 QualType FromTy = Conv.Bad.getFromType();
9037 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009038
John McCallfb7ad0f2010-02-02 02:42:52 +00009039 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009040 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009041 Expr *E = FromExpr->IgnoreParens();
9042 if (isa<UnaryOperator>(E))
9043 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009044 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009045
9046 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9047 << (unsigned) FnKind << FnDesc
9048 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9049 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009050 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009051 return;
9052 }
9053
John McCall6d174642010-01-23 08:10:49 +00009054 // Do some hand-waving analysis to see if the non-viability is due
9055 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009056 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9057 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9058 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9059 CToTy = RT->getPointeeType();
9060 else {
9061 // TODO: detect and diagnose the full richness of const mismatches.
9062 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009063 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9064 CFromTy = FromPT->getPointeeType();
9065 CToTy = ToPT->getPointeeType();
9066 }
John McCall47000992010-01-14 03:28:57 +00009067 }
9068
9069 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9070 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009071 Qualifiers FromQs = CFromTy.getQualifiers();
9072 Qualifiers ToQs = CToTy.getQualifiers();
9073
9074 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9075 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9076 << (unsigned) FnKind << FnDesc
9077 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9078 << FromTy
9079 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9080 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009081 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009082 return;
9083 }
9084
John McCall31168b02011-06-15 23:02:42 +00009085 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009087 << (unsigned) FnKind << FnDesc
9088 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9089 << FromTy
9090 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9091 << (unsigned) isObjectArgument << I+1;
9092 MaybeEmitInheritedConstructorNote(S, Fn);
9093 return;
9094 }
9095
Douglas Gregoraec25842011-04-26 23:16:46 +00009096 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9098 << (unsigned) FnKind << FnDesc
9099 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9100 << FromTy
9101 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9102 << (unsigned) isObjectArgument << I+1;
9103 MaybeEmitInheritedConstructorNote(S, Fn);
9104 return;
9105 }
9106
John McCall47000992010-01-14 03:28:57 +00009107 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9108 assert(CVR && "unexpected qualifiers mismatch");
9109
9110 if (isObjectArgument) {
9111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9112 << (unsigned) FnKind << FnDesc
9113 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9114 << FromTy << (CVR - 1);
9115 } else {
9116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9117 << (unsigned) FnKind << FnDesc
9118 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9119 << FromTy << (CVR - 1) << I+1;
9120 }
Sebastian Redl08905022011-02-05 19:23:19 +00009121 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009122 return;
9123 }
9124
Sebastian Redla72462c2011-09-24 17:48:32 +00009125 // Special diagnostic for failure to convert an initializer list, since
9126 // telling the user that it has type void is not useful.
9127 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9129 << (unsigned) FnKind << FnDesc
9130 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9131 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9132 MaybeEmitInheritedConstructorNote(S, Fn);
9133 return;
9134 }
9135
John McCall6d174642010-01-23 08:10:49 +00009136 // Diagnose references or pointers to incomplete types differently,
9137 // since it's far from impossible that the incompleteness triggered
9138 // the failure.
9139 QualType TempFromTy = FromTy.getNonReferenceType();
9140 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9141 TempFromTy = PTy->getPointeeType();
9142 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009143 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9145 << (unsigned) FnKind << FnDesc
9146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009147 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9148 << (unsigned) (Cand->Fix.Kind);
9149
Sebastian Redl08905022011-02-05 19:23:19 +00009150 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009151 return;
9152 }
9153
Douglas Gregor56f2e342010-06-30 23:01:39 +00009154 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009155 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009156 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9157 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9158 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9159 FromPtrTy->getPointeeType()) &&
9160 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9161 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009162 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009163 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009164 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009165 }
9166 } else if (const ObjCObjectPointerType *FromPtrTy
9167 = FromTy->getAs<ObjCObjectPointerType>()) {
9168 if (const ObjCObjectPointerType *ToPtrTy
9169 = ToTy->getAs<ObjCObjectPointerType>())
9170 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9171 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9172 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9173 FromPtrTy->getPointeeType()) &&
9174 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009175 BaseToDerivedConversion = 2;
9176 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009177 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9178 !FromTy->isIncompleteType() &&
9179 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009180 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009181 BaseToDerivedConversion = 3;
9182 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9183 ToTy.getNonReferenceType().getCanonicalType() ==
9184 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9186 << (unsigned) FnKind << FnDesc
9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9188 << (unsigned) isObjectArgument << I + 1;
9189 MaybeEmitInheritedConstructorNote(S, Fn);
9190 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009191 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009193
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009194 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009195 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009196 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009197 << (unsigned) FnKind << FnDesc
9198 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009199 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009201 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009202 return;
9203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009204
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009205 if (isa<ObjCObjectPointerType>(CFromTy) &&
9206 isa<PointerType>(CToTy)) {
9207 Qualifiers FromQs = CFromTy.getQualifiers();
9208 Qualifiers ToQs = CToTy.getQualifiers();
9209 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9211 << (unsigned) FnKind << FnDesc
9212 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9213 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9214 MaybeEmitInheritedConstructorNote(S, Fn);
9215 return;
9216 }
9217 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009218
9219 if (TakingCandidateAddress &&
9220 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9221 return;
9222
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009223 // Emit the generic diagnostic and, optionally, add the hints to it.
9224 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9225 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009226 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009227 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9228 << (unsigned) (Cand->Fix.Kind);
9229
9230 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009231 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9232 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009233 FDiag << *HI;
9234 S.Diag(Fn->getLocation(), FDiag);
9235
Sebastian Redl08905022011-02-05 19:23:19 +00009236 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009237}
9238
Larisse Voufo98b20f12013-07-19 23:00:19 +00009239/// Additional arity mismatch diagnosis specific to a function overload
9240/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9241/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009242static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9243 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009244 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009245 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009246
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009247 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009248 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009249 // right number of arguments, because only overloaded operators have
9250 // the weird behavior of overloading member and non-member functions.
9251 // Just don't report anything.
9252 if (Fn->isInvalidDecl() &&
9253 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009254 return true;
9255
9256 if (NumArgs < MinParams) {
9257 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9258 (Cand->FailureKind == ovl_fail_bad_deduction &&
9259 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9260 } else {
9261 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9262 (Cand->FailureKind == ovl_fail_bad_deduction &&
9263 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9264 }
9265
9266 return false;
9267}
9268
9269/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009270static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009271 assert(isa<FunctionDecl>(D) &&
9272 "The templated declaration should at least be a function"
9273 " when diagnosing bad template argument deduction due to too many"
9274 " or too few arguments");
9275
9276 FunctionDecl *Fn = cast<FunctionDecl>(D);
9277
9278 // TODO: treat calls to a missing default constructor as a special case
9279 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9280 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009281
John McCall6a61b522010-01-13 09:16:55 +00009282 // at least / at most / exactly
9283 unsigned mode, modeCount;
9284 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009285 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9286 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009287 mode = 0; // "at least"
9288 else
9289 mode = 2; // "exactly"
9290 modeCount = MinParams;
9291 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009292 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009293 mode = 1; // "at most"
9294 else
9295 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009296 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009297 }
9298
9299 std::string Description;
9300 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9301
Richard Smith10ff50d2012-05-11 05:16:41 +00009302 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009304 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9305 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009306 else
9307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009308 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9309 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009310 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009311}
9312
Larisse Voufo98b20f12013-07-19 23:00:19 +00009313/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009314static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9315 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009316 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9317 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9318}
Larisse Voufo47c08452013-07-19 22:53:23 +00009319
Richard Smith17c00b42014-11-12 01:24:00 +00009320static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009321 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9322 return FD->getDescribedFunctionTemplate();
9323 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9324 return RD->getDescribedClassTemplate();
9325
9326 llvm_unreachable("Unsupported: Getting the described template declaration"
9327 " for bad deduction diagnosis");
9328}
9329
9330/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009331static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9332 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009333 unsigned NumArgs,
9334 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009335 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009336 NamedDecl *ParamD;
9337 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9338 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9339 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009340 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009341 case Sema::TDK_Success:
9342 llvm_unreachable("TDK_success while diagnosing bad deduction");
9343
9344 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009345 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009346 S.Diag(Templated->getLocation(),
9347 diag::note_ovl_candidate_incomplete_deduction)
9348 << ParamD->getDeclName();
9349 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009350 return;
9351 }
9352
John McCall42d7d192010-08-05 09:05:08 +00009353 case Sema::TDK_Underqualified: {
9354 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9355 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9356
Larisse Voufo98b20f12013-07-19 23:00:19 +00009357 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009358
9359 // Param will have been canonicalized, but it should just be a
9360 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009361 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009362 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009363 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009364 assert(S.Context.hasSameType(Param, NonCanonParam));
9365
9366 // Arg has also been canonicalized, but there's nothing we can do
9367 // about that. It also doesn't matter as much, because it won't
9368 // have any template parameters in it (because deduction isn't
9369 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009370 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009371
Larisse Voufo98b20f12013-07-19 23:00:19 +00009372 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9373 << ParamD->getDeclName() << Arg << NonCanonParam;
9374 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009375 return;
9376 }
9377
9378 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009379 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009380 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009381 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009382 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009383 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009384 which = 1;
9385 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009386 which = 2;
9387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009388
Larisse Voufo98b20f12013-07-19 23:00:19 +00009389 S.Diag(Templated->getLocation(),
9390 diag::note_ovl_candidate_inconsistent_deduction)
9391 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9392 << *DeductionFailure.getSecondArg();
9393 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009394 return;
9395 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009396
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009397 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009398 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009399 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009400 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009401 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009402 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009403 else {
9404 int index = 0;
9405 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9406 index = TTP->getIndex();
9407 else if (NonTypeTemplateParmDecl *NTTP
9408 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9409 index = NTTP->getIndex();
9410 else
9411 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009412 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009413 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009414 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009415 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009416 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009417 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418
Douglas Gregor02eb4832010-05-08 18:13:28 +00009419 case Sema::TDK_TooManyArguments:
9420 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009421 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009422 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009423
9424 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009425 S.Diag(Templated->getLocation(),
9426 diag::note_ovl_candidate_instantiation_depth);
9427 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009428 return;
9429
9430 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009431 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009432 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009433 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009434 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009435 TemplateArgString = " ";
9436 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009437 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009438 }
9439
Richard Smith6f8d2c62012-05-09 05:17:00 +00009440 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009441 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009442 if (PDiag && PDiag->second.getDiagID() ==
9443 diag::err_typename_nested_not_found_enable_if) {
9444 // FIXME: Use the source range of the condition, and the fully-qualified
9445 // name of the enable_if template. These are both present in PDiag.
9446 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9447 << "'enable_if'" << TemplateArgString;
9448 return;
9449 }
9450
Richard Smith9ca64612012-05-07 09:03:25 +00009451 // Format the SFINAE diagnostic into the argument string.
9452 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9453 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009454 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009455 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009456 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009457 SFINAEArgString = ": ";
9458 R = SourceRange(PDiag->first, PDiag->first);
9459 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9460 }
9461
Larisse Voufo98b20f12013-07-19 23:00:19 +00009462 S.Diag(Templated->getLocation(),
9463 diag::note_ovl_candidate_substitution_failure)
9464 << TemplateArgString << SFINAEArgString << R;
9465 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009466 return;
9467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009468
Richard Smith8c6eeb92013-01-31 04:03:12 +00009469 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009470 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9471 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009472 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009473 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009474 return;
9475 }
9476
Richard Smith9b534542015-12-31 02:02:54 +00009477 case Sema::TDK_DeducedMismatch: {
9478 // Format the template argument list into the argument string.
9479 SmallString<128> TemplateArgString;
9480 if (TemplateArgumentList *Args =
9481 DeductionFailure.getTemplateArgumentList()) {
9482 TemplateArgString = " ";
9483 TemplateArgString += S.getTemplateArgumentBindingsText(
9484 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9485 }
9486
9487 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9488 << (*DeductionFailure.getCallArgIndex() + 1)
9489 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9490 << TemplateArgString;
9491 break;
9492 }
9493
Richard Trieue3732352013-04-08 21:11:40 +00009494 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009495 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009496 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9497 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009498 if (FirstTA.getKind() == TemplateArgument::Template &&
9499 SecondTA.getKind() == TemplateArgument::Template) {
9500 TemplateName FirstTN = FirstTA.getAsTemplate();
9501 TemplateName SecondTN = SecondTA.getAsTemplate();
9502 if (FirstTN.getKind() == TemplateName::Template &&
9503 SecondTN.getKind() == TemplateName::Template) {
9504 if (FirstTN.getAsTemplateDecl()->getName() ==
9505 SecondTN.getAsTemplateDecl()->getName()) {
9506 // FIXME: This fixes a bad diagnostic where both templates are named
9507 // the same. This particular case is a bit difficult since:
9508 // 1) It is passed as a string to the diagnostic printer.
9509 // 2) The diagnostic printer only attempts to find a better
9510 // name for types, not decls.
9511 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009512 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009513 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9514 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9515 return;
9516 }
9517 }
9518 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009519
9520 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9521 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9522 return;
9523
Faisal Vali2b391ab2013-09-26 19:54:12 +00009524 // FIXME: For generic lambda parameters, check if the function is a lambda
9525 // call operator, and if so, emit a prettier and more informative
9526 // diagnostic that mentions 'auto' and lambda in addition to
9527 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009528 S.Diag(Templated->getLocation(),
9529 diag::note_ovl_candidate_non_deduced_mismatch)
9530 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009531 return;
Richard Trieue3732352013-04-08 21:11:40 +00009532 }
John McCall8b9ed552010-02-01 18:53:26 +00009533 // TODO: diagnose these individually, then kill off
9534 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009535 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009536 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9537 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009538 return;
9539 }
9540}
9541
Larisse Voufo98b20f12013-07-19 23:00:19 +00009542/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009543static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009544 unsigned NumArgs,
9545 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009546 unsigned TDK = Cand->DeductionFailure.Result;
9547 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9548 if (CheckArityMismatch(S, Cand, NumArgs))
9549 return;
9550 }
9551 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009552 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009553}
9554
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009555/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009556static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009557 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9558 FunctionDecl *Callee = Cand->Function;
9559
9560 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9561 CalleeTarget = S.IdentifyCUDATarget(Callee);
9562
9563 std::string FnDesc;
9564 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9565
9566 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009567 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9568
9569 // This could be an implicit constructor for which we could not infer the
9570 // target due to a collsion. Diagnose that case.
9571 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9572 if (Meth != nullptr && Meth->isImplicit()) {
9573 CXXRecordDecl *ParentClass = Meth->getParent();
9574 Sema::CXXSpecialMember CSM;
9575
9576 switch (FnKind) {
9577 default:
9578 return;
9579 case oc_implicit_default_constructor:
9580 CSM = Sema::CXXDefaultConstructor;
9581 break;
9582 case oc_implicit_copy_constructor:
9583 CSM = Sema::CXXCopyConstructor;
9584 break;
9585 case oc_implicit_move_constructor:
9586 CSM = Sema::CXXMoveConstructor;
9587 break;
9588 case oc_implicit_copy_assignment:
9589 CSM = Sema::CXXCopyAssignment;
9590 break;
9591 case oc_implicit_move_assignment:
9592 CSM = Sema::CXXMoveAssignment;
9593 break;
9594 };
9595
9596 bool ConstRHS = false;
9597 if (Meth->getNumParams()) {
9598 if (const ReferenceType *RT =
9599 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9600 ConstRHS = RT->getPointeeType().isConstQualified();
9601 }
9602 }
9603
9604 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9605 /* ConstRHS */ ConstRHS,
9606 /* Diagnose */ true);
9607 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009608}
9609
Richard Smith17c00b42014-11-12 01:24:00 +00009610static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009611 FunctionDecl *Callee = Cand->Function;
9612 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9613
9614 S.Diag(Callee->getLocation(),
9615 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9616 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9617}
9618
John McCall8b9ed552010-02-01 18:53:26 +00009619/// Generates a 'note' diagnostic for an overload candidate. We've
9620/// already generated a primary error at the call site.
9621///
9622/// It really does need to be a single diagnostic with its caret
9623/// pointed at the candidate declaration. Yes, this creates some
9624/// major challenges of technical writing. Yes, this makes pointing
9625/// out problems with specific arguments quite awkward. It's still
9626/// better than generating twenty screens of text for every failed
9627/// overload.
9628///
9629/// It would be great to be able to express per-candidate problems
9630/// more richly for those diagnostic clients that cared, but we'd
9631/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009632static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009633 unsigned NumArgs,
9634 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009635 FunctionDecl *Fn = Cand->Function;
9636
John McCall12f97bc2010-01-08 04:41:39 +00009637 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009638 if (Cand->Viable && (Fn->isDeleted() ||
9639 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009640 std::string FnDesc;
9641 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009642
9643 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009644 << FnKind << FnDesc
9645 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009646 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009647 return;
John McCall12f97bc2010-01-08 04:41:39 +00009648 }
9649
John McCalle1ac8d12010-01-13 00:25:19 +00009650 // We don't really have anything else to say about viable candidates.
9651 if (Cand->Viable) {
9652 S.NoteOverloadCandidate(Fn);
9653 return;
9654 }
John McCall0d1da222010-01-12 00:44:57 +00009655
John McCall6a61b522010-01-13 09:16:55 +00009656 switch (Cand->FailureKind) {
9657 case ovl_fail_too_many_arguments:
9658 case ovl_fail_too_few_arguments:
9659 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009660
John McCall6a61b522010-01-13 09:16:55 +00009661 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009662 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009663
John McCall578a1f82014-12-14 01:46:53 +00009664 case ovl_fail_illegal_constructor: {
9665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9666 << (Fn->getPrimaryTemplate() ? 1 : 0);
9667 MaybeEmitInheritedConstructorNote(S, Fn);
9668 return;
9669 }
9670
John McCallfe796dd2010-01-23 05:17:32 +00009671 case ovl_fail_trivial_conversion:
9672 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009673 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009674 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009675
John McCall65eb8792010-02-25 01:37:24 +00009676 case ovl_fail_bad_conversion: {
9677 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009678 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009679 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009680 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009681
John McCall6a61b522010-01-13 09:16:55 +00009682 // FIXME: this currently happens when we're called from SemaInit
9683 // when user-conversion overload fails. Figure out how to handle
9684 // those conditions and diagnose them well.
9685 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009686 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009687
9688 case ovl_fail_bad_target:
9689 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009690
9691 case ovl_fail_enable_if:
9692 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009693
9694 case ovl_fail_addr_not_available: {
9695 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9696 (void)Available;
9697 assert(!Available);
9698 break;
9699 }
John McCall65eb8792010-02-25 01:37:24 +00009700 }
John McCalld3224162010-01-08 00:58:21 +00009701}
9702
Richard Smith17c00b42014-11-12 01:24:00 +00009703static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009704 // Desugar the type of the surrogate down to a function type,
9705 // retaining as many typedefs as possible while still showing
9706 // the function type (and, therefore, its parameter types).
9707 QualType FnType = Cand->Surrogate->getConversionType();
9708 bool isLValueReference = false;
9709 bool isRValueReference = false;
9710 bool isPointer = false;
9711 if (const LValueReferenceType *FnTypeRef =
9712 FnType->getAs<LValueReferenceType>()) {
9713 FnType = FnTypeRef->getPointeeType();
9714 isLValueReference = true;
9715 } else if (const RValueReferenceType *FnTypeRef =
9716 FnType->getAs<RValueReferenceType>()) {
9717 FnType = FnTypeRef->getPointeeType();
9718 isRValueReference = true;
9719 }
9720 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9721 FnType = FnTypePtr->getPointeeType();
9722 isPointer = true;
9723 }
9724 // Desugar down to a function type.
9725 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9726 // Reconstruct the pointer/reference as appropriate.
9727 if (isPointer) FnType = S.Context.getPointerType(FnType);
9728 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9729 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9730
9731 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9732 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009733 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009734}
9735
Richard Smith17c00b42014-11-12 01:24:00 +00009736static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9737 SourceLocation OpLoc,
9738 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009739 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009740 std::string TypeStr("operator");
9741 TypeStr += Opc;
9742 TypeStr += "(";
9743 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009744 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009745 TypeStr += ")";
9746 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9747 } else {
9748 TypeStr += ", ";
9749 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9750 TypeStr += ")";
9751 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9752 }
9753}
9754
Richard Smith17c00b42014-11-12 01:24:00 +00009755static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9756 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009757 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009758 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9759 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009760 if (ICS.isBad()) break; // all meaningless after first invalid
9761 if (!ICS.isAmbiguous()) continue;
9762
John McCall5c32be02010-08-24 20:38:10 +00009763 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009764 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009765 }
9766}
9767
Larisse Voufo98b20f12013-07-19 23:00:19 +00009768static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009769 if (Cand->Function)
9770 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009771 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009772 return Cand->Surrogate->getLocation();
9773 return SourceLocation();
9774}
9775
Larisse Voufo98b20f12013-07-19 23:00:19 +00009776static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009777 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009778 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009779 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009780
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009781 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009782 case Sema::TDK_Incomplete:
9783 return 1;
9784
9785 case Sema::TDK_Underqualified:
9786 case Sema::TDK_Inconsistent:
9787 return 2;
9788
9789 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009790 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009791 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009792 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009793 return 3;
9794
9795 case Sema::TDK_InstantiationDepth:
9796 case Sema::TDK_FailedOverloadResolution:
9797 return 4;
9798
9799 case Sema::TDK_InvalidExplicitArguments:
9800 return 5;
9801
9802 case Sema::TDK_TooManyArguments:
9803 case Sema::TDK_TooFewArguments:
9804 return 6;
9805 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009806 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009807}
9808
Richard Smith17c00b42014-11-12 01:24:00 +00009809namespace {
John McCallad2587a2010-01-12 00:48:53 +00009810struct CompareOverloadCandidatesForDisplay {
9811 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009812 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009813 size_t NumArgs;
9814
Richard Smith0f59cb32015-12-18 21:45:41 +00009815 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009816 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009817
9818 bool operator()(const OverloadCandidate *L,
9819 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009820 // Fast-path this check.
9821 if (L == R) return false;
9822
John McCall12f97bc2010-01-08 04:41:39 +00009823 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009824 if (L->Viable) {
9825 if (!R->Viable) return true;
9826
9827 // TODO: introduce a tri-valued comparison for overload
9828 // candidates. Would be more worthwhile if we had a sort
9829 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009830 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9831 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009832 } else if (R->Viable)
9833 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009834
John McCall3712d9e2010-01-15 23:32:50 +00009835 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009836
John McCall3712d9e2010-01-15 23:32:50 +00009837 // Criteria by which we can sort non-viable candidates:
9838 if (!L->Viable) {
9839 // 1. Arity mismatches come after other candidates.
9840 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009841 L->FailureKind == ovl_fail_too_few_arguments) {
9842 if (R->FailureKind == ovl_fail_too_many_arguments ||
9843 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009844 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9845 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9846 if (LDist == RDist) {
9847 if (L->FailureKind == R->FailureKind)
9848 // Sort non-surrogates before surrogates.
9849 return !L->IsSurrogate && R->IsSurrogate;
9850 // Sort candidates requiring fewer parameters than there were
9851 // arguments given after candidates requiring more parameters
9852 // than there were arguments given.
9853 return L->FailureKind == ovl_fail_too_many_arguments;
9854 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009855 return LDist < RDist;
9856 }
John McCall3712d9e2010-01-15 23:32:50 +00009857 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009858 }
John McCall3712d9e2010-01-15 23:32:50 +00009859 if (R->FailureKind == ovl_fail_too_many_arguments ||
9860 R->FailureKind == ovl_fail_too_few_arguments)
9861 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009862
John McCallfe796dd2010-01-23 05:17:32 +00009863 // 2. Bad conversions come first and are ordered by the number
9864 // of bad conversions and quality of good conversions.
9865 if (L->FailureKind == ovl_fail_bad_conversion) {
9866 if (R->FailureKind != ovl_fail_bad_conversion)
9867 return true;
9868
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009869 // The conversion that can be fixed with a smaller number of changes,
9870 // comes first.
9871 unsigned numLFixes = L->Fix.NumConversionsFixed;
9872 unsigned numRFixes = R->Fix.NumConversionsFixed;
9873 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9874 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009875 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009876 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009877 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009878
John McCallfe796dd2010-01-23 05:17:32 +00009879 // If there's any ordering between the defined conversions...
9880 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009881 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009882
9883 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009884 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009885 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009886 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009887 L->Conversions[I],
9888 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009889 case ImplicitConversionSequence::Better:
9890 leftBetter++;
9891 break;
9892
9893 case ImplicitConversionSequence::Worse:
9894 leftBetter--;
9895 break;
9896
9897 case ImplicitConversionSequence::Indistinguishable:
9898 break;
9899 }
9900 }
9901 if (leftBetter > 0) return true;
9902 if (leftBetter < 0) return false;
9903
9904 } else if (R->FailureKind == ovl_fail_bad_conversion)
9905 return false;
9906
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009907 if (L->FailureKind == ovl_fail_bad_deduction) {
9908 if (R->FailureKind != ovl_fail_bad_deduction)
9909 return true;
9910
9911 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9912 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009913 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009914 } else if (R->FailureKind == ovl_fail_bad_deduction)
9915 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009916
John McCall3712d9e2010-01-15 23:32:50 +00009917 // TODO: others?
9918 }
9919
9920 // Sort everything else by location.
9921 SourceLocation LLoc = GetLocationForCandidate(L);
9922 SourceLocation RLoc = GetLocationForCandidate(R);
9923
9924 // Put candidates without locations (e.g. builtins) at the end.
9925 if (LLoc.isInvalid()) return false;
9926 if (RLoc.isInvalid()) return true;
9927
9928 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009929 }
9930};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009931}
John McCall12f97bc2010-01-08 04:41:39 +00009932
John McCallfe796dd2010-01-23 05:17:32 +00009933/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009934/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009935static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9936 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009937 assert(!Cand->Viable);
9938
9939 // Don't do anything on failures other than bad conversion.
9940 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9941
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009942 // We only want the FixIts if all the arguments can be corrected.
9943 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009944 // Use a implicit copy initialization to check conversion fixes.
9945 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009946
John McCallfe796dd2010-01-23 05:17:32 +00009947 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009948 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009949 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009950 while (true) {
9951 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9952 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009953 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009954 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009955 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009956 }
John McCallfe796dd2010-01-23 05:17:32 +00009957 }
9958
9959 if (ConvIdx == ConvCount)
9960 return;
9961
John McCall65eb8792010-02-25 01:37:24 +00009962 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9963 "remaining conversion is initialized?");
9964
Douglas Gregoradc7a702010-04-16 17:45:54 +00009965 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009966 // operation somehow.
9967 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009968
9969 const FunctionProtoType* Proto;
9970 unsigned ArgIdx = ConvIdx;
9971
9972 if (Cand->IsSurrogate) {
9973 QualType ConvType
9974 = Cand->Surrogate->getConversionType().getNonReferenceType();
9975 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9976 ConvType = ConvPtrType->getPointeeType();
9977 Proto = ConvType->getAs<FunctionProtoType>();
9978 ArgIdx--;
9979 } else if (Cand->Function) {
9980 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9981 if (isa<CXXMethodDecl>(Cand->Function) &&
9982 !isa<CXXConstructorDecl>(Cand->Function))
9983 ArgIdx--;
9984 } else {
9985 // Builtin binary operator with a bad first conversion.
9986 assert(ConvCount <= 3);
9987 for (; ConvIdx != ConvCount; ++ConvIdx)
9988 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009989 = TryCopyInitialization(S, Args[ConvIdx],
9990 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009991 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009992 /*InOverloadResolution*/ true,
9993 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009994 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009995 return;
9996 }
9997
9998 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009999 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010000 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010001 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010002 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10003 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10004 /*InOverloadResolution=*/true,
10005 /*AllowObjCWritebackConversion=*/
10006 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010007 // Store the FixIt in the candidate if it exists.
10008 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010009 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010010 }
John McCallfe796dd2010-01-23 05:17:32 +000010011 else
10012 Cand->Conversions[ConvIdx].setEllipsis();
10013 }
10014}
10015
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010016/// PrintOverloadCandidates - When overload resolution fails, prints
10017/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010018/// set.
John McCall5c32be02010-08-24 20:38:10 +000010019void OverloadCandidateSet::NoteCandidates(Sema &S,
10020 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010021 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010022 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010023 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010024 // Sort the candidates by viability and position. Sorting directly would
10025 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010026 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010027 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10028 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010029 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010030 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010031 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010032 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010033 if (Cand->Function || Cand->IsSurrogate)
10034 Cands.push_back(Cand);
10035 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10036 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010037 }
10038 }
10039
John McCallad2587a2010-01-12 00:48:53 +000010040 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010041 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010042
John McCall0d1da222010-01-12 00:44:57 +000010043 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010044
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010045 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010046 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010047 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010048 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10049 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010050
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010051 // Set an arbitrary limit on the number of candidate functions we'll spam
10052 // the user with. FIXME: This limit should depend on details of the
10053 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010054 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010055 break;
10056 }
10057 ++CandsShown;
10058
John McCalld3224162010-01-08 00:58:21 +000010059 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010060 NoteFunctionCandidate(S, Cand, Args.size(),
10061 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010062 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010063 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010064 else {
10065 assert(Cand->Viable &&
10066 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010067 // Generally we only see ambiguities including viable builtin
10068 // operators if overload resolution got screwed up by an
10069 // ambiguous user-defined conversion.
10070 //
10071 // FIXME: It's quite possible for different conversions to see
10072 // different ambiguities, though.
10073 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010074 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010075 ReportedAmbiguousConversions = true;
10076 }
John McCalld3224162010-01-08 00:58:21 +000010077
John McCall0d1da222010-01-12 00:44:57 +000010078 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010079 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010080 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010081 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010082
10083 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010084 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010085}
10086
Larisse Voufo98b20f12013-07-19 23:00:19 +000010087static SourceLocation
10088GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10089 return Cand->Specialization ? Cand->Specialization->getLocation()
10090 : SourceLocation();
10091}
10092
Richard Smith17c00b42014-11-12 01:24:00 +000010093namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010094struct CompareTemplateSpecCandidatesForDisplay {
10095 Sema &S;
10096 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10097
10098 bool operator()(const TemplateSpecCandidate *L,
10099 const TemplateSpecCandidate *R) {
10100 // Fast-path this check.
10101 if (L == R)
10102 return false;
10103
10104 // Assuming that both candidates are not matches...
10105
10106 // Sort by the ranking of deduction failures.
10107 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10108 return RankDeductionFailure(L->DeductionFailure) <
10109 RankDeductionFailure(R->DeductionFailure);
10110
10111 // Sort everything else by location.
10112 SourceLocation LLoc = GetLocationForCandidate(L);
10113 SourceLocation RLoc = GetLocationForCandidate(R);
10114
10115 // Put candidates without locations (e.g. builtins) at the end.
10116 if (LLoc.isInvalid())
10117 return false;
10118 if (RLoc.isInvalid())
10119 return true;
10120
10121 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10122 }
10123};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010124}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010125
10126/// Diagnose a template argument deduction failure.
10127/// We are treating these failures as overload failures due to bad
10128/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010129void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10130 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010131 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010132 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010133}
10134
10135void TemplateSpecCandidateSet::destroyCandidates() {
10136 for (iterator i = begin(), e = end(); i != e; ++i) {
10137 i->DeductionFailure.Destroy();
10138 }
10139}
10140
10141void TemplateSpecCandidateSet::clear() {
10142 destroyCandidates();
10143 Candidates.clear();
10144}
10145
10146/// NoteCandidates - When no template specialization match is found, prints
10147/// diagnostic messages containing the non-matching specializations that form
10148/// the candidate set.
10149/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10150/// OCD == OCD_AllCandidates and Cand->Viable == false.
10151void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10152 // Sort the candidates by position (assuming no candidate is a match).
10153 // Sorting directly would be prohibitive, so we make a set of pointers
10154 // and sort those.
10155 SmallVector<TemplateSpecCandidate *, 32> Cands;
10156 Cands.reserve(size());
10157 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10158 if (Cand->Specialization)
10159 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010160 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010161 // in general, want to list every possible builtin candidate.
10162 }
10163
10164 std::sort(Cands.begin(), Cands.end(),
10165 CompareTemplateSpecCandidatesForDisplay(S));
10166
10167 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10168 // for generalization purposes (?).
10169 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10170
10171 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10172 unsigned CandsShown = 0;
10173 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10174 TemplateSpecCandidate *Cand = *I;
10175
10176 // Set an arbitrary limit on the number of candidates we'll spam
10177 // the user with. FIXME: This limit should depend on details of the
10178 // candidate list.
10179 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10180 break;
10181 ++CandsShown;
10182
10183 assert(Cand->Specialization &&
10184 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010185 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010186 }
10187
10188 if (I != E)
10189 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10190}
10191
Douglas Gregorb491ed32011-02-19 21:32:49 +000010192// [PossiblyAFunctionType] --> [Return]
10193// NonFunctionType --> NonFunctionType
10194// R (A) --> R(A)
10195// R (*)(A) --> R (A)
10196// R (&)(A) --> R (A)
10197// R (S::*)(A) --> R (A)
10198QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10199 QualType Ret = PossiblyAFunctionType;
10200 if (const PointerType *ToTypePtr =
10201 PossiblyAFunctionType->getAs<PointerType>())
10202 Ret = ToTypePtr->getPointeeType();
10203 else if (const ReferenceType *ToTypeRef =
10204 PossiblyAFunctionType->getAs<ReferenceType>())
10205 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010206 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010207 PossiblyAFunctionType->getAs<MemberPointerType>())
10208 Ret = MemTypePtr->getPointeeType();
10209 Ret =
10210 Context.getCanonicalType(Ret).getUnqualifiedType();
10211 return Ret;
10212}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010213
Richard Smith17c00b42014-11-12 01:24:00 +000010214namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010215// A helper class to help with address of function resolution
10216// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010217class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010218 Sema& S;
10219 Expr* SourceExpr;
10220 const QualType& TargetType;
10221 QualType TargetFunctionType; // Extracted function type from target type
10222
10223 bool Complain;
10224 //DeclAccessPair& ResultFunctionAccessPair;
10225 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010226
Douglas Gregorb491ed32011-02-19 21:32:49 +000010227 bool TargetTypeIsNonStaticMemberFunction;
10228 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010229 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010230 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010231
Douglas Gregorb491ed32011-02-19 21:32:49 +000010232 OverloadExpr::FindResult OvlExprInfo;
10233 OverloadExpr *OvlExpr;
10234 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010235 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010236 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010237
Douglas Gregorb491ed32011-02-19 21:32:49 +000010238public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010239 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10240 const QualType &TargetType, bool Complain)
10241 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10242 Complain(Complain), Context(S.getASTContext()),
10243 TargetTypeIsNonStaticMemberFunction(
10244 !!TargetType->getAs<MemberPointerType>()),
10245 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010246 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010247 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010248 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10249 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010250 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010251 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010252
David Majnemera4f7c7a2013-08-01 06:13:59 +000010253 if (TargetFunctionType->isFunctionType()) {
10254 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10255 if (!UME->isImplicitAccess() &&
10256 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10257 StaticMemberFunctionFromBoundPointer = true;
10258 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10259 DeclAccessPair dap;
10260 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10261 OvlExpr, false, &dap)) {
10262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10263 if (!Method->isStatic()) {
10264 // If the target type is a non-function type and the function found
10265 // is a non-static member function, pretend as if that was the
10266 // target, it's the only possible type to end up with.
10267 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010268
David Majnemera4f7c7a2013-08-01 06:13:59 +000010269 // And skip adding the function if its not in the proper form.
10270 // We'll diagnose this due to an empty set of functions.
10271 if (!OvlExprInfo.HasFormOfMemberPointer)
10272 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010273 }
10274
David Majnemera4f7c7a2013-08-01 06:13:59 +000010275 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010276 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010277 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010278 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010279
10280 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010281 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010282
Douglas Gregorb491ed32011-02-19 21:32:49 +000010283 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10284 // C++ [over.over]p4:
10285 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010286 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010287 if (FoundNonTemplateFunction)
10288 EliminateAllTemplateMatches();
10289 else
10290 EliminateAllExceptMostSpecializedTemplate();
10291 }
10292 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010293
10294 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10295 Matches.size() > 1)
10296 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010297 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010298
10299 bool hasComplained() const { return HasComplained; }
10300
Douglas Gregorb491ed32011-02-19 21:32:49 +000010301private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010302 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10303 QualType Discard;
10304 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10305 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010306 }
10307
George Burgess IV6da4c202016-03-23 02:33:58 +000010308 /// \return true if A is considered a better overload candidate for the
10309 /// desired type than B.
10310 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10311 // If A doesn't have exactly the correct type, we don't want to classify it
10312 // as "better" than anything else. This way, the user is required to
10313 // disambiguate for us if there are multiple candidates and no exact match.
10314 return candidateHasExactlyCorrectType(A) &&
10315 (!candidateHasExactlyCorrectType(B) ||
10316 hasBetterEnableIfAttrs(S, A, B));
10317 }
10318
10319 /// \return true if we were able to eliminate all but one overload candidate,
10320 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010321 bool eliminiateSuboptimalOverloadCandidates() {
10322 // Same algorithm as overload resolution -- one pass to pick the "best",
10323 // another pass to be sure that nothing is better than the best.
10324 auto Best = Matches.begin();
10325 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10326 if (isBetterCandidate(I->second, Best->second))
10327 Best = I;
10328
10329 const FunctionDecl *BestFn = Best->second;
10330 auto IsBestOrInferiorToBest = [this, BestFn](
10331 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10332 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10333 };
10334
10335 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10336 // option, so we can potentially give the user a better error
10337 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10338 return false;
10339 Matches[0] = *Best;
10340 Matches.resize(1);
10341 return true;
10342 }
10343
Douglas Gregorb491ed32011-02-19 21:32:49 +000010344 bool isTargetTypeAFunction() const {
10345 return TargetFunctionType->isFunctionType();
10346 }
10347
10348 // [ToType] [Return]
10349
10350 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10351 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10352 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10353 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10354 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10355 }
10356
10357 // return true if any matching specializations were found
10358 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10359 const DeclAccessPair& CurAccessFunPair) {
10360 if (CXXMethodDecl *Method
10361 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10362 // Skip non-static function templates when converting to pointer, and
10363 // static when converting to member pointer.
10364 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10365 return false;
10366 }
10367 else if (TargetTypeIsNonStaticMemberFunction)
10368 return false;
10369
10370 // C++ [over.over]p2:
10371 // If the name is a function template, template argument deduction is
10372 // done (14.8.2.2), and if the argument deduction succeeds, the
10373 // resulting template argument list is used to generate a single
10374 // function template specialization, which is added to the set of
10375 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010376 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010377 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010378 if (Sema::TemplateDeductionResult Result
10379 = S.DeduceTemplateArguments(FunctionTemplate,
10380 &OvlExplicitTemplateArgs,
10381 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010382 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010383 // Make a note of the failed deduction for diagnostics.
10384 FailedCandidates.addCandidate()
10385 .set(FunctionTemplate->getTemplatedDecl(),
10386 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010387 return false;
10388 }
10389
Douglas Gregor19a41f12013-04-17 08:45:07 +000010390 // Template argument deduction ensures that we have an exact match or
10391 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010392 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010393 assert(S.isSameOrCompatibleFunctionType(
10394 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010395 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010396
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010397 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010398 return false;
10399
Douglas Gregorb491ed32011-02-19 21:32:49 +000010400 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10401 return true;
10402 }
10403
10404 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10405 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010407 // Skip non-static functions when converting to pointer, and static
10408 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010409 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10410 return false;
10411 }
10412 else if (TargetTypeIsNonStaticMemberFunction)
10413 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010414
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010415 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010416 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010417 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010418 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010419 return false;
10420
Richard Smith2a7d4812013-05-04 07:00:32 +000010421 // If any candidate has a placeholder return type, trigger its deduction
10422 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010423 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010424 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010425 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10426 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010427 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010428 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010429
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010430 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010431 return false;
10432
George Burgess IV6da4c202016-03-23 02:33:58 +000010433 // If we're in C, we need to support types that aren't exactly identical.
10434 if (!S.getLangOpts().CPlusPlus ||
10435 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010436 Matches.push_back(std::make_pair(
10437 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010438 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010439 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010440 }
Mike Stump11289f42009-09-09 15:08:12 +000010441 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010442
10443 return false;
10444 }
10445
10446 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10447 bool Ret = false;
10448
10449 // If the overload expression doesn't have the form of a pointer to
10450 // member, don't try to convert it to a pointer-to-member type.
10451 if (IsInvalidFormOfPointerToMemberFunction())
10452 return false;
10453
10454 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10455 E = OvlExpr->decls_end();
10456 I != E; ++I) {
10457 // Look through any using declarations to find the underlying function.
10458 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10459
10460 // C++ [over.over]p3:
10461 // Non-member functions and static member functions match
10462 // targets of type "pointer-to-function" or "reference-to-function."
10463 // Nonstatic member functions match targets of
10464 // type "pointer-to-member-function."
10465 // Note that according to DR 247, the containing class does not matter.
10466 if (FunctionTemplateDecl *FunctionTemplate
10467 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10468 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10469 Ret = true;
10470 }
10471 // If we have explicit template arguments supplied, skip non-templates.
10472 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10473 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10474 Ret = true;
10475 }
10476 assert(Ret || Matches.empty());
10477 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010478 }
10479
Douglas Gregorb491ed32011-02-19 21:32:49 +000010480 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010481 // [...] and any given function template specialization F1 is
10482 // eliminated if the set contains a second function template
10483 // specialization whose function template is more specialized
10484 // than the function template of F1 according to the partial
10485 // ordering rules of 14.5.5.2.
10486
10487 // The algorithm specified above is quadratic. We instead use a
10488 // two-pass algorithm (similar to the one used to identify the
10489 // best viable function in an overload set) that identifies the
10490 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010491
10492 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10493 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10494 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010495
Larisse Voufo98b20f12013-07-19 23:00:19 +000010496 // TODO: It looks like FailedCandidates does not serve much purpose
10497 // here, since the no_viable diagnostic has index 0.
10498 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010499 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010500 SourceExpr->getLocStart(), S.PDiag(),
10501 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10502 .second->getDeclName(),
10503 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10504 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010505
Douglas Gregorb491ed32011-02-19 21:32:49 +000010506 if (Result != MatchesCopy.end()) {
10507 // Make it the first and only element
10508 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10509 Matches[0].second = cast<FunctionDecl>(*Result);
10510 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010511 } else
10512 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010514
Douglas Gregorb491ed32011-02-19 21:32:49 +000010515 void EliminateAllTemplateMatches() {
10516 // [...] any function template specializations in the set are
10517 // eliminated if the set also contains a non-template function, [...]
10518 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010519 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010520 ++I;
10521 else {
10522 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010523 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010524 }
10525 }
10526 }
10527
Artem Belevich94a55e82015-09-22 17:22:59 +000010528 void EliminateSuboptimalCudaMatches() {
10529 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10530 }
10531
Douglas Gregorb491ed32011-02-19 21:32:49 +000010532public:
10533 void ComplainNoMatchesFound() const {
10534 assert(Matches.empty());
10535 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10536 << OvlExpr->getName() << TargetFunctionType
10537 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010538 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010539 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10540 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010541 else {
10542 // We have some deduction failure messages. Use them to diagnose
10543 // the function templates, and diagnose the non-template candidates
10544 // normally.
10545 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10546 IEnd = OvlExpr->decls_end();
10547 I != IEnd; ++I)
10548 if (FunctionDecl *Fun =
10549 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010550 if (!functionHasPassObjectSizeParams(Fun))
10551 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10552 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010553 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10554 }
10555 }
10556
Douglas Gregorb491ed32011-02-19 21:32:49 +000010557 bool IsInvalidFormOfPointerToMemberFunction() const {
10558 return TargetTypeIsNonStaticMemberFunction &&
10559 !OvlExprInfo.HasFormOfMemberPointer;
10560 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010561
Douglas Gregorb491ed32011-02-19 21:32:49 +000010562 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10563 // TODO: Should we condition this on whether any functions might
10564 // have matched, or is it more appropriate to do that in callers?
10565 // TODO: a fixit wouldn't hurt.
10566 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10567 << TargetType << OvlExpr->getSourceRange();
10568 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010569
10570 bool IsStaticMemberFunctionFromBoundPointer() const {
10571 return StaticMemberFunctionFromBoundPointer;
10572 }
10573
10574 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10575 S.Diag(OvlExpr->getLocStart(),
10576 diag::err_invalid_form_pointer_member_function)
10577 << OvlExpr->getSourceRange();
10578 }
10579
Douglas Gregorb491ed32011-02-19 21:32:49 +000010580 void ComplainOfInvalidConversion() const {
10581 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10582 << OvlExpr->getName() << TargetType;
10583 }
10584
10585 void ComplainMultipleMatchesFound() const {
10586 assert(Matches.size() > 1);
10587 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10588 << OvlExpr->getName()
10589 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010590 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10591 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010592 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010593
10594 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10595
Douglas Gregorb491ed32011-02-19 21:32:49 +000010596 int getNumMatches() const { return Matches.size(); }
10597
10598 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010599 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010600 return Matches[0].second;
10601 }
10602
10603 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010604 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010605 return &Matches[0].first;
10606 }
10607};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010608}
Richard Smith17c00b42014-11-12 01:24:00 +000010609
Douglas Gregorb491ed32011-02-19 21:32:49 +000010610/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10611/// an overloaded function (C++ [over.over]), where @p From is an
10612/// expression with overloaded function type and @p ToType is the type
10613/// we're trying to resolve to. For example:
10614///
10615/// @code
10616/// int f(double);
10617/// int f(int);
10618///
10619/// int (*pfd)(double) = f; // selects f(double)
10620/// @endcode
10621///
10622/// This routine returns the resulting FunctionDecl if it could be
10623/// resolved, and NULL otherwise. When @p Complain is true, this
10624/// routine will emit diagnostics if there is an error.
10625FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010626Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10627 QualType TargetType,
10628 bool Complain,
10629 DeclAccessPair &FoundResult,
10630 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010631 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010632
10633 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10634 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010635 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010636 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010637 bool ShouldComplain = Complain && !Resolver.hasComplained();
10638 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010639 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10640 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10641 else
10642 Resolver.ComplainNoMatchesFound();
10643 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010644 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010645 Resolver.ComplainMultipleMatchesFound();
10646 else if (NumMatches == 1) {
10647 Fn = Resolver.getMatchingFunctionDecl();
10648 assert(Fn);
10649 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010650 if (Complain) {
10651 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10652 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10653 else
10654 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10655 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010656 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010657
10658 if (pHadMultipleCandidates)
10659 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010660 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010661}
10662
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010663/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010664/// resolve that function to a single function that can have its address taken.
10665/// This will modify `Pair` iff it returns non-null.
10666///
10667/// This routine can only realistically succeed if all but one candidates in the
10668/// overload set for SrcExpr cannot have their addresses taken.
10669FunctionDecl *
10670Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10671 DeclAccessPair &Pair) {
10672 OverloadExpr::FindResult R = OverloadExpr::find(E);
10673 OverloadExpr *Ovl = R.Expression;
10674 FunctionDecl *Result = nullptr;
10675 DeclAccessPair DAP;
10676 // Don't use the AddressOfResolver because we're specifically looking for
10677 // cases where we have one overload candidate that lacks
10678 // enable_if/pass_object_size/...
10679 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10680 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10681 if (!FD)
10682 return nullptr;
10683
10684 if (!checkAddressOfFunctionIsAvailable(FD))
10685 continue;
10686
10687 // We have more than one result; quit.
10688 if (Result)
10689 return nullptr;
10690 DAP = I.getPair();
10691 Result = FD;
10692 }
10693
10694 if (Result)
10695 Pair = DAP;
10696 return Result;
10697}
10698
10699/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010700/// resolve that overloaded function expression down to a single function.
10701///
10702/// This routine can only resolve template-ids that refer to a single function
10703/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010704/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010705/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010706///
10707/// If no template-ids are found, no diagnostics are emitted and NULL is
10708/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010709FunctionDecl *
10710Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10711 bool Complain,
10712 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010713 // C++ [over.over]p1:
10714 // [...] [Note: any redundant set of parentheses surrounding the
10715 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010716 // C++ [over.over]p1:
10717 // [...] The overloaded function name can be preceded by the &
10718 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010719
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010720 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010721 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010722 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010723
10724 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010725 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010726 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010727
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010728 // Look through all of the overloaded functions, searching for one
10729 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010730 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010731 for (UnresolvedSetIterator I = ovl->decls_begin(),
10732 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010733 // C++0x [temp.arg.explicit]p3:
10734 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010735 // where deduction is not done, if a template argument list is
10736 // specified and it, along with any default template arguments,
10737 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010738 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010739 FunctionTemplateDecl *FunctionTemplate
10740 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010741
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010742 // C++ [over.over]p2:
10743 // If the name is a function template, template argument deduction is
10744 // done (14.8.2.2), and if the argument deduction succeeds, the
10745 // resulting template argument list is used to generate a single
10746 // function template specialization, which is added to the set of
10747 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010748 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010749 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010750 if (TemplateDeductionResult Result
10751 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010752 Specialization, Info,
10753 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010754 // Make a note of the failed deduction for diagnostics.
10755 // TODO: Actually use the failed-deduction info?
10756 FailedCandidates.addCandidate()
10757 .set(FunctionTemplate->getTemplatedDecl(),
10758 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010759 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010760 }
10761
John McCall0009fcc2011-04-26 20:42:42 +000010762 assert(Specialization && "no specialization and no error?");
10763
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010764 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010765 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010766 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010767 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10768 << ovl->getName();
10769 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010770 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010771 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010772 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010773
John McCall0009fcc2011-04-26 20:42:42 +000010774 Matched = Specialization;
10775 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010777
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010778 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010779 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010780 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010781 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010782
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010783 return Matched;
10784}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010785
Douglas Gregor1beec452011-03-12 01:48:56 +000010786
10787
10788
John McCall50a2c2c2011-10-11 23:14:30 +000010789// Resolve and fix an overloaded expression that can be resolved
10790// because it identifies a single function template specialization.
10791//
Douglas Gregor1beec452011-03-12 01:48:56 +000010792// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010793//
10794// Return true if it was logically possible to so resolve the
10795// expression, regardless of whether or not it succeeded. Always
10796// returns true if 'complain' is set.
10797bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10798 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010799 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010800 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010801 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010802 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010803
John McCall50a2c2c2011-10-11 23:14:30 +000010804 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010805
John McCall0009fcc2011-04-26 20:42:42 +000010806 DeclAccessPair found;
10807 ExprResult SingleFunctionExpression;
10808 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10809 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010810 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010811 SrcExpr = ExprError();
10812 return true;
10813 }
John McCall0009fcc2011-04-26 20:42:42 +000010814
10815 // It is only correct to resolve to an instance method if we're
10816 // resolving a form that's permitted to be a pointer to member.
10817 // Otherwise we'll end up making a bound member expression, which
10818 // is illegal in all the contexts we resolve like this.
10819 if (!ovl.HasFormOfMemberPointer &&
10820 isa<CXXMethodDecl>(fn) &&
10821 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010822 if (!complain) return false;
10823
10824 Diag(ovl.Expression->getExprLoc(),
10825 diag::err_bound_member_function)
10826 << 0 << ovl.Expression->getSourceRange();
10827
10828 // TODO: I believe we only end up here if there's a mix of
10829 // static and non-static candidates (otherwise the expression
10830 // would have 'bound member' type, not 'overload' type).
10831 // Ideally we would note which candidate was chosen and why
10832 // the static candidates were rejected.
10833 SrcExpr = ExprError();
10834 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010835 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010836
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010837 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010838 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010839 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010840
10841 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010842 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010843 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010844 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010845 if (SingleFunctionExpression.isInvalid()) {
10846 SrcExpr = ExprError();
10847 return true;
10848 }
10849 }
John McCall0009fcc2011-04-26 20:42:42 +000010850 }
10851
10852 if (!SingleFunctionExpression.isUsable()) {
10853 if (complain) {
10854 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10855 << ovl.Expression->getName()
10856 << DestTypeForComplaining
10857 << OpRangeForComplaining
10858 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010859 NoteAllOverloadCandidates(SrcExpr.get());
10860
10861 SrcExpr = ExprError();
10862 return true;
10863 }
10864
10865 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010866 }
10867
John McCall50a2c2c2011-10-11 23:14:30 +000010868 SrcExpr = SingleFunctionExpression;
10869 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010870}
10871
Douglas Gregorcabea402009-09-22 15:41:20 +000010872/// \brief Add a single candidate to the overload set.
10873static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010874 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010875 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010876 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010877 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010878 bool PartialOverloading,
10879 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010880 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010881 if (isa<UsingShadowDecl>(Callee))
10882 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10883
Douglas Gregorcabea402009-09-22 15:41:20 +000010884 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010885 if (ExplicitTemplateArgs) {
10886 assert(!KnownValid && "Explicit template arguments?");
10887 return;
10888 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010889 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10890 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010891 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010892 return;
John McCalld14a8642009-11-21 08:51:07 +000010893 }
10894
10895 if (FunctionTemplateDecl *FuncTemplate
10896 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010897 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010898 ExplicitTemplateArgs, Args, CandidateSet,
10899 /*SuppressUsedConversions=*/false,
10900 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010901 return;
10902 }
10903
Richard Smith95ce4f62011-06-26 22:19:54 +000010904 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010905}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010906
Douglas Gregorcabea402009-09-22 15:41:20 +000010907/// \brief Add the overload candidates named by callee and/or found by argument
10908/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010909void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010910 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010911 OverloadCandidateSet &CandidateSet,
10912 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010913
10914#ifndef NDEBUG
10915 // Verify that ArgumentDependentLookup is consistent with the rules
10916 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010917 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010918 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10919 // and let Y be the lookup set produced by argument dependent
10920 // lookup (defined as follows). If X contains
10921 //
10922 // -- a declaration of a class member, or
10923 //
10924 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010925 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010926 //
10927 // -- a declaration that is neither a function or a function
10928 // template
10929 //
10930 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010931
John McCall57500772009-12-16 12:17:52 +000010932 if (ULE->requiresADL()) {
10933 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10934 E = ULE->decls_end(); I != E; ++I) {
10935 assert(!(*I)->getDeclContext()->isRecord());
10936 assert(isa<UsingShadowDecl>(*I) ||
10937 !(*I)->getDeclContext()->isFunctionOrMethod());
10938 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010939 }
10940 }
10941#endif
10942
John McCall57500772009-12-16 12:17:52 +000010943 // It would be nice to avoid this copy.
10944 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010945 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010946 if (ULE->hasExplicitTemplateArgs()) {
10947 ULE->copyTemplateArgumentsInto(TABuffer);
10948 ExplicitTemplateArgs = &TABuffer;
10949 }
10950
10951 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10952 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010953 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10954 CandidateSet, PartialOverloading,
10955 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010956
John McCall57500772009-12-16 12:17:52 +000010957 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010958 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010959 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010960 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010961}
John McCalld681c392009-12-16 08:11:27 +000010962
Richard Smith0603bbb2013-06-12 22:56:54 +000010963/// Determine whether a declaration with the specified name could be moved into
10964/// a different namespace.
10965static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10966 switch (Name.getCXXOverloadedOperator()) {
10967 case OO_New: case OO_Array_New:
10968 case OO_Delete: case OO_Array_Delete:
10969 return false;
10970
10971 default:
10972 return true;
10973 }
10974}
10975
Richard Smith998a5912011-06-05 22:42:48 +000010976/// Attempt to recover from an ill-formed use of a non-dependent name in a
10977/// template, where the non-dependent name was declared after the template
10978/// was defined. This is common in code written for a compilers which do not
10979/// correctly implement two-stage name lookup.
10980///
10981/// Returns true if a viable candidate was found and a diagnostic was issued.
10982static bool
10983DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10984 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010985 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010986 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010987 ArrayRef<Expr *> Args,
10988 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010989 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10990 return false;
10991
10992 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010993 if (DC->isTransparentContext())
10994 continue;
10995
Richard Smith998a5912011-06-05 22:42:48 +000010996 SemaRef.LookupQualifiedName(R, DC);
10997
10998 if (!R.empty()) {
10999 R.suppressDiagnostics();
11000
11001 if (isa<CXXRecordDecl>(DC)) {
11002 // Don't diagnose names we find in classes; we get much better
11003 // diagnostics for these from DiagnoseEmptyLookup.
11004 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011005 if (DoDiagnoseEmptyLookup)
11006 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011007 return false;
11008 }
11009
Richard Smith100b24a2014-04-17 01:52:14 +000011010 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011011 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11012 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011013 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011014 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011015
11016 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011017 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011018 // No viable functions. Don't bother the user with notes for functions
11019 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011020 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011021 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011022 }
Richard Smith998a5912011-06-05 22:42:48 +000011023
11024 // Find the namespaces where ADL would have looked, and suggest
11025 // declaring the function there instead.
11026 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11027 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011028 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011029 AssociatedNamespaces,
11030 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011031 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011032 if (canBeDeclaredInNamespace(R.getLookupName())) {
11033 DeclContext *Std = SemaRef.getStdNamespace();
11034 for (Sema::AssociatedNamespaceSet::iterator
11035 it = AssociatedNamespaces.begin(),
11036 end = AssociatedNamespaces.end(); it != end; ++it) {
11037 // Never suggest declaring a function within namespace 'std'.
11038 if (Std && Std->Encloses(*it))
11039 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011040
Richard Smith0603bbb2013-06-12 22:56:54 +000011041 // Never suggest declaring a function within a namespace with a
11042 // reserved name, like __gnu_cxx.
11043 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11044 if (NS &&
11045 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11046 continue;
11047
11048 SuggestedNamespaces.insert(*it);
11049 }
Richard Smith998a5912011-06-05 22:42:48 +000011050 }
11051
11052 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11053 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011054 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011055 SemaRef.Diag(Best->Function->getLocation(),
11056 diag::note_not_found_by_two_phase_lookup)
11057 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011058 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011059 SemaRef.Diag(Best->Function->getLocation(),
11060 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011061 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011062 } else {
11063 // FIXME: It would be useful to list the associated namespaces here,
11064 // but the diagnostics infrastructure doesn't provide a way to produce
11065 // a localized representation of a list of items.
11066 SemaRef.Diag(Best->Function->getLocation(),
11067 diag::note_not_found_by_two_phase_lookup)
11068 << R.getLookupName() << 2;
11069 }
11070
11071 // Try to recover by calling this function.
11072 return true;
11073 }
11074
11075 R.clear();
11076 }
11077
11078 return false;
11079}
11080
11081/// Attempt to recover from ill-formed use of a non-dependent operator in a
11082/// template, where the non-dependent operator was declared after the template
11083/// was defined.
11084///
11085/// Returns true if a viable candidate was found and a diagnostic was issued.
11086static bool
11087DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11088 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011089 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011090 DeclarationName OpName =
11091 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11092 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11093 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011094 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011095 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011096}
11097
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011098namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011099class BuildRecoveryCallExprRAII {
11100 Sema &SemaRef;
11101public:
11102 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11103 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11104 SemaRef.IsBuildingRecoveryCallExpr = true;
11105 }
11106
11107 ~BuildRecoveryCallExprRAII() {
11108 SemaRef.IsBuildingRecoveryCallExpr = false;
11109 }
11110};
11111
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011112}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011113
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011114static std::unique_ptr<CorrectionCandidateCallback>
11115MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11116 bool HasTemplateArgs, bool AllowTypoCorrection) {
11117 if (!AllowTypoCorrection)
11118 return llvm::make_unique<NoTypoCorrectionCCC>();
11119 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11120 HasTemplateArgs, ME);
11121}
11122
John McCalld681c392009-12-16 08:11:27 +000011123/// Attempts to recover from a call where no functions were found.
11124///
11125/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011126static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011127BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011128 UnresolvedLookupExpr *ULE,
11129 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011130 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011131 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011132 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011133 // Do not try to recover if it is already building a recovery call.
11134 // This stops infinite loops for template instantiations like
11135 //
11136 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11137 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11138 //
11139 if (SemaRef.IsBuildingRecoveryCallExpr)
11140 return ExprError();
11141 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011142
11143 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011144 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011145 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011146
John McCall57500772009-12-16 12:17:52 +000011147 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011148 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011149 if (ULE->hasExplicitTemplateArgs()) {
11150 ULE->copyTemplateArgumentsInto(TABuffer);
11151 ExplicitTemplateArgs = &TABuffer;
11152 }
11153
John McCalld681c392009-12-16 08:11:27 +000011154 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11155 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011156 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011157 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011158 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011159 ExplicitTemplateArgs, Args,
11160 &DoDiagnoseEmptyLookup) &&
11161 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11162 S, SS, R,
11163 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11164 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11165 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011166 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011167
John McCall57500772009-12-16 12:17:52 +000011168 assert(!R.empty() && "lookup results empty despite recovery");
11169
11170 // Build an implicit member call if appropriate. Just drop the
11171 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011172 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011173 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011174 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11175 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011176 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011177 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011178 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011179 else
11180 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11181
11182 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011183 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011184
11185 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011186 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011187 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011188 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011189 MultiExprArg(Args.data(), Args.size()),
11190 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011191}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011192
Sam Panzer0f384432012-08-21 00:52:01 +000011193/// \brief Constructs and populates an OverloadedCandidateSet from
11194/// the given function.
11195/// \returns true when an the ExprResult output parameter has been set.
11196bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11197 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011198 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011199 SourceLocation RParenLoc,
11200 OverloadCandidateSet *CandidateSet,
11201 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011202#ifndef NDEBUG
11203 if (ULE->requiresADL()) {
11204 // To do ADL, we must have found an unqualified name.
11205 assert(!ULE->getQualifier() && "qualified name with ADL");
11206
11207 // We don't perform ADL for implicit declarations of builtins.
11208 // Verify that this was correctly set up.
11209 FunctionDecl *F;
11210 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11211 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11212 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011213 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011214
John McCall57500772009-12-16 12:17:52 +000011215 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011216 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011217 }
John McCall57500772009-12-16 12:17:52 +000011218#endif
11219
John McCall4124c492011-10-17 18:40:02 +000011220 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011221 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011222 *Result = ExprError();
11223 return true;
11224 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011225
John McCall57500772009-12-16 12:17:52 +000011226 // Add the functions denoted by the callee to the set of candidate
11227 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011228 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011229
Hans Wennborgb2747382015-06-12 21:23:23 +000011230 if (getLangOpts().MSVCCompat &&
11231 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011232 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11233
11234 OverloadCandidateSet::iterator Best;
11235 if (CandidateSet->empty() ||
11236 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11237 OR_No_Viable_Function) {
11238 // In Microsoft mode, if we are inside a template class member function then
11239 // create a type dependent CallExpr. The goal is to postpone name lookup
11240 // to instantiation time to be able to search into type dependent base
11241 // classes.
11242 CallExpr *CE = new (Context) CallExpr(
11243 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011244 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011245 CE->setValueDependent(true);
11246 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011247 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011248 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011249 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011250 }
John McCalld681c392009-12-16 08:11:27 +000011251
Hans Wennborg64937c62015-06-11 21:21:57 +000011252 if (CandidateSet->empty())
11253 return false;
11254
John McCall4124c492011-10-17 18:40:02 +000011255 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011256 return false;
11257}
John McCall4124c492011-10-17 18:40:02 +000011258
Sam Panzer0f384432012-08-21 00:52:01 +000011259/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11260/// the completed call expression. If overload resolution fails, emits
11261/// diagnostics and returns ExprError()
11262static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11263 UnresolvedLookupExpr *ULE,
11264 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011265 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011266 SourceLocation RParenLoc,
11267 Expr *ExecConfig,
11268 OverloadCandidateSet *CandidateSet,
11269 OverloadCandidateSet::iterator *Best,
11270 OverloadingResult OverloadResult,
11271 bool AllowTypoCorrection) {
11272 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011273 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011274 RParenLoc, /*EmptyLookup=*/true,
11275 AllowTypoCorrection);
11276
11277 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011278 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011279 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011280 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011281 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11282 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011283 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011284 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11285 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011286 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011287
Richard Smith998a5912011-06-05 22:42:48 +000011288 case OR_No_Viable_Function: {
11289 // Try to recover by looking for viable functions which the user might
11290 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011291 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011292 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011293 /*EmptyLookup=*/false,
11294 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011295 if (!Recovery.isInvalid())
11296 return Recovery;
11297
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011298 // If the user passes in a function that we can't take the address of, we
11299 // generally end up emitting really bad error messages. Here, we attempt to
11300 // emit better ones.
11301 for (const Expr *Arg : Args) {
11302 if (!Arg->getType()->isFunctionType())
11303 continue;
11304 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11305 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11306 if (FD &&
11307 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11308 Arg->getExprLoc()))
11309 return ExprError();
11310 }
11311 }
11312
11313 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11314 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011315 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011316 break;
Richard Smith998a5912011-06-05 22:42:48 +000011317 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011318
11319 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011320 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011321 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011322 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011323 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011324
Sam Panzer0f384432012-08-21 00:52:01 +000011325 case OR_Deleted: {
11326 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11327 << (*Best)->Function->isDeleted()
11328 << ULE->getName()
11329 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11330 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011331 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011332
Sam Panzer0f384432012-08-21 00:52:01 +000011333 // We emitted an error for the unvailable/deleted function call but keep
11334 // the call in the AST.
11335 FunctionDecl *FDecl = (*Best)->Function;
11336 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011337 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11338 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011339 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011340 }
11341
Douglas Gregorb412e172010-07-25 18:17:45 +000011342 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011343 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011344}
11345
George Burgess IV7204ed92016-01-07 02:26:57 +000011346static void markUnaddressableCandidatesUnviable(Sema &S,
11347 OverloadCandidateSet &CS) {
11348 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11349 if (I->Viable &&
11350 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11351 I->Viable = false;
11352 I->FailureKind = ovl_fail_addr_not_available;
11353 }
11354 }
11355}
11356
Sam Panzer0f384432012-08-21 00:52:01 +000011357/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11358/// (which eventually refers to the declaration Func) and the call
11359/// arguments Args/NumArgs, attempt to resolve the function call down
11360/// to a specific function. If overload resolution succeeds, returns
11361/// the call expression produced by overload resolution.
11362/// Otherwise, emits diagnostics and returns ExprError.
11363ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11364 UnresolvedLookupExpr *ULE,
11365 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011366 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011367 SourceLocation RParenLoc,
11368 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011369 bool AllowTypoCorrection,
11370 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011371 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11372 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011373 ExprResult result;
11374
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011375 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11376 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011377 return result;
11378
George Burgess IV7204ed92016-01-07 02:26:57 +000011379 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11380 // functions that aren't addressible are considered unviable.
11381 if (CalleesAddressIsTaken)
11382 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11383
Sam Panzer0f384432012-08-21 00:52:01 +000011384 OverloadCandidateSet::iterator Best;
11385 OverloadingResult OverloadResult =
11386 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11387
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011388 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011389 RParenLoc, ExecConfig, &CandidateSet,
11390 &Best, OverloadResult,
11391 AllowTypoCorrection);
11392}
11393
John McCall4c4c1df2010-01-26 03:27:55 +000011394static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011395 return Functions.size() > 1 ||
11396 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11397}
11398
Douglas Gregor084d8552009-03-13 23:49:33 +000011399/// \brief Create a unary operation that may resolve to an overloaded
11400/// operator.
11401///
11402/// \param OpLoc The location of the operator itself (e.g., '*').
11403///
Craig Toppera92ffb02015-12-10 08:51:49 +000011404/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011405///
James Dennett18348b62012-06-22 08:52:37 +000011406/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011407/// considered by overload resolution. The caller needs to build this
11408/// set based on the context using, e.g.,
11409/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11410/// set should not contain any member functions; those will be added
11411/// by CreateOverloadedUnaryOp().
11412///
James Dennett91738ff2012-06-22 10:32:46 +000011413/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011414ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011415Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011416 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011417 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011418 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11419 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11420 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011421 // TODO: provide better source location info.
11422 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011423
John McCall4124c492011-10-17 18:40:02 +000011424 if (checkPlaceholderForOverload(*this, Input))
11425 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011426
Craig Topperc3ec1492014-05-26 06:22:03 +000011427 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011428 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011429
Douglas Gregor084d8552009-03-13 23:49:33 +000011430 // For post-increment and post-decrement, add the implicit '0' as
11431 // the second argument, so that we know this is a post-increment or
11432 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011433 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011434 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011435 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11436 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011437 NumArgs = 2;
11438 }
11439
Richard Smithe54c3072013-05-05 15:51:06 +000011440 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11441
Douglas Gregor084d8552009-03-13 23:49:33 +000011442 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011443 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011444 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11445 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011446
Craig Topperc3ec1492014-05-26 06:22:03 +000011447 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011448 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011449 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011450 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011451 /*ADL*/ true, IsOverloaded(Fns),
11452 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011453 return new (Context)
11454 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11455 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011456 }
11457
11458 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011459 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011460
11461 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011462 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011463
11464 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011465 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011466
John McCall4c4c1df2010-01-26 03:27:55 +000011467 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011468 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011469 /*ExplicitTemplateArgs*/nullptr,
11470 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011471
Douglas Gregor084d8552009-03-13 23:49:33 +000011472 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011473 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011474
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011475 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11476
Douglas Gregor084d8552009-03-13 23:49:33 +000011477 // Perform overload resolution.
11478 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011479 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011480 case OR_Success: {
11481 // We found a built-in operator or an overloaded operator.
11482 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011483
Douglas Gregor084d8552009-03-13 23:49:33 +000011484 if (FnDecl) {
11485 // We matched an overloaded operator. Build a call to that
11486 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011487
Douglas Gregor084d8552009-03-13 23:49:33 +000011488 // Convert the arguments.
11489 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011490 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011491
John Wiegley01296292011-04-08 18:41:53 +000011492 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011493 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011494 Best->FoundDecl, Method);
11495 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011496 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011497 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011498 } else {
11499 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011500 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011501 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011502 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011503 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011504 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011505 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011506 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011507 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011508 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011509 }
11510
Douglas Gregor084d8552009-03-13 23:49:33 +000011511 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011512 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011513 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011514 if (FnExpr.isInvalid())
11515 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011516
Richard Smithc1564702013-11-15 02:58:23 +000011517 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011518 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011519 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11520 ResultTy = ResultTy.getNonLValueExprType(Context);
11521
Eli Friedman030eee42009-11-18 03:58:17 +000011522 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011523 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011524 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011525 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011526
Alp Toker314cc812014-01-25 16:55:45 +000011527 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011528 return ExprError();
11529
John McCallb268a282010-08-23 23:25:46 +000011530 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011531 } else {
11532 // We matched a built-in operator. Convert the arguments, then
11533 // break out so that we will build the appropriate built-in
11534 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011535 ExprResult InputRes =
11536 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11537 Best->Conversions[0], AA_Passing);
11538 if (InputRes.isInvalid())
11539 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011540 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011541 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011542 }
John Wiegley01296292011-04-08 18:41:53 +000011543 }
11544
11545 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011546 // This is an erroneous use of an operator which can be overloaded by
11547 // a non-member function. Check for non-member operators which were
11548 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011549 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011550 // FIXME: Recover by calling the found function.
11551 return ExprError();
11552
John Wiegley01296292011-04-08 18:41:53 +000011553 // No viable function; fall through to handling this as a
11554 // built-in operator, which will produce an error message for us.
11555 break;
11556
11557 case OR_Ambiguous:
11558 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11559 << UnaryOperator::getOpcodeStr(Opc)
11560 << Input->getType()
11561 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011562 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011563 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11564 return ExprError();
11565
11566 case OR_Deleted:
11567 Diag(OpLoc, diag::err_ovl_deleted_oper)
11568 << Best->Function->isDeleted()
11569 << UnaryOperator::getOpcodeStr(Opc)
11570 << getDeletedOrUnavailableSuffix(Best->Function)
11571 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011573 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011574 return ExprError();
11575 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011576
11577 // Either we found no viable overloaded operator or we matched a
11578 // built-in operator. In either case, fall through to trying to
11579 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011580 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011581}
11582
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011583/// \brief Create a binary operation that may resolve to an overloaded
11584/// operator.
11585///
11586/// \param OpLoc The location of the operator itself (e.g., '+').
11587///
Craig Toppera92ffb02015-12-10 08:51:49 +000011588/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011589///
James Dennett18348b62012-06-22 08:52:37 +000011590/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011591/// considered by overload resolution. The caller needs to build this
11592/// set based on the context using, e.g.,
11593/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11594/// set should not contain any member functions; those will be added
11595/// by CreateOverloadedBinOp().
11596///
11597/// \param LHS Left-hand argument.
11598/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011599ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011600Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011601 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011602 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011603 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011604 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011605 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011606
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011607 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11608 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11609
11610 // If either side is type-dependent, create an appropriate dependent
11611 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011612 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011613 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011614 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011615 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011616 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011617 return new (Context) BinaryOperator(
11618 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11619 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011620
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011621 return new (Context) CompoundAssignOperator(
11622 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11623 Context.DependentTy, Context.DependentTy, OpLoc,
11624 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011625 }
John McCall4c4c1df2010-01-26 03:27:55 +000011626
11627 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011628 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011629 // TODO: provide better source location info in DNLoc component.
11630 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011631 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011632 = UnresolvedLookupExpr::Create(Context, NamingClass,
11633 NestedNameSpecifierLoc(), OpNameInfo,
11634 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011635 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011636 return new (Context)
11637 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11638 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011639 }
11640
John McCall4124c492011-10-17 18:40:02 +000011641 // Always do placeholder-like conversions on the RHS.
11642 if (checkPlaceholderForOverload(*this, Args[1]))
11643 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011644
John McCall526ab472011-10-25 17:37:35 +000011645 // Do placeholder-like conversion on the LHS; note that we should
11646 // not get here with a PseudoObject LHS.
11647 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011648 if (checkPlaceholderForOverload(*this, Args[0]))
11649 return ExprError();
11650
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011651 // If this is the assignment operator, we only perform overload resolution
11652 // if the left-hand side is a class or enumeration type. This is actually
11653 // a hack. The standard requires that we do overload resolution between the
11654 // various built-in candidates, but as DR507 points out, this can lead to
11655 // problems. So we do it this way, which pretty much follows what GCC does.
11656 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011657 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011658 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011659
John McCalle26a8722010-12-04 08:14:53 +000011660 // If this is the .* operator, which is not overloadable, just
11661 // create a built-in binary operator.
11662 if (Opc == BO_PtrMemD)
11663 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11664
Douglas Gregor084d8552009-03-13 23:49:33 +000011665 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011666 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011667
11668 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011669 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011670
11671 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011672 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011673
Richard Smith0daabd72014-09-23 20:31:39 +000011674 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11675 // performed for an assignment operator (nor for operator[] nor operator->,
11676 // which don't get here).
11677 if (Opc != BO_Assign)
11678 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11679 /*ExplicitTemplateArgs*/ nullptr,
11680 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011681
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011682 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011683 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011684
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011685 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11686
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011687 // Perform overload resolution.
11688 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011689 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011690 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011691 // We found a built-in operator or an overloaded operator.
11692 FunctionDecl *FnDecl = Best->Function;
11693
11694 if (FnDecl) {
11695 // We matched an overloaded operator. Build a call to that
11696 // operator.
11697
11698 // Convert the arguments.
11699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011700 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011701 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011702
Chandler Carruth8e543b32010-12-12 08:17:55 +000011703 ExprResult Arg1 =
11704 PerformCopyInitialization(
11705 InitializedEntity::InitializeParameter(Context,
11706 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011707 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011708 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011709 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011710
John Wiegley01296292011-04-08 18:41:53 +000011711 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011712 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011713 Best->FoundDecl, Method);
11714 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011715 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011716 Args[0] = Arg0.getAs<Expr>();
11717 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011718 } else {
11719 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011720 ExprResult Arg0 = PerformCopyInitialization(
11721 InitializedEntity::InitializeParameter(Context,
11722 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011723 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011724 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011725 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011726
Chandler Carruth8e543b32010-12-12 08:17:55 +000011727 ExprResult Arg1 =
11728 PerformCopyInitialization(
11729 InitializedEntity::InitializeParameter(Context,
11730 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011731 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011732 if (Arg1.isInvalid())
11733 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011734 Args[0] = LHS = Arg0.getAs<Expr>();
11735 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011736 }
11737
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011738 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011739 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011740 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011741 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011742 if (FnExpr.isInvalid())
11743 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011744
Richard Smithc1564702013-11-15 02:58:23 +000011745 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011746 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011747 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11748 ResultTy = ResultTy.getNonLValueExprType(Context);
11749
John McCallb268a282010-08-23 23:25:46 +000011750 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011751 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011752 Args, ResultTy, VK, OpLoc,
11753 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011754
Alp Toker314cc812014-01-25 16:55:45 +000011755 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011756 FnDecl))
11757 return ExprError();
11758
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011759 ArrayRef<const Expr *> ArgsArray(Args, 2);
11760 // Cut off the implicit 'this'.
11761 if (isa<CXXMethodDecl>(FnDecl))
11762 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011763
11764 // Check for a self move.
11765 if (Op == OO_Equal)
11766 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11767
Douglas Gregorb4866e82015-06-19 18:13:19 +000011768 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011769 TheCall->getSourceRange(), VariadicDoesNotApply);
11770
John McCallb268a282010-08-23 23:25:46 +000011771 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011772 } else {
11773 // We matched a built-in operator. Convert the arguments, then
11774 // break out so that we will build the appropriate built-in
11775 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011776 ExprResult ArgsRes0 =
11777 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11778 Best->Conversions[0], AA_Passing);
11779 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011780 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011781 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011782
John Wiegley01296292011-04-08 18:41:53 +000011783 ExprResult ArgsRes1 =
11784 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11785 Best->Conversions[1], AA_Passing);
11786 if (ArgsRes1.isInvalid())
11787 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011788 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011789 break;
11790 }
11791 }
11792
Douglas Gregor66950a32009-09-30 21:46:01 +000011793 case OR_No_Viable_Function: {
11794 // C++ [over.match.oper]p9:
11795 // If the operator is the operator , [...] and there are no
11796 // viable functions, then the operator is assumed to be the
11797 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011798 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011799 break;
11800
Chandler Carruth8e543b32010-12-12 08:17:55 +000011801 // For class as left operand for assignment or compound assigment
11802 // operator do not fall through to handling in built-in, but report that
11803 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011804 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011805 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011806 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011807 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11808 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011809 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011810 if (Args[0]->getType()->isIncompleteType()) {
11811 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11812 << Args[0]->getType()
11813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11814 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011815 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011816 // This is an erroneous use of an operator which can be overloaded by
11817 // a non-member function. Check for non-member operators which were
11818 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011819 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011820 // FIXME: Recover by calling the found function.
11821 return ExprError();
11822
Douglas Gregor66950a32009-09-30 21:46:01 +000011823 // No viable function; try to create a built-in operation, which will
11824 // produce an error. Then, show the non-viable candidates.
11825 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011827 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011828 "C++ binary operator overloading is missing candidates!");
11829 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011830 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011831 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011832 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011833 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011834
11835 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011836 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011837 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011838 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011839 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011840 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011841 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011842 return ExprError();
11843
11844 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011845 if (isImplicitlyDeleted(Best->Function)) {
11846 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11847 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011848 << Context.getRecordType(Method->getParent())
11849 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011850
Richard Smithde1a4872012-12-28 12:23:24 +000011851 // The user probably meant to call this special member. Just
11852 // explain why it's deleted.
11853 NoteDeletedFunction(Method);
11854 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011855 } else {
11856 Diag(OpLoc, diag::err_ovl_deleted_oper)
11857 << Best->Function->isDeleted()
11858 << BinaryOperator::getOpcodeStr(Opc)
11859 << getDeletedOrUnavailableSuffix(Best->Function)
11860 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11861 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011862 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011863 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011864 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011865 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011866
Douglas Gregor66950a32009-09-30 21:46:01 +000011867 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011868 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011869}
11870
John McCalldadc5752010-08-24 06:29:42 +000011871ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011872Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11873 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011874 Expr *Base, Expr *Idx) {
11875 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011876 DeclarationName OpName =
11877 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11878
11879 // If either side is type-dependent, create an appropriate dependent
11880 // expression.
11881 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11882
Craig Topperc3ec1492014-05-26 06:22:03 +000011883 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011884 // CHECKME: no 'operator' keyword?
11885 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11886 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011887 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011888 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011889 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011890 /*ADL*/ true, /*Overloaded*/ false,
11891 UnresolvedSetIterator(),
11892 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011893 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011895 return new (Context)
11896 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11897 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011898 }
11899
John McCall4124c492011-10-17 18:40:02 +000011900 // Handle placeholders on both operands.
11901 if (checkPlaceholderForOverload(*this, Args[0]))
11902 return ExprError();
11903 if (checkPlaceholderForOverload(*this, Args[1]))
11904 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011905
Sebastian Redladba46e2009-10-29 20:17:01 +000011906 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011907 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011908
11909 // Subscript can only be overloaded as a member function.
11910
11911 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011912 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011913
11914 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011915 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011916
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011917 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11918
Sebastian Redladba46e2009-10-29 20:17:01 +000011919 // Perform overload resolution.
11920 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011921 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011922 case OR_Success: {
11923 // We found a built-in operator or an overloaded operator.
11924 FunctionDecl *FnDecl = Best->Function;
11925
11926 if (FnDecl) {
11927 // We matched an overloaded operator. Build a call to that
11928 // operator.
11929
John McCalla0296f72010-03-19 07:35:19 +000011930 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011931
Sebastian Redladba46e2009-10-29 20:17:01 +000011932 // Convert the arguments.
11933 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011934 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011935 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011936 Best->FoundDecl, Method);
11937 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011938 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011939 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011940
Anders Carlssona68e51e2010-01-29 18:37:50 +000011941 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011942 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011943 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011944 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011945 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011946 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011947 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011948 if (InputInit.isInvalid())
11949 return ExprError();
11950
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011951 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011952
Sebastian Redladba46e2009-10-29 20:17:01 +000011953 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011954 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11955 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011956 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011957 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011958 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011959 OpLocInfo.getLoc(),
11960 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011961 if (FnExpr.isInvalid())
11962 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011963
Richard Smithc1564702013-11-15 02:58:23 +000011964 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011965 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011966 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11967 ResultTy = ResultTy.getNonLValueExprType(Context);
11968
John McCallb268a282010-08-23 23:25:46 +000011969 CXXOperatorCallExpr *TheCall =
11970 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011971 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011972 ResultTy, VK, RLoc,
11973 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011974
Alp Toker314cc812014-01-25 16:55:45 +000011975 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011976 return ExprError();
11977
John McCallb268a282010-08-23 23:25:46 +000011978 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011979 } else {
11980 // We matched a built-in operator. Convert the arguments, then
11981 // break out so that we will build the appropriate built-in
11982 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011983 ExprResult ArgsRes0 =
11984 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11985 Best->Conversions[0], AA_Passing);
11986 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011987 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011988 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011989
11990 ExprResult ArgsRes1 =
11991 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11992 Best->Conversions[1], AA_Passing);
11993 if (ArgsRes1.isInvalid())
11994 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011995 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011996
11997 break;
11998 }
11999 }
12000
12001 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012002 if (CandidateSet.empty())
12003 Diag(LLoc, diag::err_ovl_no_oper)
12004 << Args[0]->getType() << /*subscript*/ 0
12005 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12006 else
12007 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12008 << Args[0]->getType()
12009 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012011 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012012 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012013 }
12014
12015 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012016 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012017 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012018 << Args[0]->getType() << Args[1]->getType()
12019 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012020 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012021 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012022 return ExprError();
12023
12024 case OR_Deleted:
12025 Diag(LLoc, diag::err_ovl_deleted_oper)
12026 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012027 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012028 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012029 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012030 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012031 return ExprError();
12032 }
12033
12034 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012035 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012036}
12037
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012038/// BuildCallToMemberFunction - Build a call to a member
12039/// function. MemExpr is the expression that refers to the member
12040/// function (and includes the object parameter), Args/NumArgs are the
12041/// arguments to the function call (not including the object
12042/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012043/// expression refers to a non-static member function or an overloaded
12044/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012045ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012046Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012047 SourceLocation LParenLoc,
12048 MultiExprArg Args,
12049 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012050 assert(MemExprE->getType() == Context.BoundMemberTy ||
12051 MemExprE->getType() == Context.OverloadTy);
12052
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012053 // Dig out the member expression. This holds both the object
12054 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012055 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012056
John McCall0009fcc2011-04-26 20:42:42 +000012057 // Determine whether this is a call to a pointer-to-member function.
12058 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12059 assert(op->getType() == Context.BoundMemberTy);
12060 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12061
12062 QualType fnType =
12063 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12064
12065 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12066 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012067 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012068
12069 // Check that the object type isn't more qualified than the
12070 // member function we're calling.
12071 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12072
12073 QualType objectType = op->getLHS()->getType();
12074 if (op->getOpcode() == BO_PtrMemI)
12075 objectType = objectType->castAs<PointerType>()->getPointeeType();
12076 Qualifiers objectQuals = objectType.getQualifiers();
12077
12078 Qualifiers difference = objectQuals - funcQuals;
12079 difference.removeObjCGCAttr();
12080 difference.removeAddressSpace();
12081 if (difference) {
12082 std::string qualsString = difference.getAsString();
12083 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12084 << fnType.getUnqualifiedType()
12085 << qualsString
12086 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12087 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012088
John McCall0009fcc2011-04-26 20:42:42 +000012089 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012090 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012091 resultType, valueKind, RParenLoc);
12092
Alp Toker314cc812014-01-25 16:55:45 +000012093 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012094 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012095 return ExprError();
12096
Craig Topperc3ec1492014-05-26 06:22:03 +000012097 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012098 return ExprError();
12099
Richard Trieu9be9c682013-06-22 02:30:38 +000012100 if (CheckOtherCall(call, proto))
12101 return ExprError();
12102
John McCall0009fcc2011-04-26 20:42:42 +000012103 return MaybeBindToTemporary(call);
12104 }
12105
David Majnemerced8bdf2015-02-25 17:36:15 +000012106 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12107 return new (Context)
12108 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12109
John McCall4124c492011-10-17 18:40:02 +000012110 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012111 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012112 return ExprError();
12113
John McCall10eae182009-11-30 22:42:35 +000012114 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012115 CXXMethodDecl *Method = nullptr;
12116 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12117 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012118 if (isa<MemberExpr>(NakedMemExpr)) {
12119 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012120 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012121 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012122 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012123 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012124 } else {
12125 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012126 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012127
John McCall6e9f8f62009-12-03 04:06:58 +000012128 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012129 Expr::Classification ObjectClassification
12130 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12131 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012132
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012133 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012134 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12135 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012136
John McCall2d74de92009-12-01 22:10:20 +000012137 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012138 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012139 if (UnresExpr->hasExplicitTemplateArgs()) {
12140 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12141 TemplateArgs = &TemplateArgsBuffer;
12142 }
12143
John McCall10eae182009-11-30 22:42:35 +000012144 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12145 E = UnresExpr->decls_end(); I != E; ++I) {
12146
John McCall6e9f8f62009-12-03 04:06:58 +000012147 NamedDecl *Func = *I;
12148 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12149 if (isa<UsingShadowDecl>(Func))
12150 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12151
Douglas Gregor02824322011-01-26 19:30:28 +000012152
Francois Pichet64225792011-01-18 05:04:39 +000012153 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012154 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012155 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012156 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012157 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012158 // If explicit template arguments were provided, we can't call a
12159 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012160 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012161 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012162
John McCalla0296f72010-03-19 07:35:19 +000012163 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012164 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012165 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012166 } else {
John McCall10eae182009-11-30 22:42:35 +000012167 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012168 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012169 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012170 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012171 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012172 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012173 }
Mike Stump11289f42009-09-09 15:08:12 +000012174
John McCall10eae182009-11-30 22:42:35 +000012175 DeclarationName DeclName = UnresExpr->getMemberName();
12176
John McCall4124c492011-10-17 18:40:02 +000012177 UnbridgedCasts.restore();
12178
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012179 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012180 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012181 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012182 case OR_Success:
12183 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012184 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012185 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012186 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12187 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012188 // If FoundDecl is different from Method (such as if one is a template
12189 // and the other a specialization), make sure DiagnoseUseOfDecl is
12190 // called on both.
12191 // FIXME: This would be more comprehensively addressed by modifying
12192 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12193 // being used.
12194 if (Method != FoundDecl.getDecl() &&
12195 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12196 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012197 break;
12198
12199 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012200 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012201 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012202 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012204 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012205 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012206
12207 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012208 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012209 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012210 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012211 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012212 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012213
12214 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012215 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012216 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012217 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012218 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012219 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012220 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012221 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012222 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012223 }
12224
John McCall16df1e52010-03-30 21:47:33 +000012225 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012226
John McCall2d74de92009-12-01 22:10:20 +000012227 // If overload resolution picked a static member, build a
12228 // non-member call based on that function.
12229 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012230 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12231 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012232 }
12233
John McCall10eae182009-11-30 22:42:35 +000012234 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012235 }
12236
Alp Toker314cc812014-01-25 16:55:45 +000012237 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012238 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12239 ResultType = ResultType.getNonLValueExprType(Context);
12240
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012241 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012242 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012243 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012244 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012245
Eli Bendersky291a57e2014-09-25 23:59:08 +000012246 // (CUDA B.1): Check for invalid calls between targets.
12247 if (getLangOpts().CUDA) {
12248 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12249 if (CheckCUDATarget(Caller, Method)) {
12250 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12251 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12252 << IdentifyCUDATarget(Caller);
12253 return ExprError();
12254 }
12255 }
12256 }
12257
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012258 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012259 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012260 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012261 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012262
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012263 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012264 // We only need to do this if there was actually an overload; otherwise
12265 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012266 if (!Method->isStatic()) {
12267 ExprResult ObjectArg =
12268 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12269 FoundDecl, Method);
12270 if (ObjectArg.isInvalid())
12271 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012272 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012273 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012274
12275 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012276 const FunctionProtoType *Proto =
12277 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012278 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012279 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012280 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012281
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012282 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012283
Richard Smith55ce3522012-06-25 20:30:08 +000012284 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012285 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012286
George Burgess IVaea6ade2015-09-25 17:53:16 +000012287 // In the case the method to call was not selected by the overloading
12288 // resolution process, we still need to handle the enable_if attribute. Do
12289 // that here, so it will not hide previous -- and more relevant -- errors
12290 if (isa<MemberExpr>(NakedMemExpr)) {
12291 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12292 Diag(MemExprE->getLocStart(),
12293 diag::err_ovl_no_viable_member_function_in_call)
12294 << Method << Method->getSourceRange();
12295 Diag(Method->getLocation(),
12296 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12297 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12298 return ExprError();
12299 }
12300 }
12301
Anders Carlsson47061ee2011-05-06 14:25:31 +000012302 if ((isa<CXXConstructorDecl>(CurContext) ||
12303 isa<CXXDestructorDecl>(CurContext)) &&
12304 TheCall->getMethodDecl()->isPure()) {
12305 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12306
Davide Italianoccb37382015-07-14 23:36:10 +000012307 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12308 MemExpr->performsVirtualDispatch(getLangOpts())) {
12309 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012310 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12311 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12312 << MD->getParent()->getDeclName();
12313
12314 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012315 if (getLangOpts().AppleKext)
12316 Diag(MemExpr->getLocStart(),
12317 diag::note_pure_qualified_call_kext)
12318 << MD->getParent()->getDeclName()
12319 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012320 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012321 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012322
12323 if (CXXDestructorDecl *DD =
12324 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12325 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12326 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12327 getLangOpts().AppleKext;
12328 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12329 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12330 MemExpr->getMemberLoc());
12331 }
12332
John McCallb268a282010-08-23 23:25:46 +000012333 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012334}
12335
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012336/// BuildCallToObjectOfClassType - Build a call to an object of class
12337/// type (C++ [over.call.object]), which can end up invoking an
12338/// overloaded function call operator (@c operator()) or performing a
12339/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012340ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012341Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012342 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012343 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012344 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012345 if (checkPlaceholderForOverload(*this, Obj))
12346 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012347 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012348
12349 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012350 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012351 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012352
Nico Weberb58e51c2014-11-19 05:21:39 +000012353 assert(Object.get()->getType()->isRecordType() &&
12354 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012355 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012356
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012357 // C++ [over.call.object]p1:
12358 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012359 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012360 // candidate functions includes at least the function call
12361 // operators of T. The function call operators of T are obtained by
12362 // ordinary lookup of the name operator() in the context of
12363 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012364 OverloadCandidateSet CandidateSet(LParenLoc,
12365 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012366 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012367
John Wiegley01296292011-04-08 18:41:53 +000012368 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012369 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012370 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012371
John McCall27b18f82009-11-17 02:14:36 +000012372 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12373 LookupQualifiedName(R, Record->getDecl());
12374 R.suppressDiagnostics();
12375
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012376 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012377 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012378 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012379 Object.get()->Classify(Context),
12380 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012381 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012383
Douglas Gregorab7897a2008-11-19 22:57:39 +000012384 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012385 // In addition, for each (non-explicit in C++0x) conversion function
12386 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012387 //
12388 // operator conversion-type-id () cv-qualifier;
12389 //
12390 // where cv-qualifier is the same cv-qualification as, or a
12391 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012392 // denotes the type "pointer to function of (P1,...,Pn) returning
12393 // R", or the type "reference to pointer to function of
12394 // (P1,...,Pn) returning R", or the type "reference to function
12395 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012396 // is also considered as a candidate function. Similarly,
12397 // surrogate call functions are added to the set of candidate
12398 // functions for each conversion function declared in an
12399 // accessible base class provided the function is not hidden
12400 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012401 const auto &Conversions =
12402 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12403 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012404 NamedDecl *D = *I;
12405 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12406 if (isa<UsingShadowDecl>(D))
12407 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012408
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012409 // Skip over templated conversion functions; they aren't
12410 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012411 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012412 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012413
John McCall6e9f8f62009-12-03 04:06:58 +000012414 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012415 if (!Conv->isExplicit()) {
12416 // Strip the reference type (if any) and then the pointer type (if
12417 // any) to get down to what might be a function type.
12418 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12419 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12420 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012421
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012422 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12423 {
12424 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012425 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012426 }
12427 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012428 }
Mike Stump11289f42009-09-09 15:08:12 +000012429
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012430 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12431
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012432 // Perform overload resolution.
12433 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012434 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012435 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012436 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012437 // Overload resolution succeeded; we'll build the appropriate call
12438 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012439 break;
12440
12441 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012442 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012443 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012444 << Object.get()->getType() << /*call*/ 1
12445 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012446 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012447 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012448 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012449 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012450 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012451 break;
12452
12453 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012454 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012455 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012456 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012457 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012458 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012459
12460 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012461 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012462 diag::err_ovl_deleted_object_call)
12463 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012464 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012465 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012466 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012467 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012468 break;
Mike Stump11289f42009-09-09 15:08:12 +000012469 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012470
Douglas Gregorb412e172010-07-25 18:17:45 +000012471 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012472 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012473
John McCall4124c492011-10-17 18:40:02 +000012474 UnbridgedCasts.restore();
12475
Craig Topperc3ec1492014-05-26 06:22:03 +000012476 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012477 // Since there is no function declaration, this is one of the
12478 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012479 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012480 = cast<CXXConversionDecl>(
12481 Best->Conversions[0].UserDefined.ConversionFunction);
12482
Craig Topperc3ec1492014-05-26 06:22:03 +000012483 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12484 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012485 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12486 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012487 assert(Conv == Best->FoundDecl.getDecl() &&
12488 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012489 // We selected one of the surrogate functions that converts the
12490 // object parameter to a function pointer. Perform the conversion
12491 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012492
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012493 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012494 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012495 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12496 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012497 if (Call.isInvalid())
12498 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012499 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012500 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12501 CK_UserDefinedConversion, Call.get(),
12502 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012503
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012504 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012505 }
12506
Craig Topperc3ec1492014-05-26 06:22:03 +000012507 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012508
Douglas Gregorab7897a2008-11-19 22:57:39 +000012509 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12510 // that calls this method, using Object for the implicit object
12511 // parameter and passing along the remaining arguments.
12512 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012513
12514 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012515 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012516 return ExprError();
12517
Chandler Carruth8e543b32010-12-12 08:17:55 +000012518 const FunctionProtoType *Proto =
12519 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012520
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012521 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012522
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012523 DeclarationNameInfo OpLocInfo(
12524 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12525 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012526 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012527 HadMultipleCandidates,
12528 OpLocInfo.getLoc(),
12529 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012530 if (NewFn.isInvalid())
12531 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012532
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012533 // Build the full argument list for the method call (the implicit object
12534 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012535 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012536 MethodArgs[0] = Object.get();
12537 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12538
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012539 // Once we've built TheCall, all of the expressions are properly
12540 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012541 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012542 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12543 ResultTy = ResultTy.getNonLValueExprType(Context);
12544
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012545 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012546 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012547 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12548 ResultTy, VK, RParenLoc, false);
12549 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012550
Alp Toker314cc812014-01-25 16:55:45 +000012551 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012552 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012553
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012554 // We may have default arguments. If so, we need to allocate more
12555 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012556 if (Args.size() < NumParams)
12557 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012558
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012559 bool IsError = false;
12560
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012561 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012562 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012563 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012564 Best->FoundDecl, Method);
12565 if (ObjRes.isInvalid())
12566 IsError = true;
12567 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012568 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012569 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012570
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012571 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012572 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012573 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012574 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012575 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012576
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012577 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012578
John McCalldadc5752010-08-24 06:29:42 +000012579 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012580 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012581 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012582 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012583 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012584
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012585 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012586 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012587 } else {
John McCalldadc5752010-08-24 06:29:42 +000012588 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012589 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12590 if (DefArg.isInvalid()) {
12591 IsError = true;
12592 break;
12593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012594
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012595 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012596 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012597
12598 TheCall->setArg(i + 1, Arg);
12599 }
12600
12601 // If this is a variadic call, handle args passed through "...".
12602 if (Proto->isVariadic()) {
12603 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012604 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012605 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12606 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012607 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012608 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012609 }
12610 }
12611
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012612 if (IsError) return true;
12613
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012614 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012615
Richard Smith55ce3522012-06-25 20:30:08 +000012616 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012617 return true;
12618
John McCalle172be52010-08-24 06:09:16 +000012619 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012620}
12621
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012622/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012623/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012624/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012625ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012626Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12627 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012628 assert(Base->getType()->isRecordType() &&
12629 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012630
John McCall4124c492011-10-17 18:40:02 +000012631 if (checkPlaceholderForOverload(*this, Base))
12632 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012633
John McCallbc077cf2010-02-08 23:07:23 +000012634 SourceLocation Loc = Base->getExprLoc();
12635
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012636 // C++ [over.ref]p1:
12637 //
12638 // [...] An expression x->m is interpreted as (x.operator->())->m
12639 // for a class object x of type T if T::operator->() exists and if
12640 // the operator is selected as the best match function by the
12641 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012642 DeclarationName OpName =
12643 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012644 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012645 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012646
John McCallbc077cf2010-02-08 23:07:23 +000012647 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012648 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012649 return ExprError();
12650
John McCall27b18f82009-11-17 02:14:36 +000012651 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12652 LookupQualifiedName(R, BaseRecord->getDecl());
12653 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012654
12655 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012656 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012657 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012658 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012659 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012660
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012661 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12662
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012663 // Perform overload resolution.
12664 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012665 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012666 case OR_Success:
12667 // Overload resolution succeeded; we'll build the call below.
12668 break;
12669
12670 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012671 if (CandidateSet.empty()) {
12672 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012673 if (NoArrowOperatorFound) {
12674 // Report this specific error to the caller instead of emitting a
12675 // diagnostic, as requested.
12676 *NoArrowOperatorFound = true;
12677 return ExprError();
12678 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012679 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12680 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012681 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012682 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012683 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012684 }
12685 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012686 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012687 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012688 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012689 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012690
12691 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012692 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12693 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012694 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012695 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012696
12697 case OR_Deleted:
12698 Diag(OpLoc, diag::err_ovl_deleted_oper)
12699 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012700 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012701 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012702 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012704 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012705 }
12706
Craig Topperc3ec1492014-05-26 06:22:03 +000012707 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012708
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012709 // Convert the object parameter.
12710 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012711 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012712 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012713 Best->FoundDecl, Method);
12714 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012715 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012716 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012717
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012718 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012719 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012720 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012721 if (FnExpr.isInvalid())
12722 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012723
Alp Toker314cc812014-01-25 16:55:45 +000012724 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012725 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12726 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012727 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012728 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012729 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012730
Alp Toker314cc812014-01-25 16:55:45 +000012731 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012732 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012733
12734 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012735}
12736
Richard Smithbcc22fc2012-03-09 08:00:36 +000012737/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12738/// a literal operator described by the provided lookup results.
12739ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12740 DeclarationNameInfo &SuffixInfo,
12741 ArrayRef<Expr*> Args,
12742 SourceLocation LitEndLoc,
12743 TemplateArgumentListInfo *TemplateArgs) {
12744 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012745
Richard Smith100b24a2014-04-17 01:52:14 +000012746 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12747 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012748 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12749 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012750
Richard Smithbcc22fc2012-03-09 08:00:36 +000012751 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12752
Richard Smithbcc22fc2012-03-09 08:00:36 +000012753 // Perform overload resolution. This will usually be trivial, but might need
12754 // to perform substitutions for a literal operator template.
12755 OverloadCandidateSet::iterator Best;
12756 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12757 case OR_Success:
12758 case OR_Deleted:
12759 break;
12760
12761 case OR_No_Viable_Function:
12762 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12763 << R.getLookupName();
12764 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12765 return ExprError();
12766
12767 case OR_Ambiguous:
12768 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12769 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12770 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012771 }
12772
Richard Smithbcc22fc2012-03-09 08:00:36 +000012773 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012774 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12775 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012776 SuffixInfo.getLoc(),
12777 SuffixInfo.getInfo());
12778 if (Fn.isInvalid())
12779 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012780
12781 // Check the argument types. This should almost always be a no-op, except
12782 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012783 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012784 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012785 ExprResult InputInit = PerformCopyInitialization(
12786 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12787 SourceLocation(), Args[ArgIdx]);
12788 if (InputInit.isInvalid())
12789 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012790 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012791 }
12792
Alp Toker314cc812014-01-25 16:55:45 +000012793 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012794 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12795 ResultTy = ResultTy.getNonLValueExprType(Context);
12796
Richard Smithc67fdd42012-03-07 08:35:16 +000012797 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012798 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012799 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012800 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12801
Alp Toker314cc812014-01-25 16:55:45 +000012802 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012803 return ExprError();
12804
Craig Topperc3ec1492014-05-26 06:22:03 +000012805 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012806 return ExprError();
12807
12808 return MaybeBindToTemporary(UDL);
12809}
12810
Sam Panzer0f384432012-08-21 00:52:01 +000012811/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12812/// given LookupResult is non-empty, it is assumed to describe a member which
12813/// will be invoked. Otherwise, the function will be found via argument
12814/// dependent lookup.
12815/// CallExpr is set to a valid expression and FRS_Success returned on success,
12816/// otherwise CallExpr is set to ExprError() and some non-success value
12817/// is returned.
12818Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012819Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12820 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012821 const DeclarationNameInfo &NameInfo,
12822 LookupResult &MemberLookup,
12823 OverloadCandidateSet *CandidateSet,
12824 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012825 Scope *S = nullptr;
12826
Sam Panzer0f384432012-08-21 00:52:01 +000012827 CandidateSet->clear();
12828 if (!MemberLookup.empty()) {
12829 ExprResult MemberRef =
12830 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12831 /*IsPtr=*/false, CXXScopeSpec(),
12832 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012833 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012834 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012835 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012836 if (MemberRef.isInvalid()) {
12837 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012838 return FRS_DiagnosticIssued;
12839 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012840 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012841 if (CallExpr->isInvalid()) {
12842 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012843 return FRS_DiagnosticIssued;
12844 }
12845 } else {
12846 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012847 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012848 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012849 NestedNameSpecifierLoc(), NameInfo,
12850 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012851 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012852
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012853 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012854 CandidateSet, CallExpr);
12855 if (CandidateSet->empty() || CandidateSetError) {
12856 *CallExpr = ExprError();
12857 return FRS_NoViableFunction;
12858 }
12859 OverloadCandidateSet::iterator Best;
12860 OverloadingResult OverloadResult =
12861 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12862
12863 if (OverloadResult == OR_No_Viable_Function) {
12864 *CallExpr = ExprError();
12865 return FRS_NoViableFunction;
12866 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012867 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012868 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012869 OverloadResult,
12870 /*AllowTypoCorrection=*/false);
12871 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12872 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012873 return FRS_DiagnosticIssued;
12874 }
12875 }
12876 return FRS_Success;
12877}
12878
12879
Douglas Gregorcd695e52008-11-10 20:40:00 +000012880/// FixOverloadedFunctionReference - E is an expression that refers to
12881/// a C++ overloaded function (possibly with some parentheses and
12882/// perhaps a '&' around it). We have resolved the overloaded function
12883/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012884/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012885Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012886 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012887 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012888 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12889 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012890 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012891 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012892
Douglas Gregor51c538b2009-11-20 19:42:02 +000012893 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012894 }
12895
Douglas Gregor51c538b2009-11-20 19:42:02 +000012896 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012897 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12898 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012899 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012900 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012901 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012902 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012903 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012904 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012905
12906 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012907 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012908 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012909 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012910 }
12911
Douglas Gregor51c538b2009-11-20 19:42:02 +000012912 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012913 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012914 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12916 if (Method->isStatic()) {
12917 // Do nothing: static member functions aren't any different
12918 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012919 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012920 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012921 // UnresolvedLookupExpr holding an overloaded member function
12922 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012923 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12924 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012925 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012926 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012927
John McCalld14a8642009-11-21 08:51:07 +000012928 assert(isa<DeclRefExpr>(SubExpr)
12929 && "fixed to something other than a decl ref");
12930 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12931 && "fixed to a member ref with no nested name qualifier");
12932
12933 // We have taken the address of a pointer to member
12934 // function. Perform the computation here so that we get the
12935 // appropriate pointer to member type.
12936 QualType ClassType
12937 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12938 QualType MemPtrType
12939 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12940
John McCall7decc9e2010-11-18 06:31:45 +000012941 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12942 VK_RValue, OK_Ordinary,
12943 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012944 }
12945 }
John McCall16df1e52010-03-30 21:47:33 +000012946 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12947 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012948 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012949 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012950
John McCalle3027922010-08-25 11:45:40 +000012951 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012952 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012953 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012954 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012955 }
John McCalld14a8642009-11-21 08:51:07 +000012956
12957 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012958 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012959 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012960 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012961 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12962 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012963 }
12964
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012965 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12966 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012967 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012968 Fn,
John McCall113bee02012-03-10 09:33:50 +000012969 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012970 ULE->getNameLoc(),
12971 Fn->getType(),
12972 VK_LValue,
12973 Found.getDecl(),
12974 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012975 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012976 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12977 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012978 }
12979
John McCall10eae182009-11-30 22:42:35 +000012980 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012981 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012982 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012983 if (MemExpr->hasExplicitTemplateArgs()) {
12984 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12985 TemplateArgs = &TemplateArgsBuffer;
12986 }
John McCall6b51f282009-11-23 01:53:49 +000012987
John McCall2d74de92009-12-01 22:10:20 +000012988 Expr *Base;
12989
John McCall7decc9e2010-11-18 06:31:45 +000012990 // If we're filling in a static method where we used to have an
12991 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012992 if (MemExpr->isImplicitAccess()) {
12993 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012994 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12995 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012996 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012997 Fn,
John McCall113bee02012-03-10 09:33:50 +000012998 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012999 MemExpr->getMemberLoc(),
13000 Fn->getType(),
13001 VK_LValue,
13002 Found.getDecl(),
13003 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013004 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013005 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13006 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013007 } else {
13008 SourceLocation Loc = MemExpr->getMemberLoc();
13009 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013010 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013011 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013012 Base = new (Context) CXXThisExpr(Loc,
13013 MemExpr->getBaseType(),
13014 /*isImplicit=*/true);
13015 }
John McCall2d74de92009-12-01 22:10:20 +000013016 } else
John McCallc3007a22010-10-26 07:05:15 +000013017 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013018
John McCall4adb38c2011-04-27 00:36:17 +000013019 ExprValueKind valueKind;
13020 QualType type;
13021 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13022 valueKind = VK_LValue;
13023 type = Fn->getType();
13024 } else {
13025 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013026 type = Context.BoundMemberTy;
13027 }
13028
13029 MemberExpr *ME = MemberExpr::Create(
13030 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13031 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13032 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13033 OK_Ordinary);
13034 ME->setHadMultipleCandidates(true);
13035 MarkMemberReferenced(ME);
13036 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013038
John McCallc3007a22010-10-26 07:05:15 +000013039 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013040}
13041
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013042ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013043 DeclAccessPair Found,
13044 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013045 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013046}