blob: 58949bfd440676170c56c1b7d7269c919aed8629 [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:
261 case CK_FloatingToIntegral:
262 case CK_FloatingToBoolean:
263 case CK_FloatingCast:
264 Converted = ICE->getSubExpr();
265 continue;
266
267 default:
268 return Converted;
269 }
270 }
271
272 return Converted;
273}
274
275/// Check if this standard conversion sequence represents a narrowing
276/// conversion, according to C++11 [dcl.init.list]p7.
277///
278/// \param Ctx The AST context.
279/// \param Converted The result of applying this standard conversion sequence.
280/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
281/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000282/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
283/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000284NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000285StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
286 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000287 APValue &ConstantValue,
288 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000290
291 // C++11 [dcl.init.list]p7:
292 // A narrowing conversion is an implicit conversion ...
293 QualType FromType = getToType(0);
294 QualType ToType = getToType(1);
295 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000296 // 'bool' is an integral type; dispatch to the right place to handle it.
297 case ICK_Boolean_Conversion:
298 if (FromType->isRealFloatingType())
299 goto FloatingIntegralConversion;
300 if (FromType->isIntegralOrUnscopedEnumerationType())
301 goto IntegralConversion;
302 // Boolean conversions can be from pointers and pointers to members
303 // [conv.bool], and those aren't considered narrowing conversions.
304 return NK_Not_Narrowing;
305
Richard Smith66e05fe2012-01-18 05:21:49 +0000306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000313 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000378 case ICK_Integral_Conversion:
379 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 assert(FromType->isIntegralOrUnscopedEnumerationType());
381 assert(ToType->isIntegralOrUnscopedEnumerationType());
382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
383 const unsigned FromWidth = Ctx.getIntWidth(FromType);
384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
385 const unsigned ToWidth = Ctx.getIntWidth(ToType);
386
387 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000388 (FromWidth == ToWidth && FromSigned != ToSigned) ||
389 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 // Not all values of FromType can be represented in ToType.
391 llvm::APSInt InitializerValue;
392 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
394 // Such conversions on variables are always narrowing.
395 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000396 }
397 bool Narrowing = false;
398 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000399 // Negative -> unsigned is narrowing. Otherwise, more bits is never
400 // narrowing.
401 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000403 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 // Add a bit to the InitializerValue so we don't have to worry about
405 // signed vs. unsigned comparisons.
406 InitializerValue = InitializerValue.extend(
407 InitializerValue.getBitWidth() + 1);
408 // Convert the initializer to and from the target width and signed-ness.
409 llvm::APSInt ConvertedValue = InitializerValue;
410 ConvertedValue = ConvertedValue.trunc(ToWidth);
411 ConvertedValue.setIsSigned(ToSigned);
412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
413 ConvertedValue.setIsSigned(InitializerValue.isSigned());
414 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000415 if (ConvertedValue != InitializerValue)
416 Narrowing = true;
417 }
418 if (Narrowing) {
419 ConstantType = Initializer->getType();
420 ConstantValue = APValue(InitializerValue);
421 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000422 }
423 }
424 return NK_Not_Narrowing;
425 }
426
427 default:
428 // Other kinds of conversions are not narrowings.
429 return NK_Not_Narrowing;
430 }
431}
432
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000433/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000435void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000436 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437 bool PrintedSomething = false;
438 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000440 PrintedSomething = true;
441 }
442
443 if (Second != ICK_Identity) {
444 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000446 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448
449 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000451 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 PrintedSomething = true;
457 }
458
459 if (Third != ICK_Identity) {
460 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 PrintedSomething = true;
465 }
466
467 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 }
470}
471
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000472/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000474void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000480 if (ConversionFunction)
481 OS << '\'' << *ConversionFunction << '\'';
482 else
483 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 }
488}
489
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000494 if (isStdInitializerListElement())
495 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 switch (ConversionKind) {
497 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000499 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 break;
505 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 break;
John McCall0d1da222010-01-12 00:44:57 +0000508 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000510 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 break;
514 }
515
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000516 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517}
518
John McCall0d1da222010-01-12 00:44:57 +0000519void AmbiguousConversionSequence::construct() {
520 new (&conversions()) ConversionSet();
521}
522
523void AmbiguousConversionSequence::destruct() {
524 conversions().~ConversionSet();
525}
526
527void
528AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
529 FromTypePtr = O.FromTypePtr;
530 ToTypePtr = O.ToTypePtr;
531 new (&conversions()) ConversionSet(O.conversions());
532}
533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000535 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000536 // template argument information.
537 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 TemplateArgument FirstArg;
539 TemplateArgument SecondArg;
540 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000542 // template parameter and template argument information.
543 struct DFIParamWithArguments : DFIArguments {
544 TemplateParameter Param;
545 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000546}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548/// \brief Convert from Sema's representation of template deduction information
549/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000550DeductionFailureInfo
551clang::MakeDeductionFailureInfo(ASTContext &Context,
552 Sema::TemplateDeductionResult TDK,
553 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000554 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000556 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000557 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 switch (TDK) {
559 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000560 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000562 case Sema::TDK_TooManyArguments:
563 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000567 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 Result.Data = Info.Param.getOpaqueValue();
569 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 case Sema::TDK_NonDeducedMismatch: {
572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIArguments *Saved = new (Context) DFIArguments;
574 Saved->FirstArg = Info.FirstArg;
575 Saved->SecondArg = Info.SecondArg;
576 Result.Data = Saved;
577 break;
578 }
579
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000581 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000582 // FIXME: Should allocate from normal heap so that we can free this later.
583 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 Saved->Param = Info.Param;
585 Saved->FirstArg = Info.FirstArg;
586 Saved->SecondArg = Info.SecondArg;
587 Result.Data = Saved;
588 break;
589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000593 if (Info.hasSFINAEDiagnostic()) {
594 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
595 SourceLocation(), PartialDiagnostic::NullDiagnostic());
596 Info.takeSFINAEDiagnostic(*Diag);
597 Result.HasDiagnostic = true;
598 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000602 Result.Data = Info.Expression;
603 break;
604
Richard Smith44ecdbd2013-01-31 05:19:49 +0000605 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 return Result;
610}
John McCall0d1da222010-01-12 00:44:57 +0000611
Larisse Voufo98b20f12013-07-19 23:00:19 +0000612void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
614 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000615 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 case Sema::TDK_InstantiationDepth:
617 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000620 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000621 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000625 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000627 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000628 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000630
631 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000632 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000633 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000634 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
635 Diag->~PartialDiagnosticAt();
636 HasDiagnostic = false;
637 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor461761d2010-05-08 18:20:53 +0000640 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000641 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 break;
643 }
644}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Larisse Voufo98b20f12013-07-19 23:00:19 +0000646PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000647 if (HasDiagnostic)
648 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000650}
651
Larisse Voufo98b20f12013-07-19 23:00:19 +0000652TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000655 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000659 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_NonDeducedMismatch:
661 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667
668 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000669 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000673 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674 break;
675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 return TemplateParameter();
678}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Larisse Voufo98b20f12013-07-19 23:00:19 +0000680TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000681 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000682 case Sema::TDK_Success:
683 case Sema::TDK_Invalid:
684 case Sema::TDK_InstantiationDepth:
685 case Sema::TDK_TooManyArguments:
686 case Sema::TDK_TooFewArguments:
687 case Sema::TDK_Incomplete:
688 case Sema::TDK_InvalidExplicitArguments:
689 case Sema::TDK_Inconsistent:
690 case Sema::TDK_Underqualified:
691 case Sema::TDK_NonDeducedMismatch:
692 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000693 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694
Richard Smith44ecdbd2013-01-31 05:19:49 +0000695 case Sema::TDK_SubstitutionFailure:
696 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smith44ecdbd2013-01-31 05:19:49 +0000698 // Unhandled
699 case Sema::TDK_MiscellaneousDeductionFailure:
700 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000701 }
702
Craig Topperc3ec1492014-05-26 06:22:03 +0000703 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000704}
705
Larisse Voufo98b20f12013-07-19 23:00:19 +0000706const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000709 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_InstantiationDepth:
711 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000714 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000715 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000716 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000717 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000721 case Sema::TDK_NonDeducedMismatch:
722 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723
Douglas Gregor461761d2010-05-08 18:20:53 +0000724 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000725 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 break;
727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Craig Topperc3ec1492014-05-26 06:22:03 +0000729 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731
Larisse Voufo98b20f12013-07-19 23:00:19 +0000732const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
734 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000735 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_InstantiationDepth:
737 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000738 case Sema::TDK_TooManyArguments:
739 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000740 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000741 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000742 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000743 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000744
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000746 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_NonDeducedMismatch:
748 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749
Douglas Gregor461761d2010-05-08 18:20:53 +0000750 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 break;
753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756}
757
Larisse Voufo98b20f12013-07-19 23:00:19 +0000758Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000759 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
760 Sema::TDK_FailedOverloadResolution)
761 return static_cast<Expr*>(Data);
762
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000764}
765
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000767 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000768 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
769 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000770 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
771 i->DeductionFailure.Destroy();
772 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000773}
774
775void OverloadCandidateSet::clear() {
776 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000777 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000778 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779 Functions.clear();
780}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781
John McCall4124c492011-10-17 18:40:02 +0000782namespace {
783 class UnbridgedCastsSet {
784 struct Entry {
785 Expr **Addr;
786 Expr *Saved;
787 };
788 SmallVector<Entry, 2> Entries;
789
790 public:
791 void save(Sema &S, Expr *&E) {
792 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
793 Entry entry = { &E, E };
794 Entries.push_back(entry);
795 E = S.stripARCUnbridgedCast(E);
796 }
797
798 void restore() {
799 for (SmallVectorImpl<Entry>::iterator
800 i = Entries.begin(), e = Entries.end(); i != e; ++i)
801 *i->Addr = i->Saved;
802 }
803 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000804}
John McCall4124c492011-10-17 18:40:02 +0000805
806/// checkPlaceholderForOverload - Do any interesting placeholder-like
807/// preprocessing on the given expression.
808///
809/// \param unbridgedCasts a collection to which to add unbridged casts;
810/// without this, they will be immediately diagnosed as errors
811///
812/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000813static bool
814checkPlaceholderForOverload(Sema &S, Expr *&E,
815 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000816 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
817 // We can't handle overloaded expressions here because overload
818 // resolution might reasonably tweak them.
819 if (placeholder->getKind() == BuiltinType::Overload) return false;
820
821 // If the context potentially accepts unbridged ARC casts, strip
822 // the unbridged cast and add it to the collection for later restoration.
823 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
824 unbridgedCasts) {
825 unbridgedCasts->save(S, E);
826 return false;
827 }
828
829 // Go ahead and check everything else.
830 ExprResult result = S.CheckPlaceholderExpr(E);
831 if (result.isInvalid())
832 return true;
833
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000834 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000835 return false;
836 }
837
838 // Nothing to do.
839 return false;
840}
841
842/// checkArgPlaceholdersForOverload - Check a set of call operands for
843/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000844static bool checkArgPlaceholdersForOverload(Sema &S,
845 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000846 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000847 for (unsigned i = 0, e = Args.size(); i != e; ++i)
848 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000849 return true;
850
851 return false;
852}
853
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000855// overload of the declarations in Old. This routine returns false if
856// New and Old cannot be overloaded, e.g., if New has the same
857// signature as some function in Old (C++ 1.3.10) or if the Old
858// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000859// it does return false, MatchedDecl will point to the decl that New
860// cannot be overloaded with. This decl may be a UsingShadowDecl on
861// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862//
863// Example: Given the following input:
864//
865// void f(int, float); // #1
866// void f(int, int); // #2
867// int f(int, int); // #3
868//
869// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000870// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871//
John McCall3d988d92009-12-02 08:47:38 +0000872// When we process #2, Old contains only the FunctionDecl for #1. By
873// comparing the parameter types, we see that #1 and #2 are overloaded
874// (since they have different signatures), so this routine returns
875// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876//
John McCall3d988d92009-12-02 08:47:38 +0000877// When we process #3, Old is an overload set containing #1 and #2. We
878// compare the signatures of #3 to #1 (they're overloaded, so we do
879// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
880// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881// signature), IsOverload returns false and MatchedDecl will be set to
882// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000883//
884// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
885// into a class by a using declaration. The rules for whether to hide
886// shadow declarations ignore some properties which otherwise figure
887// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000888Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000889Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
890 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000891 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000892 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000893 NamedDecl *OldD = *I;
894
895 bool OldIsUsingDecl = false;
896 if (isa<UsingShadowDecl>(OldD)) {
897 OldIsUsingDecl = true;
898
899 // We can always introduce two using declarations into the same
900 // context, even if they have identical signatures.
901 if (NewIsUsingDecl) continue;
902
903 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
904 }
905
Richard Smithf091e122015-09-15 01:28:55 +0000906 // A using-declaration does not conflict with another declaration
907 // if one of them is hidden.
908 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
909 continue;
910
John McCalle9cccd82010-06-16 08:42:20 +0000911 // If either declaration was introduced by a using declaration,
912 // we'll need to use slightly different rules for matching.
913 // Essentially, these rules are the normal rules, except that
914 // function templates hide function templates with different
915 // return types or template parameter lists.
916 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000917 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
918 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000919
Alp Tokera2794f92014-01-22 07:29:52 +0000920 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000921 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
922 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
923 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
924 continue;
925 }
926
Alp Tokera2794f92014-01-22 07:29:52 +0000927 if (!isa<FunctionTemplateDecl>(OldD) &&
928 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000929 continue;
930
John McCalldaa3d6b2009-12-09 03:35:25 +0000931 Match = *I;
932 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000933 }
John McCalla8987a2942010-11-10 03:01:53 +0000934 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000935 // We can overload with these, which can show up when doing
936 // redeclaration checks for UsingDecls.
937 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000938 } else if (isa<TagDecl>(OldD)) {
939 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000940 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
941 // Optimistically assume that an unresolved using decl will
942 // overload; if it doesn't, we'll have to diagnose during
943 // template instantiation.
944 } else {
John McCall1f82f242009-11-18 22:49:29 +0000945 // (C++ 13p1):
946 // Only function declarations can be overloaded; object and type
947 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000948 Match = *I;
949 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000950 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 }
John McCall1f82f242009-11-18 22:49:29 +0000952
John McCalldaa3d6b2009-12-09 03:35:25 +0000953 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000954}
955
Richard Smithac974a32013-06-30 09:48:50 +0000956bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
957 bool UseUsingDeclRules) {
958 // C++ [basic.start.main]p2: This function shall not be overloaded.
959 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000960 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000961
David Majnemerc729b0b2013-09-16 22:44:20 +0000962 // MSVCRT user defined entry points cannot be overloaded.
963 if (New->isMSVCRTEntryPoint())
964 return false;
965
John McCall1f82f242009-11-18 22:49:29 +0000966 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
967 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
968
969 // C++ [temp.fct]p2:
970 // A function template can be overloaded with other function templates
971 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000972 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000973 return true;
974
975 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000976 QualType OldQType = Context.getCanonicalType(Old->getType());
977 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000978
979 // Compare the signatures (C++ 1.3.10) of the two functions to
980 // determine whether they are overloads. If we find any mismatch
981 // in the signature, they are overloads.
982
983 // If either of these functions is a K&R-style function (no
984 // prototype), then we consider them to have matching signatures.
985 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
986 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
987 return false;
988
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000989 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
990 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000991
992 // The signature of a function includes the types of its
993 // parameters (C++ 1.3.10), which includes the presence or absence
994 // of the ellipsis; see C++ DR 357).
995 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000997 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000999 return true;
1000
1001 // C++ [temp.over.link]p4:
1002 // The signature of a function template consists of its function
1003 // signature, its return type and its template parameter list. The names
1004 // of the template parameters are significant only for establishing the
1005 // relationship between the template parameters and the rest of the
1006 // signature.
1007 //
1008 // We check the return type and template parameter lists for function
1009 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001010 //
1011 // However, we don't consider either of these when deciding whether
1012 // a member introduced by a shadow declaration is hidden.
1013 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001014 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1015 OldTemplate->getTemplateParameters(),
1016 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001017 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001018 return true;
1019
1020 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001021 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001022 //
1023 // As part of this, also check whether one of the member functions
1024 // is static, in which case they are not overloads (C++
1025 // 13.1p2). While not part of the definition of the signature,
1026 // this check is important to determine whether these functions
1027 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001028 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1029 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001030 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001031 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1032 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1033 if (!UseUsingDeclRules &&
1034 (OldMethod->getRefQualifier() == RQ_None ||
1035 NewMethod->getRefQualifier() == RQ_None)) {
1036 // C++0x [over.load]p2:
1037 // - Member function declarations with the same name and the same
1038 // parameter-type-list as well as member function template
1039 // declarations with the same name, the same parameter-type-list, and
1040 // the same template parameter lists cannot be overloaded if any of
1041 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001042 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001043 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001044 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001045 }
1046 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Richard Smith574f4f62013-01-14 05:37:29 +00001049 // We may not have applied the implicit const for a constexpr member
1050 // function yet (because we haven't yet resolved whether this is a static
1051 // or non-static member function). Add it now, on the assumption that this
1052 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001053 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001054 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001055 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001056 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001057 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001058
1059 // We do not allow overloading based off of '__restrict'.
1060 OldQuals &= ~Qualifiers::Restrict;
1061 NewQuals &= ~Qualifiers::Restrict;
1062 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001063 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001066 // Though pass_object_size is placed on parameters and takes an argument, we
1067 // consider it to be a function-level modifier for the sake of function
1068 // identity. Either the function has one or more parameters with
1069 // pass_object_size or it doesn't.
1070 if (functionHasPassObjectSizeParams(New) !=
1071 functionHasPassObjectSizeParams(Old))
1072 return true;
1073
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001074 // enable_if attributes are an order-sensitive part of the signature.
1075 for (specific_attr_iterator<EnableIfAttr>
1076 NewI = New->specific_attr_begin<EnableIfAttr>(),
1077 NewE = New->specific_attr_end<EnableIfAttr>(),
1078 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1079 OldE = Old->specific_attr_end<EnableIfAttr>();
1080 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1081 if (NewI == NewE || OldI == OldE)
1082 return true;
1083 llvm::FoldingSetNodeID NewID, OldID;
1084 NewI->getCond()->Profile(NewID, Context, true);
1085 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001086 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001087 return true;
1088 }
1089
Artem Belevich94a55e82015-09-22 17:22:59 +00001090 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1091 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1092 OldTarget = IdentifyCUDATarget(Old);
1093 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1094 return false;
1095
1096 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1097
1098 // Don't allow mixing of HD with other kinds. This guarantees that
1099 // we have only one viable function with this signature on any
1100 // side of CUDA compilation .
1101 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1102 return false;
1103
1104 // Allow overloading of functions with same signature, but
1105 // different CUDA target attributes.
1106 return NewTarget != OldTarget;
1107 }
1108
John McCall1f82f242009-11-18 22:49:29 +00001109 // The signatures match; this is not an overload.
1110 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111}
1112
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001113/// \brief Checks availability of the function depending on the current
1114/// function context. Inside an unavailable function, unavailability is ignored.
1115///
1116/// \returns true if \arg FD is unavailable and current context is inside
1117/// an available function, false otherwise.
1118bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1119 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1120}
1121
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001122/// \brief Tries a user-defined conversion from From to ToType.
1123///
1124/// Produces an implicit conversion sequence for when a standard conversion
1125/// is not an option. See TryImplicitConversion for more information.
1126static ImplicitConversionSequence
1127TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1128 bool SuppressUserConversions,
1129 bool AllowExplicit,
1130 bool InOverloadResolution,
1131 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001132 bool AllowObjCWritebackConversion,
1133 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 ImplicitConversionSequence ICS;
1135
1136 if (SuppressUserConversions) {
1137 // We're not in the case above, so there is no conversion that
1138 // we can perform.
1139 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1140 return ICS;
1141 }
1142
1143 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001144 OverloadCandidateSet Conversions(From->getExprLoc(),
1145 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001146 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1147 Conversions, AllowExplicit,
1148 AllowObjCConversionOnExplicit)) {
1149 case OR_Success:
1150 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001151 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001152 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001153 // C++ [over.ics.user]p4:
1154 // A conversion of an expression of class type to the same class
1155 // type is given Exact Match rank, and a conversion of an
1156 // expression of class type to a base class of that type is
1157 // given Conversion rank, in spite of the fact that a copy
1158 // constructor (i.e., a user-defined conversion function) is
1159 // called for those cases.
1160 if (CXXConstructorDecl *Constructor
1161 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1162 QualType FromCanon
1163 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1164 QualType ToCanon
1165 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1166 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001167 (FromCanon == ToCanon ||
1168 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001169 // Turn this into a "standard" conversion sequence, so that it
1170 // gets ranked with standard conversion sequences.
1171 ICS.setStandard();
1172 ICS.Standard.setAsIdentityConversion();
1173 ICS.Standard.setFromType(From->getType());
1174 ICS.Standard.setAllToTypes(ToType);
1175 ICS.Standard.CopyConstructor = Constructor;
1176 if (ToCanon != FromCanon)
1177 ICS.Standard.Second = ICK_Derived_To_Base;
1178 }
1179 }
Richard Smith48372b62015-01-27 03:30:40 +00001180 break;
1181
1182 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001183 ICS.setAmbiguous();
1184 ICS.Ambiguous.setFromType(From->getType());
1185 ICS.Ambiguous.setToType(ToType);
1186 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1187 Cand != Conversions.end(); ++Cand)
1188 if (Cand->Viable)
1189 ICS.Ambiguous.addConversion(Cand->Function);
1190 break;
Richard Smith48372b62015-01-27 03:30:40 +00001191
1192 // Fall through.
1193 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001195 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001196 }
1197
1198 return ICS;
1199}
1200
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001201/// TryImplicitConversion - Attempt to perform an implicit conversion
1202/// from the given expression (Expr) to the given type (ToType). This
1203/// function returns an implicit conversion sequence that can be used
1204/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001205///
1206/// void f(float f);
1207/// void g(int i) { f(i); }
1208///
1209/// this routine would produce an implicit conversion sequence to
1210/// describe the initialization of f from i, which will be a standard
1211/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1212/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1213//
1214/// Note that this routine only determines how the conversion can be
1215/// performed; it does not actually perform the conversion. As such,
1216/// it will not produce any diagnostics if no conversion is available,
1217/// but will instead return an implicit conversion sequence of kind
1218/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001219///
1220/// If @p SuppressUserConversions, then user-defined conversions are
1221/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001222/// If @p AllowExplicit, then explicit user-defined conversions are
1223/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001224///
1225/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1226/// writeback conversion, which allows __autoreleasing id* parameters to
1227/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001228static ImplicitConversionSequence
1229TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1230 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001232 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001233 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001234 bool AllowObjCWritebackConversion,
1235 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001237 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001238 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001239 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001240 return ICS;
1241 }
1242
David Blaikiebbafb8a2012-03-11 07:00:24 +00001243 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001244 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001245 return ICS;
1246 }
1247
Douglas Gregor836a7e82010-08-11 02:15:33 +00001248 // C++ [over.ics.user]p4:
1249 // A conversion of an expression of class type to the same class
1250 // type is given Exact Match rank, and a conversion of an
1251 // expression of class type to a base class of that type is
1252 // given Conversion rank, in spite of the fact that a copy/move
1253 // constructor (i.e., a user-defined conversion function) is
1254 // called for those cases.
1255 QualType FromType = From->getType();
1256 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001257 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001258 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001259 ICS.setStandard();
1260 ICS.Standard.setAsIdentityConversion();
1261 ICS.Standard.setFromType(FromType);
1262 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001263
Douglas Gregor5ab11652010-04-17 22:01:05 +00001264 // We don't actually check at this point whether there is a valid
1265 // copy/move constructor, since overloading just assumes that it
1266 // exists. When we actually perform initialization, we'll find the
1267 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001268 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269
Douglas Gregor5ab11652010-04-17 22:01:05 +00001270 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001271 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001272 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Douglas Gregor836a7e82010-08-11 02:15:33 +00001274 return ICS;
1275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001276
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1278 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001279 AllowObjCWritebackConversion,
1280 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001281}
1282
John McCall31168b02011-06-15 23:02:42 +00001283ImplicitConversionSequence
1284Sema::TryImplicitConversion(Expr *From, QualType ToType,
1285 bool SuppressUserConversions,
1286 bool AllowExplicit,
1287 bool InOverloadResolution,
1288 bool CStyle,
1289 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001290 return ::TryImplicitConversion(*this, From, ToType,
1291 SuppressUserConversions, AllowExplicit,
1292 InOverloadResolution, CStyle,
1293 AllowObjCWritebackConversion,
1294 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001295}
1296
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001297/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001298/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001299/// converted expression. Flavor is the kind of conversion we're
1300/// performing, used in the error message. If @p AllowExplicit,
1301/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001302ExprResult
1303Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001304 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001305 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001306 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001307}
1308
John Wiegley01296292011-04-08 18:41:53 +00001309ExprResult
1310Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001311 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001312 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001313 if (checkPlaceholderForOverload(*this, From))
1314 return ExprError();
1315
John McCall31168b02011-06-15 23:02:42 +00001316 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1317 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001318 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001319 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001320 if (getLangOpts().ObjC1)
1321 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1322 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001323 ICS = ::TryImplicitConversion(*this, From, ToType,
1324 /*SuppressUserConversions=*/false,
1325 AllowExplicit,
1326 /*InOverloadResolution=*/false,
1327 /*CStyle=*/false,
1328 AllowObjCWritebackConversion,
1329 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001330 return PerformImplicitConversion(From, ToType, ICS, Action);
1331}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332
1333/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001335bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1336 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001337 if (Context.hasSameUnqualifiedType(FromType, ToType))
1338 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001339
John McCall991eb4b2010-12-21 00:44:39 +00001340 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1341 // where F adds one of the following at most once:
1342 // - a pointer
1343 // - a member pointer
1344 // - a block pointer
1345 CanQualType CanTo = Context.getCanonicalType(ToType);
1346 CanQualType CanFrom = Context.getCanonicalType(FromType);
1347 Type::TypeClass TyClass = CanTo->getTypeClass();
1348 if (TyClass != CanFrom->getTypeClass()) return false;
1349 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1350 if (TyClass == Type::Pointer) {
1351 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1352 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1353 } else if (TyClass == Type::BlockPointer) {
1354 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1355 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1356 } else if (TyClass == Type::MemberPointer) {
1357 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1358 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1359 } else {
1360 return false;
1361 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001362
John McCall991eb4b2010-12-21 00:44:39 +00001363 TyClass = CanTo->getTypeClass();
1364 if (TyClass != CanFrom->getTypeClass()) return false;
1365 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1366 return false;
1367 }
1368
1369 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1370 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1371 if (!EInfo.getNoReturn()) return false;
1372
1373 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1374 assert(QualType(FromFn, 0).isCanonical());
1375 if (QualType(FromFn, 0) != CanTo) return false;
1376
1377 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001378 return true;
1379}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
Douglas Gregor46188682010-05-18 22:42:18 +00001381/// \brief Determine whether the conversion from FromType to ToType is a valid
1382/// vector conversion.
1383///
1384/// \param ICK Will be set to the vector conversion kind, if this is a vector
1385/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001386static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001388 // We need at least one of these types to be a vector type to have a vector
1389 // conversion.
1390 if (!ToType->isVectorType() && !FromType->isVectorType())
1391 return false;
1392
1393 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001394 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001395 return false;
1396
1397 // There are no conversions between extended vector types, only identity.
1398 if (ToType->isExtVectorType()) {
1399 // There are no conversions between extended vector types other than the
1400 // identity conversion.
1401 if (FromType->isExtVectorType())
1402 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403
Douglas Gregor46188682010-05-18 22:42:18 +00001404 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001405 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001406 ICK = ICK_Vector_Splat;
1407 return true;
1408 }
1409 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001410
1411 // We can perform the conversion between vector types in the following cases:
1412 // 1)vector types are equivalent AltiVec and GCC vector types
1413 // 2)lax vector conversions are permitted and the vector types are of the
1414 // same size
1415 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001416 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1417 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001418 ICK = ICK_Vector_Conversion;
1419 return true;
1420 }
Douglas Gregor46188682010-05-18 22:42:18 +00001421 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001422
Douglas Gregor46188682010-05-18 22:42:18 +00001423 return false;
1424}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001426static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1427 bool InOverloadResolution,
1428 StandardConversionSequence &SCS,
1429 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001430
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001431/// IsStandardConversion - Determines whether there is a standard
1432/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1433/// expression From to the type ToType. Standard conversion sequences
1434/// only consider non-class types; for conversions that involve class
1435/// types, use TryImplicitConversion. If a conversion exists, SCS will
1436/// contain the standard conversion sequence required to perform this
1437/// conversion and this routine will return true. Otherwise, this
1438/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001439static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1440 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001441 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001442 bool CStyle,
1443 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001444 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001446 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001447 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001448 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001449 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001450 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001451
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001452 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001453 // abort early. When overloading in C, however, we do permit them.
1454 if (S.getLangOpts().CPlusPlus &&
1455 (FromType->isRecordType() || ToType->isRecordType()))
1456 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001457
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458 // The first conversion can be an lvalue-to-rvalue conversion,
1459 // array-to-pointer conversion, or function-to-pointer conversion
1460 // (C++ 4p1).
1461
John McCall5c32be02010-08-24 20:38:10 +00001462 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001463 DeclAccessPair AccessPair;
1464 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001466 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001467 // We were able to resolve the address of the overloaded function,
1468 // so we can convert to the type of that function.
1469 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001470 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001471
1472 // we can sometimes resolve &foo<int> regardless of ToType, so check
1473 // if the type matches (identity) or we are converting to bool
1474 if (!S.Context.hasSameUnqualifiedType(
1475 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1476 QualType resultTy;
1477 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001478 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001479 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1480 // otherwise, only a boolean conversion is standard
1481 if (!ToType->isBooleanType())
1482 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Chandler Carruthffce2452011-03-29 08:08:18 +00001485 // Check if the "from" expression is taking the address of an overloaded
1486 // function and recompute the FromType accordingly. Take advantage of the
1487 // fact that non-static member functions *must* have such an address-of
1488 // expression.
1489 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1490 if (Method && !Method->isStatic()) {
1491 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1492 "Non-unary operator on non-static member address");
1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1494 == UO_AddrOf &&
1495 "Non-address-of operator on non-static member address");
1496 const Type *ClassType
1497 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1498 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001499 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1500 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1501 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001502 "Non-address-of operator for overloaded function expression");
1503 FromType = S.Context.getPointerType(FromType);
1504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505
Douglas Gregor980fb162010-04-29 18:24:40 +00001506 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001507 assert(S.Context.hasSameType(
1508 FromType,
1509 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001510 } else {
1511 return false;
1512 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001513 }
John McCall154a2fd2011-08-30 00:57:29 +00001514 // Lvalue-to-rvalue conversion (C++11 4.1):
1515 // A glvalue (3.10) of a non-function, non-array type T can
1516 // be converted to a prvalue.
1517 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001518 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001519 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001520 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522
Douglas Gregorc79862f2012-04-12 17:51:55 +00001523 // C11 6.3.2.1p2:
1524 // ... if the lvalue has atomic type, the value has the non-atomic version
1525 // of the type of the lvalue ...
1526 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1527 FromType = Atomic->getValueType();
1528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 // If T is a non-class type, the type of the rvalue is the
1530 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001531 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1532 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001534 } else if (FromType->isArrayType()) {
1535 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537
1538 // An lvalue or rvalue of type "array of N T" or "array of unknown
1539 // bound of T" can be converted to an rvalue of type "pointer to
1540 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001541 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001542
John McCall5c32be02010-08-24 20:38:10 +00001543 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001544 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001545 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546
1547 // For the purpose of ranking in overload resolution
1548 // (13.3.3.1.1), this conversion is considered an
1549 // array-to-pointer conversion followed by a qualification
1550 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.Second = ICK_Identity;
1552 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001553 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001554 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 }
John McCall086a4642010-11-24 05:12:34 +00001557 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001558 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001561 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1562 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1563 if (!S.checkAddressOfFunctionIsAvailable(FD))
1564 return false;
1565
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566 // An lvalue of function type T can be converted to an rvalue of
1567 // type "pointer to T." The result is a pointer to the
1568 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001569 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001570 } else {
1571 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001572 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001574 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001575
1576 // The second conversion can be an integral promotion, floating
1577 // point promotion, integral conversion, floating point conversion,
1578 // floating-integral conversion, pointer conversion,
1579 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001580 // For overloading in C, this can also be a "compatible-type"
1581 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001582 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001583 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001584 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585 // The unqualified versions of the types are the same: there's no
1586 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001587 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001588 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001589 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001592 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001594 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001596 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001597 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001598 SCS.Second = ICK_Complex_Promotion;
1599 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001600 } else if (ToType->isBooleanType() &&
1601 (FromType->isArithmeticType() ||
1602 FromType->isAnyPointerType() ||
1603 FromType->isBlockPointerType() ||
1604 FromType->isMemberPointerType() ||
1605 FromType->isNullPtrType())) {
1606 // Boolean conversions (C++ 4.12).
1607 SCS.Second = ICK_Boolean_Conversion;
1608 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001609 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001610 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001611 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001612 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001613 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001614 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001615 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001616 SCS.Second = ICK_Complex_Conversion;
1617 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001618 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1619 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001620 // Complex-real conversions (C99 6.3.1.7)
1621 SCS.Second = ICK_Complex_Real;
1622 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001623 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001624 // Floating point conversions (C++ 4.8).
1625 SCS.Second = ICK_Floating_Conversion;
1626 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001628 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001629 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001630 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001631 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001632 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001634 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001635 SCS.Second = ICK_Block_Pointer_Conversion;
1636 } else if (AllowObjCWritebackConversion &&
1637 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1638 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001639 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1640 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001641 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001642 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001643 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001644 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001645 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001646 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001647 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001648 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001649 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001650 SCS.Second = SecondICK;
1651 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001652 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001653 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001654 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001655 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001656 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001657 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001658 // Treat a conversion that strips "noreturn" as an identity conversion.
1659 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001660 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1661 InOverloadResolution,
1662 SCS, CStyle)) {
1663 SCS.Second = ICK_TransparentUnionConversion;
1664 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001665 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1666 CStyle)) {
1667 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001668 // appropriately.
1669 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001670 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001671 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001672 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001673 SCS.Second = ICK_Zero_Event_Conversion;
1674 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 } else {
1676 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001677 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001679 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001681 QualType CanonFrom;
1682 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001684 bool ObjCLifetimeConversion;
1685 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1686 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001687 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001688 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001690 CanonFrom = S.Context.getCanonicalType(FromType);
1691 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692 } else {
1693 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001694 SCS.Third = ICK_Identity;
1695
Mike Stump11289f42009-09-09 15:08:12 +00001696 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001697 // [...] Any difference in top-level cv-qualification is
1698 // subsumed by the initialization itself and does not constitute
1699 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001700 CanonFrom = S.Context.getCanonicalType(FromType);
1701 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001703 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001704 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001705 FromType = ToType;
1706 CanonFrom = CanonTo;
1707 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001709 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
George Burgess IV45461812015-10-11 20:13:20 +00001711 if (CanonFrom == CanonTo)
1712 return true;
1713
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001715 // this is a bad conversion sequence, unless we're resolving an overload in C.
1716 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001717 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718
George Burgess IV45461812015-10-11 20:13:20 +00001719 ExprResult ER = ExprResult{From};
1720 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1721 /*Diagnose=*/false,
1722 /*DiagnoseCFAudited=*/false,
1723 /*ConvertRHS=*/false);
1724 if (Conv != Sema::Compatible)
1725 return false;
1726
1727 SCS.setAllToTypes(ToType);
1728 // We need to set all three because we want this conversion to rank terribly,
1729 // and we don't know what conversions it may overlap with.
1730 SCS.First = ICK_C_Only_Conversion;
1731 SCS.Second = ICK_C_Only_Conversion;
1732 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001733 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001734}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001735
1736static bool
1737IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1738 QualType &ToType,
1739 bool InOverloadResolution,
1740 StandardConversionSequence &SCS,
1741 bool CStyle) {
1742
1743 const RecordType *UT = ToType->getAsUnionType();
1744 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1745 return false;
1746 // The field to initialize within the transparent union.
1747 RecordDecl *UD = UT->getDecl();
1748 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001749 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001750 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1751 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001752 ToType = it->getType();
1753 return true;
1754 }
1755 }
1756 return false;
1757}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758
1759/// IsIntegralPromotion - Determines whether the conversion from the
1760/// expression From (whose potentially-adjusted type is FromType) to
1761/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1762/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001763bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001764 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001765 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001766 if (!To) {
1767 return false;
1768 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001769
1770 // An rvalue of type char, signed char, unsigned char, short int, or
1771 // unsigned short int can be converted to an rvalue of type int if
1772 // int can represent all the values of the source type; otherwise,
1773 // the source rvalue can be converted to an rvalue of type unsigned
1774 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001775 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1776 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777 if (// We can promote any signed, promotable integer type to an int
1778 (FromType->isSignedIntegerType() ||
1779 // We can promote any unsigned integer type whose size is
1780 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001781 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001782 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001784 }
1785
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001786 return To->getKind() == BuiltinType::UInt;
1787 }
1788
Richard Smithb9c5a602012-09-13 21:18:54 +00001789 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001790 // A prvalue of an unscoped enumeration type whose underlying type is not
1791 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1792 // following types that can represent all the values of the enumeration
1793 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1794 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001795 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001797 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001798 // with lowest integer conversion rank (4.13) greater than the rank of long
1799 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001800 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001801 // C++11 [conv.prom]p4:
1802 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1803 // can be converted to a prvalue of its underlying type. Moreover, if
1804 // integral promotion can be applied to its underlying type, a prvalue of an
1805 // unscoped enumeration type whose underlying type is fixed can also be
1806 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001807 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1808 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1809 // provided for a scoped enumeration.
1810 if (FromEnumType->getDecl()->isScoped())
1811 return false;
1812
Richard Smithb9c5a602012-09-13 21:18:54 +00001813 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001814 // even if that's not the promoted type. Note that the check for promoting
1815 // the underlying type is based on the type alone, and does not consider
1816 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001817 if (FromEnumType->getDecl()->isFixed()) {
1818 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1819 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001820 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001821 }
1822
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001823 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001825 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001826 return Context.hasSameUnqualifiedType(
1827 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001828 }
John McCall56774992009-12-09 09:09:27 +00001829
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001830 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1832 // to an rvalue a prvalue of the first of the following types that can
1833 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001834 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001835 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001836 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001838 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001840 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 // Determine whether the type we're converting from is signed or
1842 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001843 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846 // The types we'll try to promote to, in the appropriate
1847 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001848 QualType PromoteTypes[6] = {
1849 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001850 Context.LongTy, Context.UnsignedLongTy ,
1851 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001852 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001853 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001854 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1855 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001856 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001857 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1858 // We found the type that we can promote to. If this is the
1859 // type we wanted, we have a promotion. Otherwise, no
1860 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001861 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001862 }
1863 }
1864 }
1865
1866 // An rvalue for an integral bit-field (9.6) can be converted to an
1867 // rvalue of type int if int can represent all the values of the
1868 // bit-field; otherwise, it can be converted to unsigned int if
1869 // unsigned int can represent all the values of the bit-field. If
1870 // the bit-field is larger yet, no integral promotion applies to
1871 // it. If the bit-field has an enumerated type, it is treated as any
1872 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001873 // FIXME: We should delay checking of bit-fields until we actually perform the
1874 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001875 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001876 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001877 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001878 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001879 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001880 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001881 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001883 // Are we promoting to an int from a bitfield that fits in an int?
1884 if (BitWidth < ToSize ||
1885 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1886 return To->getKind() == BuiltinType::Int;
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001889 // Are we promoting to an unsigned int from an unsigned bitfield
1890 // that fits into an unsigned int?
1891 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1892 return To->getKind() == BuiltinType::UInt;
1893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001895 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001896 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001897 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001898 }
Mike Stump11289f42009-09-09 15:08:12 +00001899
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001900 // An rvalue of type bool can be converted to an rvalue of type int,
1901 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001902 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001903 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001904 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001905
1906 return false;
1907}
1908
1909/// IsFloatingPointPromotion - Determines whether the conversion from
1910/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1911/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001912bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001913 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1914 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001915 /// An rvalue of type float can be converted to an rvalue of type
1916 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001917 if (FromBuiltin->getKind() == BuiltinType::Float &&
1918 ToBuiltin->getKind() == BuiltinType::Double)
1919 return true;
1920
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001921 // C99 6.3.1.5p1:
1922 // When a float is promoted to double or long double, or a
1923 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001924 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001925 (FromBuiltin->getKind() == BuiltinType::Float ||
1926 FromBuiltin->getKind() == BuiltinType::Double) &&
1927 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1928 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001929
1930 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001931 if (!getLangOpts().NativeHalfType &&
1932 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001933 ToBuiltin->getKind() == BuiltinType::Float)
1934 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001935 }
1936
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001937 return false;
1938}
1939
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001940/// \brief Determine if a conversion is a complex promotion.
1941///
1942/// A complex promotion is defined as a complex -> complex conversion
1943/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001944/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001945bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001946 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001947 if (!FromComplex)
1948 return false;
1949
John McCall9dd450b2009-09-21 23:43:11 +00001950 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001951 if (!ToComplex)
1952 return false;
1953
1954 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001955 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001956 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001957 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001958}
1959
Douglas Gregor237f96c2008-11-26 23:31:11 +00001960/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1961/// the pointer type FromPtr to a pointer to type ToPointee, with the
1962/// same type qualifiers as FromPtr has on its pointee type. ToType,
1963/// if non-empty, will be a pointer to ToType that may or may not have
1964/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001965///
Mike Stump11289f42009-09-09 15:08:12 +00001966static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001967BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001968 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001969 ASTContext &Context,
1970 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001971 assert((FromPtr->getTypeClass() == Type::Pointer ||
1972 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1973 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001974
John McCall31168b02011-06-15 23:02:42 +00001975 /// Conversions to 'id' subsume cv-qualifier conversions.
1976 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001977 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978
1979 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001980 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001981 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001982 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001983
John McCall31168b02011-06-15 23:02:42 +00001984 if (StripObjCLifetime)
1985 Quals.removeObjCLifetime();
1986
Mike Stump11289f42009-09-09 15:08:12 +00001987 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001988 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001989 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001990 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001991 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001992
1993 // Build a pointer to ToPointee. It has the right qualifiers
1994 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001995 if (isa<ObjCObjectPointerType>(ToType))
1996 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001997 return Context.getPointerType(ToPointee);
1998 }
1999
2000 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002001 QualType QualifiedCanonToPointee
2002 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002004 if (isa<ObjCObjectPointerType>(ToType))
2005 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2006 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002007}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Mike Stump11289f42009-09-09 15:08:12 +00002009static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002010 bool InOverloadResolution,
2011 ASTContext &Context) {
2012 // Handle value-dependent integral null pointer constants correctly.
2013 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2014 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002015 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002016 return !InOverloadResolution;
2017
Douglas Gregor56751b52009-09-25 04:25:58 +00002018 return Expr->isNullPointerConstant(Context,
2019 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2020 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002021}
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002023/// IsPointerConversion - Determines whether the conversion of the
2024/// expression From, which has the (possibly adjusted) type FromType,
2025/// can be converted to the type ToType via a pointer conversion (C++
2026/// 4.10). If so, returns true and places the converted type (that
2027/// might differ from ToType in its cv-qualifiers at some level) into
2028/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002029///
Douglas Gregora29dc052008-11-27 01:19:21 +00002030/// This routine also supports conversions to and from block pointers
2031/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2032/// pointers to interfaces. FIXME: Once we've determined the
2033/// appropriate overloading rules for Objective-C, we may want to
2034/// split the Objective-C checks into a different routine; however,
2035/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002036/// conversions, so for now they live here. IncompatibleObjC will be
2037/// set if the conversion is an allowed Objective-C conversion that
2038/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002039bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002040 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002041 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002042 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002043 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002044 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2045 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002046 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002047
Mike Stump11289f42009-09-09 15:08:12 +00002048 // Conversion from a null pointer constant to any Objective-C pointer type.
2049 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002050 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002051 ConvertedType = ToType;
2052 return true;
2053 }
2054
Douglas Gregor231d1c62008-11-27 00:15:41 +00002055 // Blocks: Block pointers can be converted to void*.
2056 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002057 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002058 ConvertedType = ToType;
2059 return true;
2060 }
2061 // Blocks: A null pointer constant can be converted to a block
2062 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002063 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002064 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002065 ConvertedType = ToType;
2066 return true;
2067 }
2068
Sebastian Redl576fd422009-05-10 18:38:11 +00002069 // If the left-hand-side is nullptr_t, the right side can be a null
2070 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002071 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002072 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002073 ConvertedType = ToType;
2074 return true;
2075 }
2076
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002077 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002078 if (!ToTypePtr)
2079 return false;
2080
2081 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002082 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002083 ConvertedType = ToType;
2084 return true;
2085 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002086
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002088 // , including objective-c pointers.
2089 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002090 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002091 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002092 ConvertedType = BuildSimilarlyQualifiedPointerType(
2093 FromType->getAs<ObjCObjectPointerType>(),
2094 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002095 ToType, Context);
2096 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002097 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002098 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002099 if (!FromTypePtr)
2100 return false;
2101
2102 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002103
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002105 // pointer conversion, so don't do all of the work below.
2106 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2107 return false;
2108
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 // An rvalue of type "pointer to cv T," where T is an object type,
2110 // can be converted to an rvalue of type "pointer to cv void" (C++
2111 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002112 if (FromPointeeType->isIncompleteOrObjectType() &&
2113 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002114 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002115 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002116 ToType, Context,
2117 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002118 return true;
2119 }
2120
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002121 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002122 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002123 ToPointeeType->isVoidType()) {
2124 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2125 ToPointeeType,
2126 ToType, Context);
2127 return true;
2128 }
2129
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002130 // When we're overloading in C, we allow a special kind of pointer
2131 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002132 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002133 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002134 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002135 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002136 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002137 return true;
2138 }
2139
Douglas Gregor5c407d92008-10-23 00:40:37 +00002140 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002141 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002142 // An rvalue of type "pointer to cv D," where D is a class type,
2143 // can be converted to an rvalue of type "pointer to cv B," where
2144 // B is a base class (clause 10) of D. If B is an inaccessible
2145 // (clause 11) or ambiguous (10.2) base class of D, a program that
2146 // necessitates this conversion is ill-formed. The result of the
2147 // conversion is a pointer to the base class sub-object of the
2148 // derived class object. The null pointer value is converted to
2149 // the null pointer value of the destination type.
2150 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002151 // Note that we do not check for ambiguity or inaccessibility
2152 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002153 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002154 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002155 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002156 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002158 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002159 ToType, Context);
2160 return true;
2161 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002162
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002163 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2164 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2166 ToPointeeType,
2167 ToType, Context);
2168 return true;
2169 }
2170
Douglas Gregora119f102008-12-19 19:13:09 +00002171 return false;
2172}
Douglas Gregoraec25842011-04-26 23:16:46 +00002173
2174/// \brief Adopt the given qualifiers for the given type.
2175static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2176 Qualifiers TQs = T.getQualifiers();
2177
2178 // Check whether qualifiers already match.
2179 if (TQs == Qs)
2180 return T;
2181
2182 if (Qs.compatiblyIncludes(TQs))
2183 return Context.getQualifiedType(T, Qs);
2184
2185 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2186}
Douglas Gregora119f102008-12-19 19:13:09 +00002187
2188/// isObjCPointerConversion - Determines whether this is an
2189/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2190/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002191bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002192 QualType& ConvertedType,
2193 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002194 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002195 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregoraec25842011-04-26 23:16:46 +00002197 // The set of qualifiers on the type we're converting from.
2198 Qualifiers FromQualifiers = FromType.getQualifiers();
2199
Steve Naroff7cae42b2009-07-10 23:34:53 +00002200 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002201 const ObjCObjectPointerType* ToObjCPtr =
2202 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002203 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002204 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002205
Steve Naroff7cae42b2009-07-10 23:34:53 +00002206 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002207 // If the pointee types are the same (ignoring qualifications),
2208 // then this is not a pointer conversion.
2209 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2210 FromObjCPtr->getPointeeType()))
2211 return false;
2212
Douglas Gregorab209d82015-07-07 03:58:42 +00002213 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002214 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002215 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2216 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002217 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002218 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2219 FromObjCPtr->getPointeeType()))
2220 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002222 ToObjCPtr->getPointeeType(),
2223 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002225 return true;
2226 }
2227
2228 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2229 // Okay: this is some kind of implicit downcast of Objective-C
2230 // interfaces, which is permitted. However, we're going to
2231 // complain about it.
2232 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002234 ToObjCPtr->getPointeeType(),
2235 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002237 return true;
2238 }
Mike Stump11289f42009-09-09 15:08:12 +00002239 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002240 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002241 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002242 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002243 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002245 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002246 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002247 // to a block pointer type.
2248 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002249 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002250 return true;
2251 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002252 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002254 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002255 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002256 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002257 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002259 return true;
2260 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002261 else
Douglas Gregora119f102008-12-19 19:13:09 +00002262 return false;
2263
Douglas Gregor033f56d2008-12-23 00:53:59 +00002264 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002265 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002266 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002267 else if (const BlockPointerType *FromBlockPtr =
2268 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002269 FromPointeeType = FromBlockPtr->getPointeeType();
2270 else
Douglas Gregora119f102008-12-19 19:13:09 +00002271 return false;
2272
Douglas Gregora119f102008-12-19 19:13:09 +00002273 // If we have pointers to pointers, recursively check whether this
2274 // is an Objective-C conversion.
2275 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2277 IncompatibleObjC)) {
2278 // We always complain about this conversion.
2279 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002280 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002281 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002282 return true;
2283 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002284 // Allow conversion of pointee being objective-c pointer to another one;
2285 // as in I* to id.
2286 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2287 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2288 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2289 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002290
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002291 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002292 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002293 return true;
2294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295
Douglas Gregor033f56d2008-12-23 00:53:59 +00002296 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002297 // differences in the argument and result types are in Objective-C
2298 // pointer conversions. If so, we permit the conversion (but
2299 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002300 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002301 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002302 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002303 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002304 if (FromFunctionType && ToFunctionType) {
2305 // If the function types are exactly the same, this isn't an
2306 // Objective-C pointer conversion.
2307 if (Context.getCanonicalType(FromPointeeType)
2308 == Context.getCanonicalType(ToPointeeType))
2309 return false;
2310
2311 // Perform the quick checks that will tell us whether these
2312 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002313 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002314 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2315 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2316 return false;
2317
2318 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002319 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2320 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002321 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002322 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2323 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002324 ConvertedType, IncompatibleObjC)) {
2325 // Okay, we have an Objective-C pointer conversion.
2326 HasObjCConversion = true;
2327 } else {
2328 // Function types are too different. Abort.
2329 return false;
2330 }
Mike Stump11289f42009-09-09 15:08:12 +00002331
Douglas Gregora119f102008-12-19 19:13:09 +00002332 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002333 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002334 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002335 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2336 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002337 if (Context.getCanonicalType(FromArgType)
2338 == Context.getCanonicalType(ToArgType)) {
2339 // Okay, the types match exactly. Nothing to do.
2340 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2341 ConvertedType, IncompatibleObjC)) {
2342 // Okay, we have an Objective-C pointer conversion.
2343 HasObjCConversion = true;
2344 } else {
2345 // Argument types are too different. Abort.
2346 return false;
2347 }
2348 }
2349
2350 if (HasObjCConversion) {
2351 // We had an Objective-C conversion. Allow this pointer
2352 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002353 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002354 IncompatibleObjC = true;
2355 return true;
2356 }
2357 }
2358
Sebastian Redl72b597d2009-01-25 19:43:20 +00002359 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002360}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002361
John McCall31168b02011-06-15 23:02:42 +00002362/// \brief Determine whether this is an Objective-C writeback conversion,
2363/// used for parameter passing when performing automatic reference counting.
2364///
2365/// \param FromType The type we're converting form.
2366///
2367/// \param ToType The type we're converting to.
2368///
2369/// \param ConvertedType The type that will be produced after applying
2370/// this conversion.
2371bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2372 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002374 Context.hasSameUnqualifiedType(FromType, ToType))
2375 return false;
2376
2377 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2378 QualType ToPointee;
2379 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2380 ToPointee = ToPointer->getPointeeType();
2381 else
2382 return false;
2383
2384 Qualifiers ToQuals = ToPointee.getQualifiers();
2385 if (!ToPointee->isObjCLifetimeType() ||
2386 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002387 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002388 return false;
2389
2390 // Argument must be a pointer to __strong to __weak.
2391 QualType FromPointee;
2392 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2393 FromPointee = FromPointer->getPointeeType();
2394 else
2395 return false;
2396
2397 Qualifiers FromQuals = FromPointee.getQualifiers();
2398 if (!FromPointee->isObjCLifetimeType() ||
2399 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2400 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2401 return false;
2402
2403 // Make sure that we have compatible qualifiers.
2404 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2405 if (!ToQuals.compatiblyIncludes(FromQuals))
2406 return false;
2407
2408 // Remove qualifiers from the pointee type we're converting from; they
2409 // aren't used in the compatibility check belong, and we'll be adding back
2410 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2411 FromPointee = FromPointee.getUnqualifiedType();
2412
2413 // The unqualified form of the pointee types must be compatible.
2414 ToPointee = ToPointee.getUnqualifiedType();
2415 bool IncompatibleObjC;
2416 if (Context.typesAreCompatible(FromPointee, ToPointee))
2417 FromPointee = ToPointee;
2418 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2419 IncompatibleObjC))
2420 return false;
2421
2422 /// \brief Construct the type we're converting to, which is a pointer to
2423 /// __autoreleasing pointee.
2424 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2425 ConvertedType = Context.getPointerType(FromPointee);
2426 return true;
2427}
2428
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002429bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2430 QualType& ConvertedType) {
2431 QualType ToPointeeType;
2432 if (const BlockPointerType *ToBlockPtr =
2433 ToType->getAs<BlockPointerType>())
2434 ToPointeeType = ToBlockPtr->getPointeeType();
2435 else
2436 return false;
2437
2438 QualType FromPointeeType;
2439 if (const BlockPointerType *FromBlockPtr =
2440 FromType->getAs<BlockPointerType>())
2441 FromPointeeType = FromBlockPtr->getPointeeType();
2442 else
2443 return false;
2444 // We have pointer to blocks, check whether the only
2445 // differences in the argument and result types are in Objective-C
2446 // pointer conversions. If so, we permit the conversion.
2447
2448 const FunctionProtoType *FromFunctionType
2449 = FromPointeeType->getAs<FunctionProtoType>();
2450 const FunctionProtoType *ToFunctionType
2451 = ToPointeeType->getAs<FunctionProtoType>();
2452
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002453 if (!FromFunctionType || !ToFunctionType)
2454 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002455
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002456 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002457 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002458
2459 // Perform the quick checks that will tell us whether these
2460 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2463 return false;
2464
2465 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2466 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2467 if (FromEInfo != ToEInfo)
2468 return false;
2469
2470 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002471 if (Context.hasSameType(FromFunctionType->getReturnType(),
2472 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002473 // Okay, the types match exactly. Nothing to do.
2474 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002475 QualType RHS = FromFunctionType->getReturnType();
2476 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002477 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002478 !RHS.hasQualifiers() && LHS.hasQualifiers())
2479 LHS = LHS.getUnqualifiedType();
2480
2481 if (Context.hasSameType(RHS,LHS)) {
2482 // OK exact match.
2483 } else if (isObjCPointerConversion(RHS, LHS,
2484 ConvertedType, IncompatibleObjC)) {
2485 if (IncompatibleObjC)
2486 return false;
2487 // Okay, we have an Objective-C pointer conversion.
2488 }
2489 else
2490 return false;
2491 }
2492
2493 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002494 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002495 ArgIdx != NumArgs; ++ArgIdx) {
2496 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002497 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2498 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002499 if (Context.hasSameType(FromArgType, ToArgType)) {
2500 // Okay, the types match exactly. Nothing to do.
2501 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2502 ConvertedType, IncompatibleObjC)) {
2503 if (IncompatibleObjC)
2504 return false;
2505 // Okay, we have an Objective-C pointer conversion.
2506 } else
2507 // Argument types are too different. Abort.
2508 return false;
2509 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002510 if (LangOpts.ObjCAutoRefCount &&
2511 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2512 ToFunctionType))
2513 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002514
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002515 ConvertedType = ToType;
2516 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002517}
2518
Richard Trieucaff2472011-11-23 22:32:32 +00002519enum {
2520 ft_default,
2521 ft_different_class,
2522 ft_parameter_arity,
2523 ft_parameter_mismatch,
2524 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002525 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002526};
2527
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002528/// Attempts to get the FunctionProtoType from a Type. Handles
2529/// MemberFunctionPointers properly.
2530static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2531 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2532 return FPT;
2533
2534 if (auto *MPT = FromType->getAs<MemberPointerType>())
2535 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2536
2537 return nullptr;
2538}
2539
Richard Trieucaff2472011-11-23 22:32:32 +00002540/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2541/// function types. Catches different number of parameter, mismatch in
2542/// parameter types, and different return types.
2543void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2544 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002545 // If either type is not valid, include no extra info.
2546 if (FromType.isNull() || ToType.isNull()) {
2547 PDiag << ft_default;
2548 return;
2549 }
2550
Richard Trieucaff2472011-11-23 22:32:32 +00002551 // Get the function type from the pointers.
2552 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2553 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2554 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002555 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002556 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2557 << QualType(FromMember->getClass(), 0);
2558 return;
2559 }
2560 FromType = FromMember->getPointeeType();
2561 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002562 }
2563
Richard Trieu96ed5b62011-12-13 23:19:45 +00002564 if (FromType->isPointerType())
2565 FromType = FromType->getPointeeType();
2566 if (ToType->isPointerType())
2567 ToType = ToType->getPointeeType();
2568
2569 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002570 FromType = FromType.getNonReferenceType();
2571 ToType = ToType.getNonReferenceType();
2572
Richard Trieucaff2472011-11-23 22:32:32 +00002573 // Don't print extra info for non-specialized template functions.
2574 if (FromType->isInstantiationDependentType() &&
2575 !FromType->getAs<TemplateSpecializationType>()) {
2576 PDiag << ft_default;
2577 return;
2578 }
2579
Richard Trieu96ed5b62011-12-13 23:19:45 +00002580 // No extra info for same types.
2581 if (Context.hasSameType(FromType, ToType)) {
2582 PDiag << ft_default;
2583 return;
2584 }
2585
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002586 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2587 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002588
2589 // Both types need to be function types.
2590 if (!FromFunction || !ToFunction) {
2591 PDiag << ft_default;
2592 return;
2593 }
2594
Alp Toker9cacbab2014-01-20 20:26:09 +00002595 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2596 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2597 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002598 return;
2599 }
2600
2601 // Handle different parameter types.
2602 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002603 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002604 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002605 << ToFunction->getParamType(ArgPos)
2606 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002607 return;
2608 }
2609
2610 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002611 if (!Context.hasSameType(FromFunction->getReturnType(),
2612 ToFunction->getReturnType())) {
2613 PDiag << ft_return_type << ToFunction->getReturnType()
2614 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002615 return;
2616 }
2617
2618 unsigned FromQuals = FromFunction->getTypeQuals(),
2619 ToQuals = ToFunction->getTypeQuals();
2620 if (FromQuals != ToQuals) {
2621 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2622 return;
2623 }
2624
2625 // Unable to find a difference, so add no extra info.
2626 PDiag << ft_default;
2627}
2628
Alp Toker9cacbab2014-01-20 20:26:09 +00002629/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002630/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002631/// they have same number of arguments. If the parameters are different,
2632/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002633bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2634 const FunctionProtoType *NewType,
2635 unsigned *ArgPos) {
2636 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2637 N = NewType->param_type_begin(),
2638 E = OldType->param_type_end();
2639 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002640 if (!Context.hasSameType(O->getUnqualifiedType(),
2641 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002642 if (ArgPos)
2643 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002644 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002645 }
2646 }
2647 return true;
2648}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002649
Douglas Gregor39c16d42008-10-24 04:54:22 +00002650/// CheckPointerConversion - Check the pointer conversion from the
2651/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002652/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002653/// conversions for which IsPointerConversion has already returned
2654/// true. It returns true and produces a diagnostic if there was an
2655/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002656bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002657 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002658 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002659 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002660 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002661 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002662
John McCall8cb679e2010-11-15 09:13:47 +00002663 Kind = CK_BitCast;
2664
David Blaikie1c7c8f72012-08-08 17:33:31 +00002665 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002666 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002667 Expr::NPCK_ZeroExpression) {
2668 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2669 DiagRuntimeBehavior(From->getExprLoc(), From,
2670 PDiag(diag::warn_impcast_bool_to_null_pointer)
2671 << ToType << From->getSourceRange());
2672 else if (!isUnevaluatedContext())
2673 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2674 << ToType << From->getSourceRange();
2675 }
John McCall9320b872011-09-09 05:25:32 +00002676 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2677 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002678 QualType FromPointeeType = FromPtrType->getPointeeType(),
2679 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002680
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002683 // We must have a derived-to-base conversion. Check an
2684 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2686 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002687 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002688 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002689 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002691 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002692 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002693 }
David Majnemer6bf02822015-10-31 08:42:14 +00002694
2695 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() &&
2696 ToPointeeType->isVoidType()) {
2697 assert(getLangOpts().MSVCCompat &&
2698 "this should only be possible with MSVCCompat!");
2699 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2700 << From->getSourceRange();
2701 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002702 }
John McCall9320b872011-09-09 05:25:32 +00002703 } else if (const ObjCObjectPointerType *ToPtrType =
2704 ToType->getAs<ObjCObjectPointerType>()) {
2705 if (const ObjCObjectPointerType *FromPtrType =
2706 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002707 // Objective-C++ conversions are always okay.
2708 // FIXME: We should have a different class of conversions for the
2709 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002710 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002711 return false;
John McCall9320b872011-09-09 05:25:32 +00002712 } else if (FromType->isBlockPointerType()) {
2713 Kind = CK_BlockPointerToObjCPointerCast;
2714 } else {
2715 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002716 }
John McCall9320b872011-09-09 05:25:32 +00002717 } else if (ToType->isBlockPointerType()) {
2718 if (!FromType->isBlockPointerType())
2719 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002720 }
John McCall8cb679e2010-11-15 09:13:47 +00002721
2722 // We shouldn't fall into this case unless it's valid for other
2723 // reasons.
2724 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2725 Kind = CK_NullToPointer;
2726
Douglas Gregor39c16d42008-10-24 04:54:22 +00002727 return false;
2728}
2729
Sebastian Redl72b597d2009-01-25 19:43:20 +00002730/// IsMemberPointerConversion - Determines whether the conversion of the
2731/// expression From, which has the (possibly adjusted) type FromType, can be
2732/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2733/// If so, returns true and places the converted type (that might differ from
2734/// ToType in its cv-qualifiers at some level) into ConvertedType.
2735bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002736 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002737 bool InOverloadResolution,
2738 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002739 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002740 if (!ToTypePtr)
2741 return false;
2742
2743 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002744 if (From->isNullPointerConstant(Context,
2745 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2746 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002747 ConvertedType = ToType;
2748 return true;
2749 }
2750
2751 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002752 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002753 if (!FromTypePtr)
2754 return false;
2755
2756 // A pointer to member of B can be converted to a pointer to member of D,
2757 // where D is derived from B (C++ 4.11p2).
2758 QualType FromClass(FromTypePtr->getClass(), 0);
2759 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002760
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002761 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002762 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002763 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2764 ToClass.getTypePtr());
2765 return true;
2766 }
2767
2768 return false;
2769}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002770
Sebastian Redl72b597d2009-01-25 19:43:20 +00002771/// CheckMemberPointerConversion - Check the member pointer conversion from the
2772/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002773/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002774/// for which IsMemberPointerConversion has already returned true. It returns
2775/// true and produces a diagnostic if there was an error, or returns false
2776/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002777bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002778 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002779 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002780 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002781 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002782 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002783 if (!FromPtrType) {
2784 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002786 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002787 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002788 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002789 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002790 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002792 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002793 assert(ToPtrType && "No member pointer cast has a target type "
2794 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002795
Sebastian Redled8f2002009-01-28 18:33:18 +00002796 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2797 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002798
Sebastian Redled8f2002009-01-28 18:33:18 +00002799 // FIXME: What about dependent types?
2800 assert(FromClass->isRecordType() && "Pointer into non-class.");
2801 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002802
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002803 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002804 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002805 bool DerivationOkay =
2806 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002807 assert(DerivationOkay &&
2808 "Should not have been called if derivation isn't OK.");
2809 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002810
Sebastian Redled8f2002009-01-28 18:33:18 +00002811 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2812 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002813 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2814 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2815 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2816 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002817 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002818
Douglas Gregor89ee6822009-02-28 01:32:25 +00002819 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002820 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2821 << FromClass << ToClass << QualType(VBase, 0)
2822 << From->getSourceRange();
2823 return true;
2824 }
2825
John McCall5b0829a2010-02-10 09:31:12 +00002826 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002827 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2828 Paths.front(),
2829 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002830
Anders Carlssond7923c62009-08-22 23:33:40 +00002831 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002832 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002833 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002834 return false;
2835}
2836
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002837/// Determine whether the lifetime conversion between the two given
2838/// qualifiers sets is nontrivial.
2839static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2840 Qualifiers ToQuals) {
2841 // Converting anything to const __unsafe_unretained is trivial.
2842 if (ToQuals.hasConst() &&
2843 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2844 return false;
2845
2846 return true;
2847}
2848
Douglas Gregor9a657932008-10-21 23:43:52 +00002849/// IsQualificationConversion - Determines whether the conversion from
2850/// an rvalue of type FromType to ToType is a qualification conversion
2851/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002852///
2853/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2854/// when the qualification conversion involves a change in the Objective-C
2855/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002856bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002858 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002859 FromType = Context.getCanonicalType(FromType);
2860 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002861 ObjCLifetimeConversion = false;
2862
Douglas Gregor9a657932008-10-21 23:43:52 +00002863 // If FromType and ToType are the same type, this is not a
2864 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002865 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002866 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002867
Douglas Gregor9a657932008-10-21 23:43:52 +00002868 // (C++ 4.4p4):
2869 // A conversion can add cv-qualifiers at levels other than the first
2870 // in multi-level pointers, subject to the following rules: [...]
2871 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002872 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002873 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002874 // Within each iteration of the loop, we check the qualifiers to
2875 // determine if this still looks like a qualification
2876 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002877 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002878 // until there are no more pointers or pointers-to-members left to
2879 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002880 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002881
Douglas Gregor90609aa2011-04-25 18:40:17 +00002882 Qualifiers FromQuals = FromType.getQualifiers();
2883 Qualifiers ToQuals = ToType.getQualifiers();
2884
John McCall31168b02011-06-15 23:02:42 +00002885 // Objective-C ARC:
2886 // Check Objective-C lifetime conversions.
2887 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2888 UnwrappedAnyPointer) {
2889 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002890 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2891 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002892 FromQuals.removeObjCLifetime();
2893 ToQuals.removeObjCLifetime();
2894 } else {
2895 // Qualification conversions cannot cast between different
2896 // Objective-C lifetime qualifiers.
2897 return false;
2898 }
2899 }
2900
Douglas Gregorf30053d2011-05-08 06:09:53 +00002901 // Allow addition/removal of GC attributes but not changing GC attributes.
2902 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2903 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2904 FromQuals.removeObjCGCAttr();
2905 ToQuals.removeObjCGCAttr();
2906 }
2907
Douglas Gregor9a657932008-10-21 23:43:52 +00002908 // -- for every j > 0, if const is in cv 1,j then const is in cv
2909 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002910 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002911 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Douglas Gregor9a657932008-10-21 23:43:52 +00002913 // -- if the cv 1,j and cv 2,j are different, then const is in
2914 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002915 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002916 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002917 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregor9a657932008-10-21 23:43:52 +00002919 // Keep track of whether all prior cv-qualifiers in the "to" type
2920 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002921 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002922 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002923 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002924
2925 // We are left with FromType and ToType being the pointee types
2926 // after unwrapping the original FromType and ToType the same number
2927 // of types. If we unwrapped any pointers, and if FromType and
2928 // ToType have the same unqualified type (since we checked
2929 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002930 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002931}
2932
Douglas Gregorc79862f2012-04-12 17:51:55 +00002933/// \brief - Determine whether this is a conversion from a scalar type to an
2934/// atomic type.
2935///
2936/// If successful, updates \c SCS's second and third steps in the conversion
2937/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002938static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2939 bool InOverloadResolution,
2940 StandardConversionSequence &SCS,
2941 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002942 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2943 if (!ToAtomic)
2944 return false;
2945
2946 StandardConversionSequence InnerSCS;
2947 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2948 InOverloadResolution, InnerSCS,
2949 CStyle, /*AllowObjCWritebackConversion=*/false))
2950 return false;
2951
2952 SCS.Second = InnerSCS.Second;
2953 SCS.setToType(1, InnerSCS.getToType(1));
2954 SCS.Third = InnerSCS.Third;
2955 SCS.QualificationIncludesObjCLifetime
2956 = InnerSCS.QualificationIncludesObjCLifetime;
2957 SCS.setToType(2, InnerSCS.getToType(2));
2958 return true;
2959}
2960
Sebastian Redle5417162012-03-27 18:33:03 +00002961static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2962 CXXConstructorDecl *Constructor,
2963 QualType Type) {
2964 const FunctionProtoType *CtorType =
2965 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002966 if (CtorType->getNumParams() > 0) {
2967 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002968 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2969 return true;
2970 }
2971 return false;
2972}
2973
Sebastian Redl82ace982012-02-11 23:51:08 +00002974static OverloadingResult
2975IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2976 CXXRecordDecl *To,
2977 UserDefinedConversionSequence &User,
2978 OverloadCandidateSet &CandidateSet,
2979 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002980 DeclContext::lookup_result R = S.LookupConstructors(To);
2981 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002982 Con != ConEnd; ++Con) {
2983 NamedDecl *D = *Con;
2984 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2985
2986 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002987 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002988 FunctionTemplateDecl *ConstructorTmpl
2989 = dyn_cast<FunctionTemplateDecl>(D);
2990 if (ConstructorTmpl)
2991 Constructor
2992 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2993 else
2994 Constructor = cast<CXXConstructorDecl>(D);
2995
2996 bool Usable = !Constructor->isInvalidDecl() &&
2997 S.isInitListConstructor(Constructor) &&
2998 (AllowExplicit || !Constructor->isExplicit());
2999 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003000 // If the first argument is (a reference to) the target type,
3001 // suppress conversions.
3002 bool SuppressUserConversions =
3003 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003004 if (ConstructorTmpl)
3005 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003006 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003007 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003008 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003009 else
3010 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003011 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003012 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003013 }
3014 }
3015
3016 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3017
3018 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003019 switch (auto Result =
3020 CandidateSet.BestViableFunction(S, From->getLocStart(),
3021 Best, true)) {
3022 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003023 case OR_Success: {
3024 // Record the standard conversion we used and the conversion function.
3025 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003026 QualType ThisType = Constructor->getThisType(S.Context);
3027 // Initializer lists don't have conversions as such.
3028 User.Before.setAsIdentityConversion();
3029 User.HadMultipleCandidates = HadMultipleCandidates;
3030 User.ConversionFunction = Constructor;
3031 User.FoundConversionFunction = Best->FoundDecl;
3032 User.After.setAsIdentityConversion();
3033 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3034 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003035 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003036 }
3037
3038 case OR_No_Viable_Function:
3039 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003040 case OR_Ambiguous:
3041 return OR_Ambiguous;
3042 }
3043
3044 llvm_unreachable("Invalid OverloadResult!");
3045}
3046
Douglas Gregor576e98c2009-01-30 23:27:23 +00003047/// Determines whether there is a user-defined conversion sequence
3048/// (C++ [over.ics.user]) that converts expression From to the type
3049/// ToType. If such a conversion exists, User will contain the
3050/// user-defined conversion sequence that performs such a conversion
3051/// and this routine will return true. Otherwise, this routine returns
3052/// false and User is unspecified.
3053///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003054/// \param AllowExplicit true if the conversion should consider C++0x
3055/// "explicit" conversion functions as well as non-explicit conversion
3056/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003057///
3058/// \param AllowObjCConversionOnExplicit true if the conversion should
3059/// allow an extra Objective-C pointer conversion on uses of explicit
3060/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003061static OverloadingResult
3062IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003063 UserDefinedConversionSequence &User,
3064 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003065 bool AllowExplicit,
3066 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003067 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003068
Douglas Gregor5ab11652010-04-17 22:01:05 +00003069 // Whether we will only visit constructors.
3070 bool ConstructorsOnly = false;
3071
3072 // If the type we are conversion to is a class type, enumerate its
3073 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003075 // C++ [over.match.ctor]p1:
3076 // When objects of class type are direct-initialized (8.5), or
3077 // copy-initialized from an expression of the same or a
3078 // derived class type (8.5), overload resolution selects the
3079 // constructor. [...] For copy-initialization, the candidate
3080 // functions are all the converting constructors (12.3.1) of
3081 // that class. The argument list is the expression-list within
3082 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003083 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003084 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003085 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 ConstructorsOnly = true;
3087
Richard Smith82b8d4e2015-12-18 22:19:11 +00003088 if (S.RequireCompleteType(From->getExprLoc(), ToType, 0)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003089 // We're not going to find any constructors.
3090 } else if (CXXRecordDecl *ToRecordDecl
3091 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003092
3093 Expr **Args = &From;
3094 unsigned NumArgs = 1;
3095 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003096 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003097 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003098 OverloadingResult Result = IsInitializerListConstructorConversion(
3099 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3100 if (Result != OR_No_Viable_Function)
3101 return Result;
3102 // Never mind.
3103 CandidateSet.clear();
3104
3105 // If we're list-initializing, we pass the individual elements as
3106 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003107 Args = InitList->getInits();
3108 NumArgs = InitList->getNumInits();
3109 ListInitializing = true;
3110 }
3111
David Blaikieff7d47a2012-12-19 00:45:41 +00003112 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3113 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003114 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003115 NamedDecl *D = *Con;
3116 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3117
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003118 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003119 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003120 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003121 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003122 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003123 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003124 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3125 else
John McCalla0296f72010-03-19 07:35:19 +00003126 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003128 bool Usable = !Constructor->isInvalidDecl();
3129 if (ListInitializing)
3130 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3131 else
3132 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3133 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003134 bool SuppressUserConversions = !ConstructorsOnly;
3135 if (SuppressUserConversions && ListInitializing) {
3136 SuppressUserConversions = false;
3137 if (NumArgs == 1) {
3138 // If the first argument is (a reference to) the target type,
3139 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003140 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3141 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003142 }
3143 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003144 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003145 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003146 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003147 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003148 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003149 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003150 // Allow one user-defined conversion when user specifies a
3151 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003152 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003153 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003154 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003155 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003156 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003157 }
3158 }
3159
Douglas Gregor5ab11652010-04-17 22:01:05 +00003160 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003161 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003162 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003163 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003164 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003165 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003166 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003167 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3168 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003169 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3170 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003171 DeclAccessPair FoundDecl = I.getPair();
3172 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003173 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3174 if (isa<UsingShadowDecl>(D))
3175 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3176
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003177 CXXConversionDecl *Conv;
3178 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003179 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003181 else
John McCallda4458e2010-03-31 01:36:47 +00003182 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003183
3184 if (AllowExplicit || !Conv->isExplicit()) {
3185 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003186 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3187 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003188 CandidateSet,
3189 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003190 else
John McCall5c32be02010-08-24 20:38:10 +00003191 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003192 From, ToType, CandidateSet,
3193 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003194 }
3195 }
3196 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003197 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003198
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003199 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3200
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003201 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003202 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3203 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003204 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003205 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003206 // Record the standard conversion we used and the conversion function.
3207 if (CXXConstructorDecl *Constructor
3208 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3209 // C++ [over.ics.user]p1:
3210 // If the user-defined conversion is specified by a
3211 // constructor (12.3.1), the initial standard conversion
3212 // sequence converts the source type to the type required by
3213 // the argument of the constructor.
3214 //
3215 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003216 if (isa<InitListExpr>(From)) {
3217 // Initializer lists don't have conversions as such.
3218 User.Before.setAsIdentityConversion();
3219 } else {
3220 if (Best->Conversions[0].isEllipsis())
3221 User.EllipsisConversion = true;
3222 else {
3223 User.Before = Best->Conversions[0].Standard;
3224 User.EllipsisConversion = false;
3225 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003226 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003227 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003228 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003229 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003230 User.After.setAsIdentityConversion();
3231 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3232 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003233 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003234 }
3235 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003236 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3237 // C++ [over.ics.user]p1:
3238 //
3239 // [...] If the user-defined conversion is specified by a
3240 // conversion function (12.3.2), the initial standard
3241 // conversion sequence converts the source type to the
3242 // implicit object parameter of the conversion function.
3243 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003244 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003245 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003246 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003247 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003248
John McCall5c32be02010-08-24 20:38:10 +00003249 // C++ [over.ics.user]p2:
3250 // The second standard conversion sequence converts the
3251 // result of the user-defined conversion to the target type
3252 // for the sequence. Since an implicit conversion sequence
3253 // is an initialization, the special rules for
3254 // initialization by user-defined conversion apply when
3255 // selecting the best user-defined conversion for a
3256 // user-defined conversion sequence (see 13.3.3 and
3257 // 13.3.3.1).
3258 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003259 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003260 }
David Blaikie8a40f702012-01-17 06:56:22 +00003261 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003262
John McCall5c32be02010-08-24 20:38:10 +00003263 case OR_No_Viable_Function:
3264 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
John McCall5c32be02010-08-24 20:38:10 +00003266 case OR_Ambiguous:
3267 return OR_Ambiguous;
3268 }
3269
David Blaikie8a40f702012-01-17 06:56:22 +00003270 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003271}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003273bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003274Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003275 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003276 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3277 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003279 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003280 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003281 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003282 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3283 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003284 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003285 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003286 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003287 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003288 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003289 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003291 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003294}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003295
Douglas Gregor2837aa22012-02-22 17:32:19 +00003296/// \brief Compare the user-defined conversion functions or constructors
3297/// of two user-defined conversion sequences to determine whether any ordering
3298/// is possible.
3299static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003300compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003301 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003302 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003303 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003304
Douglas Gregor2837aa22012-02-22 17:32:19 +00003305 // Objective-C++:
3306 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003307 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003308 // respectively, always prefer the conversion to a function pointer,
3309 // because the function pointer is more lightweight and is more likely
3310 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003311 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003312 if (!Conv1)
3313 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003314
Douglas Gregor2837aa22012-02-22 17:32:19 +00003315 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3316 if (!Conv2)
3317 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003318
Douglas Gregor2837aa22012-02-22 17:32:19 +00003319 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3320 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3321 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3322 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003323 return Block1 ? ImplicitConversionSequence::Worse
3324 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003325 }
3326
3327 return ImplicitConversionSequence::Indistinguishable;
3328}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003329
3330static bool hasDeprecatedStringLiteralToCharPtrConversion(
3331 const ImplicitConversionSequence &ICS) {
3332 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3333 (ICS.isUserDefined() &&
3334 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3335}
3336
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003337/// CompareImplicitConversionSequences - Compare two implicit
3338/// conversion sequences to determine whether one is better than the
3339/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003340static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003341CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003342 const ImplicitConversionSequence& ICS1,
3343 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003344{
3345 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3346 // conversion sequences (as defined in 13.3.3.1)
3347 // -- a standard conversion sequence (13.3.3.1.1) is a better
3348 // conversion sequence than a user-defined conversion sequence or
3349 // an ellipsis conversion sequence, and
3350 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3351 // conversion sequence than an ellipsis conversion sequence
3352 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003353 //
John McCall0d1da222010-01-12 00:44:57 +00003354 // C++0x [over.best.ics]p10:
3355 // For the purpose of ranking implicit conversion sequences as
3356 // described in 13.3.3.2, the ambiguous conversion sequence is
3357 // treated as a user-defined sequence that is indistinguishable
3358 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003359
3360 // String literal to 'char *' conversion has been deprecated in C++03. It has
3361 // been removed from C++11. We still accept this conversion, if it happens at
3362 // the best viable function. Otherwise, this conversion is considered worse
3363 // than ellipsis conversion. Consider this as an extension; this is not in the
3364 // standard. For example:
3365 //
3366 // int &f(...); // #1
3367 // void f(char*); // #2
3368 // void g() { int &r = f("foo"); }
3369 //
3370 // In C++03, we pick #2 as the best viable function.
3371 // In C++11, we pick #1 as the best viable function, because ellipsis
3372 // conversion is better than string-literal to char* conversion (since there
3373 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3374 // convert arguments, #2 would be the best viable function in C++11.
3375 // If the best viable function has this conversion, a warning will be issued
3376 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3377
3378 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3379 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3380 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3381 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3382 ? ImplicitConversionSequence::Worse
3383 : ImplicitConversionSequence::Better;
3384
Douglas Gregor5ab11652010-04-17 22:01:05 +00003385 if (ICS1.getKindRank() < ICS2.getKindRank())
3386 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003387 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003388 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003389
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003390 // The following checks require both conversion sequences to be of
3391 // the same kind.
3392 if (ICS1.getKind() != ICS2.getKind())
3393 return ImplicitConversionSequence::Indistinguishable;
3394
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003395 ImplicitConversionSequence::CompareKind Result =
3396 ImplicitConversionSequence::Indistinguishable;
3397
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003398 // Two implicit conversion sequences of the same form are
3399 // indistinguishable conversion sequences unless one of the
3400 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003401
3402 // List-initialization sequence L1 is a better conversion sequence than
3403 // list-initialization sequence L2 if:
3404 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3405 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003406 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003407 // and N1 is smaller than N2.,
3408 // even if one of the other rules in this paragraph would otherwise apply.
3409 if (!ICS1.isBad()) {
3410 if (ICS1.isStdInitializerListElement() &&
3411 !ICS2.isStdInitializerListElement())
3412 return ImplicitConversionSequence::Better;
3413 if (!ICS1.isStdInitializerListElement() &&
3414 ICS2.isStdInitializerListElement())
3415 return ImplicitConversionSequence::Worse;
3416 }
3417
John McCall0d1da222010-01-12 00:44:57 +00003418 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003419 // Standard conversion sequence S1 is a better conversion sequence than
3420 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003421 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003422 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003423 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003424 // User-defined conversion sequence U1 is a better conversion
3425 // sequence than another user-defined conversion sequence U2 if
3426 // they contain the same user-defined conversion function or
3427 // constructor and if the second standard conversion sequence of
3428 // U1 is better than the second standard conversion sequence of
3429 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003430 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003431 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003432 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003433 ICS1.UserDefined.After,
3434 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003435 else
3436 Result = compareConversionFunctions(S,
3437 ICS1.UserDefined.ConversionFunction,
3438 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003439 }
3440
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003441 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003442}
3443
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003444static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3445 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3446 Qualifiers Quals;
3447 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003451 return Context.hasSameUnqualifiedType(T1, T2);
3452}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003454// Per 13.3.3.2p3, compare the given standard conversion sequences to
3455// determine if one is a proper subset of the other.
3456static ImplicitConversionSequence::CompareKind
3457compareStandardConversionSubsets(ASTContext &Context,
3458 const StandardConversionSequence& SCS1,
3459 const StandardConversionSequence& SCS2) {
3460 ImplicitConversionSequence::CompareKind Result
3461 = ImplicitConversionSequence::Indistinguishable;
3462
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003464 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003465 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3466 return ImplicitConversionSequence::Better;
3467 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3468 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003470 if (SCS1.Second != SCS2.Second) {
3471 if (SCS1.Second == ICK_Identity)
3472 Result = ImplicitConversionSequence::Better;
3473 else if (SCS2.Second == ICK_Identity)
3474 Result = ImplicitConversionSequence::Worse;
3475 else
3476 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003477 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003478 return ImplicitConversionSequence::Indistinguishable;
3479
3480 if (SCS1.Third == SCS2.Third) {
3481 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3482 : ImplicitConversionSequence::Indistinguishable;
3483 }
3484
3485 if (SCS1.Third == ICK_Identity)
3486 return Result == ImplicitConversionSequence::Worse
3487 ? ImplicitConversionSequence::Indistinguishable
3488 : ImplicitConversionSequence::Better;
3489
3490 if (SCS2.Third == ICK_Identity)
3491 return Result == ImplicitConversionSequence::Better
3492 ? ImplicitConversionSequence::Indistinguishable
3493 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003495 return ImplicitConversionSequence::Indistinguishable;
3496}
3497
Douglas Gregore696ebb2011-01-26 14:52:12 +00003498/// \brief Determine whether one of the given reference bindings is better
3499/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003500static bool
3501isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3502 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003503 // C++0x [over.ics.rank]p3b4:
3504 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3505 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003507 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003509 // reference*.
3510 //
3511 // FIXME: Rvalue references. We're going rogue with the above edits,
3512 // because the semantics in the current C++0x working paper (N3225 at the
3513 // time of this writing) break the standard definition of std::forward
3514 // and std::reference_wrapper when dealing with references to functions.
3515 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003516 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3517 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3518 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519
Douglas Gregore696ebb2011-01-26 14:52:12 +00003520 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3521 SCS2.IsLvalueReference) ||
3522 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003523 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003524}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003526/// CompareStandardConversionSequences - Compare two standard
3527/// conversion sequences to determine whether one is better than the
3528/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003529static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003530CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003531 const StandardConversionSequence& SCS1,
3532 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003533{
3534 // Standard conversion sequence S1 is a better conversion sequence
3535 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3536
3537 // -- S1 is a proper subsequence of S2 (comparing the conversion
3538 // sequences in the canonical form defined by 13.3.3.1.1,
3539 // excluding any Lvalue Transformation; the identity conversion
3540 // sequence is considered to be a subsequence of any
3541 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003542 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003543 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003544 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003545
3546 // -- the rank of S1 is better than the rank of S2 (by the rules
3547 // defined below), or, if not that,
3548 ImplicitConversionRank Rank1 = SCS1.getRank();
3549 ImplicitConversionRank Rank2 = SCS2.getRank();
3550 if (Rank1 < Rank2)
3551 return ImplicitConversionSequence::Better;
3552 else if (Rank2 < Rank1)
3553 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003554
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003555 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3556 // are indistinguishable unless one of the following rules
3557 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003558
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559 // A conversion that is not a conversion of a pointer, or
3560 // pointer to member, to bool is better than another conversion
3561 // that is such a conversion.
3562 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3563 return SCS2.isPointerConversionToBool()
3564 ? ImplicitConversionSequence::Better
3565 : ImplicitConversionSequence::Worse;
3566
Douglas Gregor5c407d92008-10-23 00:40:37 +00003567 // C++ [over.ics.rank]p4b2:
3568 //
3569 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003570 // conversion of B* to A* is better than conversion of B* to
3571 // void*, and conversion of A* to void* is better than conversion
3572 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003573 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003574 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003575 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003576 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003577 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3578 // Exactly one of the conversion sequences is a conversion to
3579 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003580 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3581 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003582 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3583 // Neither conversion sequence converts to a void pointer; compare
3584 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003585 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003586 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003587 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003588 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3589 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003590 // Both conversion sequences are conversions to void
3591 // pointers. Compare the source types to determine if there's an
3592 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003593 QualType FromType1 = SCS1.getFromType();
3594 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003595
3596 // Adjust the types we're converting from via the array-to-pointer
3597 // conversion, if we need to.
3598 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003599 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003601 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003602
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003603 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3604 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003605
Richard Smith0f59cb32015-12-18 21:45:41 +00003606 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003607 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003608 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003609 return ImplicitConversionSequence::Worse;
3610
3611 // Objective-C++: If one interface is more specific than the
3612 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003613 const ObjCObjectPointerType* FromObjCPtr1
3614 = FromType1->getAs<ObjCObjectPointerType>();
3615 const ObjCObjectPointerType* FromObjCPtr2
3616 = FromType2->getAs<ObjCObjectPointerType>();
3617 if (FromObjCPtr1 && FromObjCPtr2) {
3618 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3619 FromObjCPtr2);
3620 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3621 FromObjCPtr1);
3622 if (AssignLeft != AssignRight) {
3623 return AssignLeft? ImplicitConversionSequence::Better
3624 : ImplicitConversionSequence::Worse;
3625 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003626 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003627 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003628
3629 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3630 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003631 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003632 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003633 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003634
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003635 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003636 // Check for a better reference binding based on the kind of bindings.
3637 if (isBetterReferenceBindingKind(SCS1, SCS2))
3638 return ImplicitConversionSequence::Better;
3639 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3640 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641
Sebastian Redlb28b4072009-03-22 23:49:27 +00003642 // C++ [over.ics.rank]p3b4:
3643 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3644 // which the references refer are the same type except for
3645 // top-level cv-qualifiers, and the type to which the reference
3646 // initialized by S2 refers is more cv-qualified than the type
3647 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003648 QualType T1 = SCS1.getToType(2);
3649 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003650 T1 = S.Context.getCanonicalType(T1);
3651 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003652 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003653 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3654 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003655 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003656 // Objective-C++ ARC: If the references refer to objects with different
3657 // lifetimes, prefer bindings that don't change lifetime.
3658 if (SCS1.ObjCLifetimeConversionBinding !=
3659 SCS2.ObjCLifetimeConversionBinding) {
3660 return SCS1.ObjCLifetimeConversionBinding
3661 ? ImplicitConversionSequence::Worse
3662 : ImplicitConversionSequence::Better;
3663 }
3664
Chandler Carruth8e543b32010-12-12 08:17:55 +00003665 // If the type is an array type, promote the element qualifiers to the
3666 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003667 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003668 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003669 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003670 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003671 if (T2.isMoreQualifiedThan(T1))
3672 return ImplicitConversionSequence::Better;
3673 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003674 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003675 }
3676 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003677
Francois Pichet08d2fa02011-09-18 21:37:37 +00003678 // In Microsoft mode, prefer an integral conversion to a
3679 // floating-to-integral conversion if the integral conversion
3680 // is between types of the same size.
3681 // For example:
3682 // void f(float);
3683 // void f(int);
3684 // int main {
3685 // long a;
3686 // f(a);
3687 // }
3688 // Here, MSVC will call f(int) instead of generating a compile error
3689 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003690 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3691 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003692 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003693 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003694 return ImplicitConversionSequence::Better;
3695
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696 return ImplicitConversionSequence::Indistinguishable;
3697}
3698
3699/// CompareQualificationConversions - Compares two standard conversion
3700/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003701/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003702static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003703CompareQualificationConversions(Sema &S,
3704 const StandardConversionSequence& SCS1,
3705 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003706 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003707 // -- S1 and S2 differ only in their qualification conversion and
3708 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3709 // cv-qualification signature of type T1 is a proper subset of
3710 // the cv-qualification signature of type T2, and S1 is not the
3711 // deprecated string literal array-to-pointer conversion (4.2).
3712 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3713 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3714 return ImplicitConversionSequence::Indistinguishable;
3715
3716 // FIXME: the example in the standard doesn't use a qualification
3717 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003718 QualType T1 = SCS1.getToType(2);
3719 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003720 T1 = S.Context.getCanonicalType(T1);
3721 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003722 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003723 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3724 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003725
3726 // If the types are the same, we won't learn anything by unwrapped
3727 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003728 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 return ImplicitConversionSequence::Indistinguishable;
3730
Chandler Carruth607f38e2009-12-29 07:16:59 +00003731 // If the type is an array type, promote the element qualifiers to the type
3732 // for comparison.
3733 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003734 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003735 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003736 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003737
Mike Stump11289f42009-09-09 15:08:12 +00003738 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003739 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003740
3741 // Objective-C++ ARC:
3742 // Prefer qualification conversions not involving a change in lifetime
3743 // to qualification conversions that do not change lifetime.
3744 if (SCS1.QualificationIncludesObjCLifetime !=
3745 SCS2.QualificationIncludesObjCLifetime) {
3746 Result = SCS1.QualificationIncludesObjCLifetime
3747 ? ImplicitConversionSequence::Worse
3748 : ImplicitConversionSequence::Better;
3749 }
3750
John McCall5c32be02010-08-24 20:38:10 +00003751 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003752 // Within each iteration of the loop, we check the qualifiers to
3753 // determine if this still looks like a qualification
3754 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003755 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003756 // until there are no more pointers or pointers-to-members left
3757 // to unwrap. This essentially mimics what
3758 // IsQualificationConversion does, but here we're checking for a
3759 // strict subset of qualifiers.
3760 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3761 // The qualifiers are the same, so this doesn't tell us anything
3762 // about how the sequences rank.
3763 ;
3764 else if (T2.isMoreQualifiedThan(T1)) {
3765 // T1 has fewer qualifiers, so it could be the better sequence.
3766 if (Result == ImplicitConversionSequence::Worse)
3767 // Neither has qualifiers that are a subset of the other's
3768 // qualifiers.
3769 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003770
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003771 Result = ImplicitConversionSequence::Better;
3772 } else if (T1.isMoreQualifiedThan(T2)) {
3773 // T2 has fewer qualifiers, so it could be the better sequence.
3774 if (Result == ImplicitConversionSequence::Better)
3775 // Neither has qualifiers that are a subset of the other's
3776 // qualifiers.
3777 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003778
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003779 Result = ImplicitConversionSequence::Worse;
3780 } else {
3781 // Qualifiers are disjoint.
3782 return ImplicitConversionSequence::Indistinguishable;
3783 }
3784
3785 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003786 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003787 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003788 }
3789
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003790 // Check that the winning standard conversion sequence isn't using
3791 // the deprecated string literal array to pointer conversion.
3792 switch (Result) {
3793 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003794 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003795 Result = ImplicitConversionSequence::Indistinguishable;
3796 break;
3797
3798 case ImplicitConversionSequence::Indistinguishable:
3799 break;
3800
3801 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003802 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003803 Result = ImplicitConversionSequence::Indistinguishable;
3804 break;
3805 }
3806
3807 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003808}
3809
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810/// CompareDerivedToBaseConversions - Compares two standard conversion
3811/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003812/// various kinds of derived-to-base conversions (C++
3813/// [over.ics.rank]p4b3). As part of these checks, we also look at
3814/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003815static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003816CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003817 const StandardConversionSequence& SCS1,
3818 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003819 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003820 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003821 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003822 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003823
3824 // Adjust the types we're converting from via the array-to-pointer
3825 // conversion, if we need to.
3826 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003827 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003828 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003829 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003830
3831 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003832 FromType1 = S.Context.getCanonicalType(FromType1);
3833 ToType1 = S.Context.getCanonicalType(ToType1);
3834 FromType2 = S.Context.getCanonicalType(FromType2);
3835 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003836
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003837 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003838 //
3839 // If class B is derived directly or indirectly from class A and
3840 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003841 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003843 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003844 SCS2.Second == ICK_Pointer_Conversion &&
3845 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3846 FromType1->isPointerType() && FromType2->isPointerType() &&
3847 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003848 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003849 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003850 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003851 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003852 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003853 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003854 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003855 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003856
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003857 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003858 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003859 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003860 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003861 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003862 return ImplicitConversionSequence::Worse;
3863 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003864
3865 // -- conversion of B* to A* is better than conversion of C* to A*,
3866 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003867 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003868 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003869 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003870 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003871 }
3872 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3873 SCS2.Second == ICK_Pointer_Conversion) {
3874 const ObjCObjectPointerType *FromPtr1
3875 = FromType1->getAs<ObjCObjectPointerType>();
3876 const ObjCObjectPointerType *FromPtr2
3877 = FromType2->getAs<ObjCObjectPointerType>();
3878 const ObjCObjectPointerType *ToPtr1
3879 = ToType1->getAs<ObjCObjectPointerType>();
3880 const ObjCObjectPointerType *ToPtr2
3881 = ToType2->getAs<ObjCObjectPointerType>();
3882
3883 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3884 // Apply the same conversion ranking rules for Objective-C pointer types
3885 // that we do for C++ pointers to class types. However, we employ the
3886 // Objective-C pseudo-subtyping relationship used for assignment of
3887 // Objective-C pointer types.
3888 bool FromAssignLeft
3889 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3890 bool FromAssignRight
3891 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3892 bool ToAssignLeft
3893 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3894 bool ToAssignRight
3895 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3896
3897 // A conversion to an a non-id object pointer type or qualified 'id'
3898 // type is better than a conversion to 'id'.
3899 if (ToPtr1->isObjCIdType() &&
3900 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3901 return ImplicitConversionSequence::Worse;
3902 if (ToPtr2->isObjCIdType() &&
3903 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3904 return ImplicitConversionSequence::Better;
3905
3906 // A conversion to a non-id object pointer type is better than a
3907 // conversion to a qualified 'id' type
3908 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3909 return ImplicitConversionSequence::Worse;
3910 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3911 return ImplicitConversionSequence::Better;
3912
3913 // A conversion to an a non-Class object pointer type or qualified 'Class'
3914 // type is better than a conversion to 'Class'.
3915 if (ToPtr1->isObjCClassType() &&
3916 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3917 return ImplicitConversionSequence::Worse;
3918 if (ToPtr2->isObjCClassType() &&
3919 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3920 return ImplicitConversionSequence::Better;
3921
3922 // A conversion to a non-Class object pointer type is better than a
3923 // conversion to a qualified 'Class' type.
3924 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3925 return ImplicitConversionSequence::Worse;
3926 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3927 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003928
Douglas Gregor058d3de2011-01-31 18:51:41 +00003929 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3930 if (S.Context.hasSameType(FromType1, FromType2) &&
3931 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3932 (ToAssignLeft != ToAssignRight))
3933 return ToAssignLeft? ImplicitConversionSequence::Worse
3934 : ImplicitConversionSequence::Better;
3935
3936 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3937 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3938 (FromAssignLeft != FromAssignRight))
3939 return FromAssignLeft? ImplicitConversionSequence::Better
3940 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003941 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003942 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003943
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003944 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003945 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3946 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3947 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003949 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003951 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003953 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003955 ToType2->getAs<MemberPointerType>();
3956 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3957 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3958 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3959 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3960 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3961 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3962 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3963 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003964 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003965 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003966 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003967 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00003968 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003969 return ImplicitConversionSequence::Better;
3970 }
3971 // conversion of B::* to C::* is better than conversion of A::* to C::*
3972 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003973 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003974 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003975 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003976 return ImplicitConversionSequence::Worse;
3977 }
3978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979
Douglas Gregor5ab11652010-04-17 22:01:05 +00003980 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003981 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003982 // -- binding of an expression of type C to a reference of type
3983 // B& is better than binding an expression of type C to a
3984 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003985 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3986 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003987 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003988 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003989 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003990 return ImplicitConversionSequence::Worse;
3991 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003992
Douglas Gregor2fe98832008-11-03 19:09:14 +00003993 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003994 // -- binding of an expression of type B to a reference of type
3995 // A& is better than binding an expression of type C to a
3996 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003997 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3998 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003999 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004000 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004001 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004002 return ImplicitConversionSequence::Worse;
4003 }
4004 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004005
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 return ImplicitConversionSequence::Indistinguishable;
4007}
4008
Douglas Gregor45bb4832013-03-26 23:36:30 +00004009/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4010/// C++ class.
4011static bool isTypeValid(QualType T) {
4012 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4013 return !Record->isInvalidDecl();
4014
4015 return true;
4016}
4017
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004018/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4019/// determine whether they are reference-related,
4020/// reference-compatible, reference-compatible with added
4021/// qualification, or incompatible, for use in C++ initialization by
4022/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4023/// type, and the first type (T1) is the pointee type of the reference
4024/// type being initialized.
4025Sema::ReferenceCompareResult
4026Sema::CompareReferenceRelationship(SourceLocation Loc,
4027 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004028 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004029 bool &ObjCConversion,
4030 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004031 assert(!OrigT1->isReferenceType() &&
4032 "T1 must be the pointee type of the reference type");
4033 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4034
4035 QualType T1 = Context.getCanonicalType(OrigT1);
4036 QualType T2 = Context.getCanonicalType(OrigT2);
4037 Qualifiers T1Quals, T2Quals;
4038 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4039 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4040
4041 // C++ [dcl.init.ref]p4:
4042 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4043 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4044 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004045 DerivedToBase = false;
4046 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004047 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004048 if (UnqualT1 == UnqualT2) {
4049 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004050 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004051 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004052 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004053 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004054 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4055 UnqualT2->isObjCObjectOrInterfaceType() &&
4056 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4057 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004058 else
4059 return Ref_Incompatible;
4060
4061 // At this point, we know that T1 and T2 are reference-related (at
4062 // least).
4063
4064 // If the type is an array type, promote the element qualifiers to the type
4065 // for comparison.
4066 if (isa<ArrayType>(T1) && T1Quals)
4067 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4068 if (isa<ArrayType>(T2) && T2Quals)
4069 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4070
4071 // C++ [dcl.init.ref]p4:
4072 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4073 // reference-related to T2 and cv1 is the same cv-qualification
4074 // as, or greater cv-qualification than, cv2. For purposes of
4075 // overload resolution, cases for which cv1 is greater
4076 // cv-qualification than cv2 are identified as
4077 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004078 //
4079 // Note that we also require equivalence of Objective-C GC and address-space
4080 // qualifiers when performing these computations, so that e.g., an int in
4081 // address space 1 is not reference-compatible with an int in address
4082 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004083 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4084 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004085 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4086 ObjCLifetimeConversion = true;
4087
John McCall31168b02011-06-15 23:02:42 +00004088 T1Quals.removeObjCLifetime();
4089 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004090 }
4091
Douglas Gregord517d552011-04-28 17:56:11 +00004092 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004093 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004094 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004095 return Ref_Compatible_With_Added_Qualification;
4096 else
4097 return Ref_Related;
4098}
4099
Douglas Gregor836a7e82010-08-11 02:15:33 +00004100/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004101/// with DeclType. Return true if something definite is found.
4102static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004103FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4104 QualType DeclType, SourceLocation DeclLoc,
4105 Expr *Init, QualType T2, bool AllowRvalues,
4106 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004107 assert(T2->isRecordType() && "Can only find conversions of record types.");
4108 CXXRecordDecl *T2RecordDecl
4109 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4110
Richard Smith100b24a2014-04-17 01:52:14 +00004111 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004112 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4113 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004114 NamedDecl *D = *I;
4115 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4116 if (isa<UsingShadowDecl>(D))
4117 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4118
4119 FunctionTemplateDecl *ConvTemplate
4120 = dyn_cast<FunctionTemplateDecl>(D);
4121 CXXConversionDecl *Conv;
4122 if (ConvTemplate)
4123 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4124 else
4125 Conv = cast<CXXConversionDecl>(D);
4126
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004128 // explicit conversions, skip it.
4129 if (!AllowExplicit && Conv->isExplicit())
4130 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
Douglas Gregor836a7e82010-08-11 02:15:33 +00004132 if (AllowRvalues) {
4133 bool DerivedToBase = false;
4134 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004135 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004136
4137 // If we are initializing an rvalue reference, don't permit conversion
4138 // functions that return lvalues.
4139 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4140 const ReferenceType *RefType
4141 = Conv->getConversionType()->getAs<LValueReferenceType>();
4142 if (RefType && !RefType->getPointeeType()->isFunctionType())
4143 continue;
4144 }
4145
Douglas Gregor836a7e82010-08-11 02:15:33 +00004146 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004147 S.CompareReferenceRelationship(
4148 DeclLoc,
4149 Conv->getConversionType().getNonReferenceType()
4150 .getUnqualifiedType(),
4151 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004152 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004153 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004154 continue;
4155 } else {
4156 // If the conversion function doesn't return a reference type,
4157 // it can't be considered for this conversion. An rvalue reference
4158 // is only acceptable if its referencee is a function type.
4159
4160 const ReferenceType *RefType =
4161 Conv->getConversionType()->getAs<ReferenceType>();
4162 if (!RefType ||
4163 (!RefType->isLValueReferenceType() &&
4164 !RefType->getPointeeType()->isFunctionType()))
4165 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167
Douglas Gregor836a7e82010-08-11 02:15:33 +00004168 if (ConvTemplate)
4169 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004170 Init, DeclType, CandidateSet,
4171 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004172 else
4173 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004174 DeclType, CandidateSet,
4175 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004176 }
4177
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004178 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4179
Sebastian Redld92badf2010-06-30 18:13:39 +00004180 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004181 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004182 case OR_Success:
4183 // C++ [over.ics.ref]p1:
4184 //
4185 // [...] If the parameter binds directly to the result of
4186 // applying a conversion function to the argument
4187 // expression, the implicit conversion sequence is a
4188 // user-defined conversion sequence (13.3.3.1.2), with the
4189 // second standard conversion sequence either an identity
4190 // conversion or, if the conversion function returns an
4191 // entity of a type that is a derived class of the parameter
4192 // type, a derived-to-base Conversion.
4193 if (!Best->FinalConversion.DirectBinding)
4194 return false;
4195
4196 ICS.setUserDefined();
4197 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4198 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004199 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004200 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004201 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 ICS.UserDefined.EllipsisConversion = false;
4203 assert(ICS.UserDefined.After.ReferenceBinding &&
4204 ICS.UserDefined.After.DirectBinding &&
4205 "Expected a direct reference binding!");
4206 return true;
4207
4208 case OR_Ambiguous:
4209 ICS.setAmbiguous();
4210 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4211 Cand != CandidateSet.end(); ++Cand)
4212 if (Cand->Viable)
4213 ICS.Ambiguous.addConversion(Cand->Function);
4214 return true;
4215
4216 case OR_No_Viable_Function:
4217 case OR_Deleted:
4218 // There was no suitable conversion, or we found a deleted
4219 // conversion; continue with other checks.
4220 return false;
4221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
David Blaikie8a40f702012-01-17 06:56:22 +00004223 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004224}
4225
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004226/// \brief Compute an implicit conversion sequence for reference
4227/// initialization.
4228static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004229TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004230 SourceLocation DeclLoc,
4231 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004232 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004233 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4234
4235 // Most paths end in a failed conversion.
4236 ImplicitConversionSequence ICS;
4237 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4238
4239 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4240 QualType T2 = Init->getType();
4241
4242 // If the initializer is the address of an overloaded function, try
4243 // to resolve the overloaded function. If all goes well, T2 is the
4244 // type of the resulting function.
4245 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4246 DeclAccessPair Found;
4247 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4248 false, Found))
4249 T2 = Fn->getType();
4250 }
4251
4252 // Compute some basic properties of the types and the initializer.
4253 bool isRValRef = DeclType->isRValueReferenceType();
4254 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004255 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004256 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004258 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004259 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004260 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262
Sebastian Redld92badf2010-06-30 18:13:39 +00004263 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004264 // A reference to type "cv1 T1" is initialized by an expression
4265 // of type "cv2 T2" as follows:
4266
Sebastian Redld92badf2010-06-30 18:13:39 +00004267 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004268 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004269 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4270 // reference-compatible with "cv2 T2," or
4271 //
4272 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4273 if (InitCategory.isLValue() &&
4274 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004275 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004276 // When a parameter of reference type binds directly (8.5.3)
4277 // to an argument expression, the implicit conversion sequence
4278 // is the identity conversion, unless the argument expression
4279 // has a type that is a derived class of the parameter type,
4280 // in which case the implicit conversion sequence is a
4281 // derived-to-base Conversion (13.3.3.1).
4282 ICS.setStandard();
4283 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004284 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4285 : ObjCConversion? ICK_Compatible_Conversion
4286 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004287 ICS.Standard.Third = ICK_Identity;
4288 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4289 ICS.Standard.setToType(0, T2);
4290 ICS.Standard.setToType(1, T1);
4291 ICS.Standard.setToType(2, T1);
4292 ICS.Standard.ReferenceBinding = true;
4293 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004294 ICS.Standard.IsLvalueReference = !isRValRef;
4295 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4296 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004297 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004298 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004299 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004300 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004301
Sebastian Redld92badf2010-06-30 18:13:39 +00004302 // Nothing more to do: the inaccessibility/ambiguity check for
4303 // derived-to-base conversions is suppressed when we're
4304 // computing the implicit conversion sequence (C++
4305 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004306 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004307 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004308
Sebastian Redld92badf2010-06-30 18:13:39 +00004309 // -- has a class type (i.e., T2 is a class type), where T1 is
4310 // not reference-related to T2, and can be implicitly
4311 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4312 // is reference-compatible with "cv3 T3" 92) (this
4313 // conversion is selected by enumerating the applicable
4314 // conversion functions (13.3.1.6) and choosing the best
4315 // one through overload resolution (13.3)),
4316 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004318 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004319 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320 Init, T2, /*AllowRvalues=*/false,
4321 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004322 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004323 }
4324 }
4325
Sebastian Redld92badf2010-06-30 18:13:39 +00004326 // -- Otherwise, the reference shall be an lvalue reference to a
4327 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004328 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004329 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004330 return ICS;
4331
Douglas Gregorf143cd52011-01-24 16:14:37 +00004332 // -- If the initializer expression
4333 //
4334 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004335 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004336 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4337 (InitCategory.isXValue() ||
4338 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4339 (InitCategory.isLValue() && T2->isFunctionType()))) {
4340 ICS.setStandard();
4341 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004343 : ObjCConversion? ICK_Compatible_Conversion
4344 : ICK_Identity;
4345 ICS.Standard.Third = ICK_Identity;
4346 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4347 ICS.Standard.setToType(0, T2);
4348 ICS.Standard.setToType(1, T1);
4349 ICS.Standard.setToType(2, T1);
4350 ICS.Standard.ReferenceBinding = true;
4351 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4352 // binding unless we're binding to a class prvalue.
4353 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4354 // allow the use of rvalue references in C++98/03 for the benefit of
4355 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004357 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004358 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004359 ICS.Standard.IsLvalueReference = !isRValRef;
4360 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004362 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004363 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004364 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004365 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregorf143cd52011-01-24 16:14:37 +00004369 // -- has a class type (i.e., T2 is a class type), where T1 is not
4370 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 // an xvalue, class prvalue, or function lvalue of type
4372 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004373 // "cv3 T3",
4374 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004376 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004378 // class subobject).
4379 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004381 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4382 Init, T2, /*AllowRvalues=*/true,
4383 AllowExplicit)) {
4384 // In the second case, if the reference is an rvalue reference
4385 // and the second standard conversion sequence of the
4386 // user-defined conversion sequence includes an lvalue-to-rvalue
4387 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004389 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4390 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4391
Douglas Gregor95273c32011-01-21 16:36:05 +00004392 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Richard Smith19172c42014-07-14 02:28:44 +00004395 // A temporary of function type cannot be created; don't even try.
4396 if (T1->isFunctionType())
4397 return ICS;
4398
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004399 // -- Otherwise, a temporary of type "cv1 T1" is created and
4400 // initialized from the initializer expression using the
4401 // rules for a non-reference copy initialization (8.5). The
4402 // reference is then bound to the temporary. If T1 is
4403 // reference-related to T2, cv1 must be the same
4404 // cv-qualification as, or greater cv-qualification than,
4405 // cv2; otherwise, the program is ill-formed.
4406 if (RefRelationship == Sema::Ref_Related) {
4407 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4408 // we would be reference-compatible or reference-compatible with
4409 // added qualification. But that wasn't the case, so the reference
4410 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004411 //
4412 // Note that we only want to check address spaces and cvr-qualifiers here.
4413 // ObjC GC and lifetime qualifiers aren't important.
4414 Qualifiers T1Quals = T1.getQualifiers();
4415 Qualifiers T2Quals = T2.getQualifiers();
4416 T1Quals.removeObjCGCAttr();
4417 T1Quals.removeObjCLifetime();
4418 T2Quals.removeObjCGCAttr();
4419 T2Quals.removeObjCLifetime();
4420 if (!T1Quals.compatiblyIncludes(T2Quals))
4421 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004422 }
4423
4424 // If at least one of the types is a class type, the types are not
4425 // related, and we aren't allowed any user conversions, the
4426 // reference binding fails. This case is important for breaking
4427 // recursion, since TryImplicitConversion below will attempt to
4428 // create a temporary through the use of a copy constructor.
4429 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4430 (T1->isRecordType() || T2->isRecordType()))
4431 return ICS;
4432
Douglas Gregorcba72b12011-01-21 05:18:22 +00004433 // If T1 is reference-related to T2 and the reference is an rvalue
4434 // reference, the initializer expression shall not be an lvalue.
4435 if (RefRelationship >= Sema::Ref_Related &&
4436 isRValRef && Init->Classify(S.Context).isLValue())
4437 return ICS;
4438
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004439 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004440 // When a parameter of reference type is not bound directly to
4441 // an argument expression, the conversion sequence is the one
4442 // required to convert the argument expression to the
4443 // underlying type of the reference according to
4444 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4445 // to copy-initializing a temporary of the underlying type with
4446 // the argument expression. Any difference in top-level
4447 // cv-qualification is subsumed by the initialization itself
4448 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004449 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4450 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004451 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004452 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004453 /*AllowObjCWritebackConversion=*/false,
4454 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004455
4456 // Of course, that's still a reference binding.
4457 if (ICS.isStandard()) {
4458 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004459 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004460 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004461 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004462 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004463 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004464 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004465 const ReferenceType *LValRefType =
4466 ICS.UserDefined.ConversionFunction->getReturnType()
4467 ->getAs<LValueReferenceType>();
4468
4469 // C++ [over.ics.ref]p3:
4470 // Except for an implicit object parameter, for which see 13.3.1, a
4471 // standard conversion sequence cannot be formed if it requires [...]
4472 // binding an rvalue reference to an lvalue other than a function
4473 // lvalue.
4474 // Note that the function case is not possible here.
4475 if (DeclType->isRValueReferenceType() && LValRefType) {
4476 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4477 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4478 // reference to an rvalue!
4479 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4480 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004481 }
Richard Smith19172c42014-07-14 02:28:44 +00004482
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004483 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004484 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004485 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004486 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4487 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004488 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4489 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004490 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004491
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004492 return ICS;
4493}
4494
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004495static ImplicitConversionSequence
4496TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4497 bool SuppressUserConversions,
4498 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004499 bool AllowObjCWritebackConversion,
4500 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004501
4502/// TryListConversion - Try to copy-initialize a value of type ToType from the
4503/// initializer list From.
4504static ImplicitConversionSequence
4505TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4506 bool SuppressUserConversions,
4507 bool InOverloadResolution,
4508 bool AllowObjCWritebackConversion) {
4509 // C++11 [over.ics.list]p1:
4510 // When an argument is an initializer list, it is not an expression and
4511 // special rules apply for converting it to a parameter type.
4512
4513 ImplicitConversionSequence Result;
4514 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4515
Sebastian Redl09edce02012-01-23 22:09:39 +00004516 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004517 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004518 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004519 return Result;
4520
Larisse Voufo19d08672015-01-27 18:47:05 +00004521 // Per DR1467:
4522 // If the parameter type is a class X and the initializer list has a single
4523 // element of type cv U, where U is X or a class derived from X, the
4524 // implicit conversion sequence is the one required to convert the element
4525 // to the parameter type.
4526 //
4527 // Otherwise, if the parameter type is a character array [... ]
4528 // and the initializer list has a single element that is an
4529 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4530 // implicit conversion sequence is the identity conversion.
4531 if (From->getNumInits() == 1) {
4532 if (ToType->isRecordType()) {
4533 QualType InitType = From->getInit(0)->getType();
4534 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004535 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004536 return TryCopyInitialization(S, From->getInit(0), ToType,
4537 SuppressUserConversions,
4538 InOverloadResolution,
4539 AllowObjCWritebackConversion);
4540 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004541 // FIXME: Check the other conditions here: array of character type,
4542 // initializer is a string literal.
4543 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004544 InitializedEntity Entity =
4545 InitializedEntity::InitializeParameter(S.Context, ToType,
4546 /*Consumed=*/false);
4547 if (S.CanPerformCopyInitialization(Entity, From)) {
4548 Result.setStandard();
4549 Result.Standard.setAsIdentityConversion();
4550 Result.Standard.setFromType(ToType);
4551 Result.Standard.setAllToTypes(ToType);
4552 return Result;
4553 }
4554 }
4555 }
4556
4557 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004558 // C++11 [over.ics.list]p2:
4559 // If the parameter type is std::initializer_list<X> or "array of X" and
4560 // all the elements can be implicitly converted to X, the implicit
4561 // conversion sequence is the worst conversion necessary to convert an
4562 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004563 //
4564 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004565 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004566 // list has exactly N elements or if it has fewer than N elements and X is
4567 // default-constructible, and if all the elements of the initializer list
4568 // can be implicitly converted to X, the implicit conversion sequence is
4569 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004570 //
4571 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004572 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004573 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004574 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004575 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004576 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004577 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004578 if (!X.isNull()) {
4579 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4580 Expr *Init = From->getInit(i);
4581 ImplicitConversionSequence ICS =
4582 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4583 InOverloadResolution,
4584 AllowObjCWritebackConversion);
4585 // If a single element isn't convertible, fail.
4586 if (ICS.isBad()) {
4587 Result = ICS;
4588 break;
4589 }
4590 // Otherwise, look for the worst conversion.
4591 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004592 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4593 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004594 ImplicitConversionSequence::Worse)
4595 Result = ICS;
4596 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004597
4598 // For an empty list, we won't have computed any conversion sequence.
4599 // Introduce the identity conversion sequence.
4600 if (From->getNumInits() == 0) {
4601 Result.setStandard();
4602 Result.Standard.setAsIdentityConversion();
4603 Result.Standard.setFromType(ToType);
4604 Result.Standard.setAllToTypes(ToType);
4605 }
4606
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004607 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004608 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004609 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004610
Larisse Voufo19d08672015-01-27 18:47:05 +00004611 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004612 // C++11 [over.ics.list]p3:
4613 // Otherwise, if the parameter is a non-aggregate class X and overload
4614 // resolution chooses a single best constructor [...] the implicit
4615 // conversion sequence is a user-defined conversion sequence. If multiple
4616 // constructors are viable but none is better than the others, the
4617 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004618 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4619 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004620 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4621 /*AllowExplicit=*/false,
4622 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004623 AllowObjCWritebackConversion,
4624 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004625 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004626
Larisse Voufo19d08672015-01-27 18:47:05 +00004627 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004628 // C++11 [over.ics.list]p4:
4629 // Otherwise, if the parameter has an aggregate type which can be
4630 // initialized from the initializer list [...] the implicit conversion
4631 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004632 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004633 // Type is an aggregate, argument is an init list. At this point it comes
4634 // down to checking whether the initialization works.
4635 // FIXME: Find out whether this parameter is consumed or not.
4636 InitializedEntity Entity =
4637 InitializedEntity::InitializeParameter(S.Context, ToType,
4638 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004639 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004640 Result.setUserDefined();
4641 Result.UserDefined.Before.setAsIdentityConversion();
4642 // Initializer lists don't have a type.
4643 Result.UserDefined.Before.setFromType(QualType());
4644 Result.UserDefined.Before.setAllToTypes(QualType());
4645
4646 Result.UserDefined.After.setAsIdentityConversion();
4647 Result.UserDefined.After.setFromType(ToType);
4648 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004649 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004650 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004651 return Result;
4652 }
4653
Larisse Voufo19d08672015-01-27 18:47:05 +00004654 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004655 // C++11 [over.ics.list]p5:
4656 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004657 if (ToType->isReferenceType()) {
4658 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4659 // mention initializer lists in any way. So we go by what list-
4660 // initialization would do and try to extrapolate from that.
4661
4662 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4663
4664 // If the initializer list has a single element that is reference-related
4665 // to the parameter type, we initialize the reference from that.
4666 if (From->getNumInits() == 1) {
4667 Expr *Init = From->getInit(0);
4668
4669 QualType T2 = Init->getType();
4670
4671 // If the initializer is the address of an overloaded function, try
4672 // to resolve the overloaded function. If all goes well, T2 is the
4673 // type of the resulting function.
4674 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4675 DeclAccessPair Found;
4676 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4677 Init, ToType, false, Found))
4678 T2 = Fn->getType();
4679 }
4680
4681 // Compute some basic properties of the types and the initializer.
4682 bool dummy1 = false;
4683 bool dummy2 = false;
4684 bool dummy3 = false;
4685 Sema::ReferenceCompareResult RefRelationship
4686 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4687 dummy2, dummy3);
4688
Richard Smith4d2bbd72013-09-06 01:22:42 +00004689 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004690 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4691 SuppressUserConversions,
4692 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004693 }
Sebastian Redldf888642011-12-03 14:54:30 +00004694 }
4695
4696 // Otherwise, we bind the reference to a temporary created from the
4697 // initializer list.
4698 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4699 InOverloadResolution,
4700 AllowObjCWritebackConversion);
4701 if (Result.isFailure())
4702 return Result;
4703 assert(!Result.isEllipsis() &&
4704 "Sub-initialization cannot result in ellipsis conversion.");
4705
4706 // Can we even bind to a temporary?
4707 if (ToType->isRValueReferenceType() ||
4708 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4709 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4710 Result.UserDefined.After;
4711 SCS.ReferenceBinding = true;
4712 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4713 SCS.BindsToRvalue = true;
4714 SCS.BindsToFunctionLvalue = false;
4715 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4716 SCS.ObjCLifetimeConversionBinding = false;
4717 } else
4718 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4719 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004720 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004721 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004722
Larisse Voufo19d08672015-01-27 18:47:05 +00004723 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004724 // C++11 [over.ics.list]p6:
4725 // Otherwise, if the parameter type is not a class:
4726 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004727 // - if the initializer list has one element that is not itself an
4728 // initializer list, the implicit conversion sequence is the one
4729 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004730 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004731 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004732 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4733 SuppressUserConversions,
4734 InOverloadResolution,
4735 AllowObjCWritebackConversion);
4736 // - if the initializer list has no elements, the implicit conversion
4737 // sequence is the identity conversion.
4738 else if (NumInits == 0) {
4739 Result.setStandard();
4740 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004741 Result.Standard.setFromType(ToType);
4742 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004743 }
4744 return Result;
4745 }
4746
Larisse Voufo19d08672015-01-27 18:47:05 +00004747 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004748 // C++11 [over.ics.list]p7:
4749 // In all cases other than those enumerated above, no conversion is possible
4750 return Result;
4751}
4752
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004753/// TryCopyInitialization - Try to copy-initialize a value of type
4754/// ToType from the expression From. Return the implicit conversion
4755/// sequence required to pass this argument, which may be a bad
4756/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004757/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004758/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004759static ImplicitConversionSequence
4760TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004762 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004763 bool AllowObjCWritebackConversion,
4764 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004765 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4766 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4767 InOverloadResolution,AllowObjCWritebackConversion);
4768
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004769 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004770 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004771 /*FIXME:*/From->getLocStart(),
4772 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004773 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004774
John McCall5c32be02010-08-24 20:38:10 +00004775 return TryImplicitConversion(S, From, ToType,
4776 SuppressUserConversions,
4777 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004778 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004779 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004780 AllowObjCWritebackConversion,
4781 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004782}
4783
Anna Zaks1b068122011-07-28 19:46:48 +00004784static bool TryCopyInitialization(const CanQualType FromQTy,
4785 const CanQualType ToQTy,
4786 Sema &S,
4787 SourceLocation Loc,
4788 ExprValueKind FromVK) {
4789 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4790 ImplicitConversionSequence ICS =
4791 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4792
4793 return !ICS.isBad();
4794}
4795
Douglas Gregor436424c2008-11-18 23:14:02 +00004796/// TryObjectArgumentInitialization - Try to initialize the object
4797/// parameter of the given member function (@c Method) from the
4798/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004799static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004800TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004801 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004802 CXXMethodDecl *Method,
4803 CXXRecordDecl *ActingContext) {
4804 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004805 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4806 // const volatile object.
4807 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4808 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004809 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004810
4811 // Set up the conversion sequence as a "bad" conversion, to allow us
4812 // to exit early.
4813 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004814
4815 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004816 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004817 FromType = PT->getPointeeType();
4818
Douglas Gregor02824322011-01-26 19:30:28 +00004819 // When we had a pointer, it's implicitly dereferenced, so we
4820 // better have an lvalue.
4821 assert(FromClassification.isLValue());
4822 }
4823
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004824 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004825
Douglas Gregor02824322011-01-26 19:30:28 +00004826 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004828 // parameter is
4829 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004830 // - "lvalue reference to cv X" for functions declared without a
4831 // ref-qualifier or with the & ref-qualifier
4832 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004833 // ref-qualifier
4834 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004836 // cv-qualification on the member function declaration.
4837 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004839 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004840 // (C++ [over.match.funcs]p5). We perform a simplified version of
4841 // reference binding here, that allows class rvalues to bind to
4842 // non-constant references.
4843
Douglas Gregor02824322011-01-26 19:30:28 +00004844 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004845 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004847 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004848 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004849 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004850 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004851 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004852 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004853
4854 // Check that we have either the same type or a derived type. It
4855 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004856 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004857 ImplicitConversionKind SecondKind;
4858 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4859 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004860 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004861 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004862 else {
John McCall65eb8792010-02-25 01:37:24 +00004863 ICS.setBad(BadConversionSequence::unrelated_class,
4864 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004865 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004866 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004867
Douglas Gregor02824322011-01-26 19:30:28 +00004868 // Check the ref-qualifier.
4869 switch (Method->getRefQualifier()) {
4870 case RQ_None:
4871 // Do nothing; we don't care about lvalueness or rvalueness.
4872 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Douglas Gregor02824322011-01-26 19:30:28 +00004874 case RQ_LValue:
4875 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4876 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004878 ImplicitParamType);
4879 return ICS;
4880 }
4881 break;
4882
4883 case RQ_RValue:
4884 if (!FromClassification.isRValue()) {
4885 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004887 ImplicitParamType);
4888 return ICS;
4889 }
4890 break;
4891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004892
Douglas Gregor436424c2008-11-18 23:14:02 +00004893 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004894 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004895 ICS.Standard.setAsIdentityConversion();
4896 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004897 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004898 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004899 ICS.Standard.ReferenceBinding = true;
4900 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004902 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004903 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4904 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4905 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004906 return ICS;
4907}
4908
4909/// PerformObjectArgumentInitialization - Perform initialization of
4910/// the implicit object parameter for the given Method with the given
4911/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004912ExprResult
4913Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004915 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004916 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004917 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004918 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004919 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004920
Douglas Gregor02824322011-01-26 19:30:28 +00004921 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004922 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004923 FromRecordType = PT->getPointeeType();
4924 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004925 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004926 } else {
4927 FromRecordType = From->getType();
4928 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004929 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004930 }
4931
John McCall6e9f8f62009-12-03 04:06:58 +00004932 // Note that we always use the true parent context when performing
4933 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004934 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004935 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4936 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004937 if (ICS.isBad()) {
4938 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4939 Qualifiers FromQs = FromRecordType.getQualifiers();
4940 Qualifiers ToQs = DestType.getQualifiers();
4941 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4942 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004943 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004944 diag::err_member_function_call_bad_cvr)
4945 << Method->getDeclName() << FromRecordType << (CVR - 1)
4946 << From->getSourceRange();
4947 Diag(Method->getLocation(), diag::note_previous_decl)
4948 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004949 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004950 }
4951 }
4952
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004953 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004954 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004955 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004956 }
Mike Stump11289f42009-09-09 15:08:12 +00004957
John Wiegley01296292011-04-08 18:41:53 +00004958 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4959 ExprResult FromRes =
4960 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4961 if (FromRes.isInvalid())
4962 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004963 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004964 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004965
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004966 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004967 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004968 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004969 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004970}
4971
Douglas Gregor5fb53972009-01-14 15:45:31 +00004972/// TryContextuallyConvertToBool - Attempt to contextually convert the
4973/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004974static ImplicitConversionSequence
4975TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004976 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004977 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004978 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004979 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004980 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004981 /*AllowObjCWritebackConversion=*/false,
4982 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004983}
4984
4985/// PerformContextuallyConvertToBool - Perform a contextual conversion
4986/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004987ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004988 if (checkPlaceholderForOverload(*this, From))
4989 return ExprError();
4990
John McCall5c32be02010-08-24 20:38:10 +00004991 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004992 if (!ICS.isBad())
4993 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994
Fariborz Jahanian76197412009-11-18 18:26:29 +00004995 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004996 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004997 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004998 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004999 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005000}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Richard Smithf8379a02012-01-18 23:55:52 +00005002/// Check that the specified conversion is permitted in a converted constant
5003/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5004/// is acceptable.
5005static bool CheckConvertedConstantConversions(Sema &S,
5006 StandardConversionSequence &SCS) {
5007 // Since we know that the target type is an integral or unscoped enumeration
5008 // type, most conversion kinds are impossible. All possible First and Third
5009 // conversions are fine.
5010 switch (SCS.Second) {
5011 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005012 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005013 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005014 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005015 return true;
5016
5017 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005018 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005019 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5020 // conversion, so we allow it in a converted constant expression.
5021 //
5022 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5023 // a lot of popular code. We should at least add a warning for this
5024 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005025 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5026 SCS.getToType(2)->isBooleanType();
5027
Richard Smith410cc892014-11-26 03:26:53 +00005028 case ICK_Pointer_Conversion:
5029 case ICK_Pointer_Member:
5030 // C++1z: null pointer conversions and null member pointer conversions are
5031 // only permitted if the source type is std::nullptr_t.
5032 return SCS.getFromType()->isNullPtrType();
5033
5034 case ICK_Floating_Promotion:
5035 case ICK_Complex_Promotion:
5036 case ICK_Floating_Conversion:
5037 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005038 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005039 case ICK_Compatible_Conversion:
5040 case ICK_Derived_To_Base:
5041 case ICK_Vector_Conversion:
5042 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005043 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005044 case ICK_Block_Pointer_Conversion:
5045 case ICK_TransparentUnionConversion:
5046 case ICK_Writeback_Conversion:
5047 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005048 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005049 return false;
5050
5051 case ICK_Lvalue_To_Rvalue:
5052 case ICK_Array_To_Pointer:
5053 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005054 llvm_unreachable("found a first conversion kind in Second");
5055
Richard Smithf8379a02012-01-18 23:55:52 +00005056 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005057 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005058
5059 case ICK_Num_Conversion_Kinds:
5060 break;
5061 }
5062
5063 llvm_unreachable("unknown conversion kind");
5064}
5065
5066/// CheckConvertedConstantExpression - Check that the expression From is a
5067/// converted constant expression of type T, perform the conversion and produce
5068/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005069static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5070 QualType T, APValue &Value,
5071 Sema::CCEKind CCE,
5072 bool RequireInt) {
5073 assert(S.getLangOpts().CPlusPlus11 &&
5074 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005075
Richard Smith410cc892014-11-26 03:26:53 +00005076 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005077 return ExprError();
5078
Richard Smith410cc892014-11-26 03:26:53 +00005079 // C++1z [expr.const]p3:
5080 // A converted constant expression of type T is an expression,
5081 // implicitly converted to type T, where the converted
5082 // expression is a constant expression and the implicit conversion
5083 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005084 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005085 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005086 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005087 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005088 /*AllowObjcWritebackConversion=*/false,
5089 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005090 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005091 switch (ICS.getKind()) {
5092 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005093 SCS = &ICS.Standard;
5094 break;
5095 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005096 // We are converting to a non-class type, so the Before sequence
5097 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005098 SCS = &ICS.UserDefined.After;
5099 break;
5100 case ImplicitConversionSequence::AmbiguousConversion:
5101 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005102 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5103 return S.Diag(From->getLocStart(),
5104 diag::err_typecheck_converted_constant_expression)
5105 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005106 return ExprError();
5107
5108 case ImplicitConversionSequence::EllipsisConversion:
5109 llvm_unreachable("ellipsis conversion in converted constant expression");
5110 }
5111
Richard Smith410cc892014-11-26 03:26:53 +00005112 // Check that we would only use permitted conversions.
5113 if (!CheckConvertedConstantConversions(S, *SCS)) {
5114 return S.Diag(From->getLocStart(),
5115 diag::err_typecheck_converted_constant_expression_disallowed)
5116 << From->getType() << From->getSourceRange() << T;
5117 }
5118 // [...] and where the reference binding (if any) binds directly.
5119 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5120 return S.Diag(From->getLocStart(),
5121 diag::err_typecheck_converted_constant_expression_indirect)
5122 << From->getType() << From->getSourceRange() << T;
5123 }
5124
5125 ExprResult Result =
5126 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005127 if (Result.isInvalid())
5128 return Result;
5129
5130 // Check for a narrowing implicit conversion.
5131 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005132 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005133 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005134 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005135 case NK_Variable_Narrowing:
5136 // Implicit conversion to a narrower type, and the value is not a constant
5137 // expression. We'll diagnose this in a moment.
5138 case NK_Not_Narrowing:
5139 break;
5140
5141 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005142 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005143 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005144 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005145 break;
5146
5147 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005148 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005149 << CCE << /*Constant*/0 << From->getType() << T;
5150 break;
5151 }
5152
5153 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005154 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005155 Expr::EvalResult Eval;
5156 Eval.Diag = &Notes;
5157
Richard Smith410cc892014-11-26 03:26:53 +00005158 if ((T->isReferenceType()
5159 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5160 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5161 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005162 // The expression can't be folded, so we can't keep it at this position in
5163 // the AST.
5164 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005165 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005166 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005167
5168 if (Notes.empty()) {
5169 // It's a constant expression.
5170 return Result;
5171 }
Richard Smithf8379a02012-01-18 23:55:52 +00005172 }
5173
5174 // It's not a constant expression. Produce an appropriate diagnostic.
5175 if (Notes.size() == 1 &&
5176 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005177 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005178 else {
Richard Smith410cc892014-11-26 03:26:53 +00005179 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005180 << CCE << From->getSourceRange();
5181 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005182 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005183 }
Richard Smith410cc892014-11-26 03:26:53 +00005184 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005185}
5186
Richard Smith410cc892014-11-26 03:26:53 +00005187ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5188 APValue &Value, CCEKind CCE) {
5189 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5190}
5191
5192ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5193 llvm::APSInt &Value,
5194 CCEKind CCE) {
5195 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5196
5197 APValue V;
5198 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5199 if (!R.isInvalid())
5200 Value = V.getInt();
5201 return R;
5202}
5203
5204
John McCallfec112d2011-09-09 06:11:02 +00005205/// dropPointerConversions - If the given standard conversion sequence
5206/// involves any pointer conversions, remove them. This may change
5207/// the result type of the conversion sequence.
5208static void dropPointerConversion(StandardConversionSequence &SCS) {
5209 if (SCS.Second == ICK_Pointer_Conversion) {
5210 SCS.Second = ICK_Identity;
5211 SCS.Third = ICK_Identity;
5212 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5213 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005214}
John McCall5c32be02010-08-24 20:38:10 +00005215
John McCallfec112d2011-09-09 06:11:02 +00005216/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5217/// convert the expression From to an Objective-C pointer type.
5218static ImplicitConversionSequence
5219TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5220 // Do an implicit conversion to 'id'.
5221 QualType Ty = S.Context.getObjCIdType();
5222 ImplicitConversionSequence ICS
5223 = TryImplicitConversion(S, From, Ty,
5224 // FIXME: Are these flags correct?
5225 /*SuppressUserConversions=*/false,
5226 /*AllowExplicit=*/true,
5227 /*InOverloadResolution=*/false,
5228 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005229 /*AllowObjCWritebackConversion=*/false,
5230 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005231
5232 // Strip off any final conversions to 'id'.
5233 switch (ICS.getKind()) {
5234 case ImplicitConversionSequence::BadConversion:
5235 case ImplicitConversionSequence::AmbiguousConversion:
5236 case ImplicitConversionSequence::EllipsisConversion:
5237 break;
5238
5239 case ImplicitConversionSequence::UserDefinedConversion:
5240 dropPointerConversion(ICS.UserDefined.After);
5241 break;
5242
5243 case ImplicitConversionSequence::StandardConversion:
5244 dropPointerConversion(ICS.Standard);
5245 break;
5246 }
5247
5248 return ICS;
5249}
5250
5251/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5252/// conversion of the expression From to an Objective-C pointer type.
5253ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005254 if (checkPlaceholderForOverload(*this, From))
5255 return ExprError();
5256
John McCall8b07ec22010-05-15 11:32:37 +00005257 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005258 ImplicitConversionSequence ICS =
5259 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005260 if (!ICS.isBad())
5261 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005262 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005263}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005264
Richard Smith8dd34252012-02-04 07:07:42 +00005265/// Determine whether the provided type is an integral type, or an enumeration
5266/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005267bool Sema::ICEConvertDiagnoser::match(QualType T) {
5268 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5269 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005270}
5271
Larisse Voufo236bec22013-06-10 06:50:24 +00005272static ExprResult
5273diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5274 Sema::ContextualImplicitConverter &Converter,
5275 QualType T, UnresolvedSetImpl &ViableConversions) {
5276
5277 if (Converter.Suppress)
5278 return ExprError();
5279
5280 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5281 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5282 CXXConversionDecl *Conv =
5283 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5284 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5285 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5286 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005287 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005288}
5289
5290static bool
5291diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5292 Sema::ContextualImplicitConverter &Converter,
5293 QualType T, bool HadMultipleCandidates,
5294 UnresolvedSetImpl &ExplicitConversions) {
5295 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5296 DeclAccessPair Found = ExplicitConversions[0];
5297 CXXConversionDecl *Conversion =
5298 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5299
5300 // The user probably meant to invoke the given explicit
5301 // conversion; use it.
5302 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5303 std::string TypeStr;
5304 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5305
5306 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5307 << FixItHint::CreateInsertion(From->getLocStart(),
5308 "static_cast<" + TypeStr + ">(")
5309 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005310 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005311 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5312
5313 // If we aren't in a SFINAE context, build a call to the
5314 // explicit conversion function.
5315 if (SemaRef.isSFINAEContext())
5316 return true;
5317
Craig Topperc3ec1492014-05-26 06:22:03 +00005318 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005319 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5320 HadMultipleCandidates);
5321 if (Result.isInvalid())
5322 return true;
5323 // Record usage of conversion in an implicit cast.
5324 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005325 CK_UserDefinedConversion, Result.get(),
5326 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005327 }
5328 return false;
5329}
5330
5331static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5332 Sema::ContextualImplicitConverter &Converter,
5333 QualType T, bool HadMultipleCandidates,
5334 DeclAccessPair &Found) {
5335 CXXConversionDecl *Conversion =
5336 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005337 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005338
5339 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5340 if (!Converter.SuppressConversion) {
5341 if (SemaRef.isSFINAEContext())
5342 return true;
5343
5344 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5345 << From->getSourceRange();
5346 }
5347
5348 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5349 HadMultipleCandidates);
5350 if (Result.isInvalid())
5351 return true;
5352 // Record usage of conversion in an implicit cast.
5353 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005354 CK_UserDefinedConversion, Result.get(),
5355 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005356 return false;
5357}
5358
5359static ExprResult finishContextualImplicitConversion(
5360 Sema &SemaRef, SourceLocation Loc, Expr *From,
5361 Sema::ContextualImplicitConverter &Converter) {
5362 if (!Converter.match(From->getType()) && !Converter.Suppress)
5363 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5364 << From->getSourceRange();
5365
5366 return SemaRef.DefaultLvalueConversion(From);
5367}
5368
5369static void
5370collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5371 UnresolvedSetImpl &ViableConversions,
5372 OverloadCandidateSet &CandidateSet) {
5373 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5374 DeclAccessPair FoundDecl = ViableConversions[I];
5375 NamedDecl *D = FoundDecl.getDecl();
5376 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5377 if (isa<UsingShadowDecl>(D))
5378 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5379
5380 CXXConversionDecl *Conv;
5381 FunctionTemplateDecl *ConvTemplate;
5382 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5383 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5384 else
5385 Conv = cast<CXXConversionDecl>(D);
5386
5387 if (ConvTemplate)
5388 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005389 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5390 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005391 else
5392 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005393 ToType, CandidateSet,
5394 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 }
5396}
5397
Richard Smithccc11812013-05-21 19:05:48 +00005398/// \brief Attempt to convert the given expression to a type which is accepted
5399/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005400///
Richard Smithccc11812013-05-21 19:05:48 +00005401/// This routine will attempt to convert an expression of class type to a
5402/// type accepted by the specified converter. In C++11 and before, the class
5403/// must have a single non-explicit conversion function converting to a matching
5404/// type. In C++1y, there can be multiple such conversion functions, but only
5405/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005406///
Douglas Gregor4799d032010-06-30 00:20:43 +00005407/// \param Loc The source location of the construct that requires the
5408/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005409///
James Dennett18348b62012-06-22 08:52:37 +00005410/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005411///
Richard Smithccc11812013-05-21 19:05:48 +00005412/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005413///
Douglas Gregor4799d032010-06-30 00:20:43 +00005414/// \returns The expression, converted to an integral or enumeration type if
5415/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005416ExprResult Sema::PerformContextualImplicitConversion(
5417 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005418 // We can't perform any more checking for type-dependent expressions.
5419 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005420 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005421
Eli Friedman1da70392012-01-26 00:26:18 +00005422 // Process placeholders immediately.
5423 if (From->hasPlaceholderType()) {
5424 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005425 if (result.isInvalid())
5426 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005427 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005428 }
5429
Richard Smithccc11812013-05-21 19:05:48 +00005430 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005431 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005432 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005433 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005434
5435 // FIXME: Check for missing '()' if T is a function type?
5436
Richard Smithccc11812013-05-21 19:05:48 +00005437 // We can only perform contextual implicit conversions on objects of class
5438 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005439 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005440 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005441 if (!Converter.Suppress)
5442 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005443 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005446 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005447 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005448 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005449 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005450
5451 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5452 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5453
Craig Toppere14c0f82014-03-12 04:55:44 +00005454 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005455 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005456 }
Richard Smithccc11812013-05-21 19:05:48 +00005457 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005458
5459 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005460 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005461
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005462 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005463 UnresolvedSet<4>
5464 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005465 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005466 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005467 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005470 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005471
Larisse Voufo236bec22013-06-10 06:50:24 +00005472 // To check that there is only one target type, in C++1y:
5473 QualType ToType;
5474 bool HasUniqueTargetType = true;
5475
5476 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005477 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005478 NamedDecl *D = (*I)->getUnderlyingDecl();
5479 CXXConversionDecl *Conversion;
5480 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5481 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005482 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005483 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5484 else
5485 continue; // C++11 does not consider conversion operator templates(?).
5486 } else
5487 Conversion = cast<CXXConversionDecl>(D);
5488
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005489 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005490 "Conversion operator templates are considered potentially "
5491 "viable in C++1y");
5492
5493 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5494 if (Converter.match(CurToType) || ConvTemplate) {
5495
5496 if (Conversion->isExplicit()) {
5497 // FIXME: For C++1y, do we need this restriction?
5498 // cf. diagnoseNoViableConversion()
5499 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005500 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005501 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005502 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005503 if (ToType.isNull())
5504 ToType = CurToType.getUnqualifiedType();
5505 else if (HasUniqueTargetType &&
5506 (CurToType.getUnqualifiedType() != ToType))
5507 HasUniqueTargetType = false;
5508 }
5509 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005510 }
Richard Smith8dd34252012-02-04 07:07:42 +00005511 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005514 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005515 // C++1y [conv]p6:
5516 // ... An expression e of class type E appearing in such a context
5517 // is said to be contextually implicitly converted to a specified
5518 // type T and is well-formed if and only if e can be implicitly
5519 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005520 // for conversion functions whose return type is cv T or reference to
5521 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005522 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523
Larisse Voufo236bec22013-06-10 06:50:24 +00005524 // If no unique T is found:
5525 if (ToType.isNull()) {
5526 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5527 HadMultipleCandidates,
5528 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005529 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005530 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Larisse Voufo236bec22013-06-10 06:50:24 +00005533 // If more than one unique Ts are found:
5534 if (!HasUniqueTargetType)
5535 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5536 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005537
Larisse Voufo236bec22013-06-10 06:50:24 +00005538 // If one unique T is found:
5539 // First, build a candidate set from the previously recorded
5540 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005541 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005542 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5543 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Larisse Voufo236bec22013-06-10 06:50:24 +00005545 // Then, perform overload resolution over the candidate set.
5546 OverloadCandidateSet::iterator Best;
5547 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5548 case OR_Success: {
5549 // Apply this conversion.
5550 DeclAccessPair Found =
5551 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5552 if (recordConversion(*this, Loc, From, Converter, T,
5553 HadMultipleCandidates, Found))
5554 return ExprError();
5555 break;
5556 }
5557 case OR_Ambiguous:
5558 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5559 ViableConversions);
5560 case OR_No_Viable_Function:
5561 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5562 HadMultipleCandidates,
5563 ExplicitConversions))
5564 return ExprError();
5565 // fall through 'OR_Deleted' case.
5566 case OR_Deleted:
5567 // We'll complain below about a non-integral condition type.
5568 break;
5569 }
5570 } else {
5571 switch (ViableConversions.size()) {
5572 case 0: {
5573 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5574 HadMultipleCandidates,
5575 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005576 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Larisse Voufo236bec22013-06-10 06:50:24 +00005578 // We'll complain below about a non-integral condition type.
5579 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005580 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005581 case 1: {
5582 // Apply this conversion.
5583 DeclAccessPair Found = ViableConversions[0];
5584 if (recordConversion(*this, Loc, From, Converter, T,
5585 HadMultipleCandidates, Found))
5586 return ExprError();
5587 break;
5588 }
5589 default:
5590 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5591 ViableConversions);
5592 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594
Larisse Voufo236bec22013-06-10 06:50:24 +00005595 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005596}
5597
Richard Smith100b24a2014-04-17 01:52:14 +00005598/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5599/// an acceptable non-member overloaded operator for a call whose
5600/// arguments have types T1 (and, if non-empty, T2). This routine
5601/// implements the check in C++ [over.match.oper]p3b2 concerning
5602/// enumeration types.
5603static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5604 FunctionDecl *Fn,
5605 ArrayRef<Expr *> Args) {
5606 QualType T1 = Args[0]->getType();
5607 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5608
5609 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5610 return true;
5611
5612 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5613 return true;
5614
5615 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5616 if (Proto->getNumParams() < 1)
5617 return false;
5618
5619 if (T1->isEnumeralType()) {
5620 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5621 if (Context.hasSameUnqualifiedType(T1, ArgType))
5622 return true;
5623 }
5624
5625 if (Proto->getNumParams() < 2)
5626 return false;
5627
5628 if (!T2.isNull() && T2->isEnumeralType()) {
5629 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5630 if (Context.hasSameUnqualifiedType(T2, ArgType))
5631 return true;
5632 }
5633
5634 return false;
5635}
5636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005637/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005638/// candidate functions, using the given function call arguments. If
5639/// @p SuppressUserConversions, then don't allow user-defined
5640/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005641///
James Dennett2a4d13c2012-06-15 07:13:21 +00005642/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005643/// based on an incomplete set of function arguments. This feature is used by
5644/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005645void
5646Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005647 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005648 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005649 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005650 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005651 bool PartialOverloading,
5652 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005653 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005654 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005655 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005656 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005657 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005658
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005660 if (!isa<CXXConstructorDecl>(Method)) {
5661 // If we get here, it's because we're calling a member function
5662 // that is named without a member access expression (e.g.,
5663 // "this->f") that was either written explicitly or created
5664 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005665 // function, e.g., X::f(). We use an empty type for the implied
5666 // object argument (C++ [over.call.func]p3), and the acting context
5667 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005668 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005670 Args, CandidateSet, SuppressUserConversions,
5671 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005672 return;
5673 }
5674 // We treat a constructor like a non-member function, since its object
5675 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005676 }
5677
Douglas Gregorff7028a2009-11-13 23:59:09 +00005678 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005679 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005680
Richard Smith100b24a2014-04-17 01:52:14 +00005681 // C++ [over.match.oper]p3:
5682 // if no operand has a class type, only those non-member functions in the
5683 // lookup set that have a first parameter of type T1 or "reference to
5684 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5685 // is a right operand) a second parameter of type T2 or "reference to
5686 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5687 // candidate functions.
5688 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5689 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5690 return;
5691
Richard Smith8b86f2d2013-11-04 01:48:18 +00005692 // C++11 [class.copy]p11: [DR1402]
5693 // A defaulted move constructor that is defined as deleted is ignored by
5694 // overload resolution.
5695 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5696 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5697 Constructor->isMoveConstructor())
5698 return;
5699
Douglas Gregor27381f32009-11-23 12:27:39 +00005700 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005701 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005702
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005703 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005704 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005705 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005706 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005707 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005708 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005709 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005710 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
John McCall578a1f82014-12-14 01:46:53 +00005712 if (Constructor) {
5713 // C++ [class.copy]p3:
5714 // A member function template is never instantiated to perform the copy
5715 // of a class object to an object of its class type.
5716 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005717 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005718 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005719 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5720 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005721 Candidate.Viable = false;
5722 Candidate.FailureKind = ovl_fail_illegal_constructor;
5723 return;
5724 }
5725 }
5726
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005727 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005728
5729 // (C++ 13.3.2p2): A candidate function having fewer than m
5730 // parameters is viable only if it has an ellipsis in its parameter
5731 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005732 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005733 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005734 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005735 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005736 return;
5737 }
5738
5739 // (C++ 13.3.2p2): A candidate function having more than m parameters
5740 // is viable only if the (m+1)st parameter has a default argument
5741 // (8.3.6). For the purposes of overload resolution, the
5742 // parameter list is truncated on the right, so that there are
5743 // exactly m parameters.
5744 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005745 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005746 // Not enough arguments.
5747 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005748 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005749 return;
5750 }
5751
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005752 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005753 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005754 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005755 // Skip the check for callers that are implicit members, because in this
5756 // case we may not yet know what the member's target is; the target is
5757 // inferred for the member automatically, based on the bases and fields of
5758 // the class.
5759 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005760 Candidate.Viable = false;
5761 Candidate.FailureKind = ovl_fail_bad_target;
5762 return;
5763 }
5764
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005765 // Determine the implicit conversion sequences for each of the
5766 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005767 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005768 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005769 // (C++ 13.3.2p3): for F to be a viable function, there shall
5770 // exist for each argument an implicit conversion sequence
5771 // (13.3.3.1) that converts that argument to the corresponding
5772 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005773 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005774 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005775 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005776 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005777 /*InOverloadResolution=*/true,
5778 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005779 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005780 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005781 if (Candidate.Conversions[ArgIdx].isBad()) {
5782 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005783 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005784 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005785 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005786 } else {
5787 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5788 // argument for which there is no corresponding parameter is
5789 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005790 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005791 }
5792 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005793
5794 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5795 Candidate.Viable = false;
5796 Candidate.FailureKind = ovl_fail_enable_if;
5797 Candidate.DeductionFailure.Data = FailedAttr;
5798 return;
5799 }
5800}
5801
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005802ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005803 bool IsInstance) {
5804 SmallVector<ObjCMethodDecl*, 4> Methods;
5805 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5806 return nullptr;
5807
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005808 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5809 bool Match = true;
5810 ObjCMethodDecl *Method = Methods[b];
5811 unsigned NumNamedArgs = Sel.getNumArgs();
5812 // Method might have more arguments than selector indicates. This is due
5813 // to addition of c-style arguments in method.
5814 if (Method->param_size() > NumNamedArgs)
5815 NumNamedArgs = Method->param_size();
5816 if (Args.size() < NumNamedArgs)
5817 continue;
5818
5819 for (unsigned i = 0; i < NumNamedArgs; i++) {
5820 // We can't do any type-checking on a type-dependent argument.
5821 if (Args[i]->isTypeDependent()) {
5822 Match = false;
5823 break;
5824 }
5825
5826 ParmVarDecl *param = Method->parameters()[i];
5827 Expr *argExpr = Args[i];
5828 assert(argExpr && "SelectBestMethod(): missing expression");
5829
5830 // Strip the unbridged-cast placeholder expression off unless it's
5831 // a consumed argument.
5832 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5833 !param->hasAttr<CFConsumedAttr>())
5834 argExpr = stripARCUnbridgedCast(argExpr);
5835
5836 // If the parameter is __unknown_anytype, move on to the next method.
5837 if (param->getType() == Context.UnknownAnyTy) {
5838 Match = false;
5839 break;
5840 }
George Burgess IV45461812015-10-11 20:13:20 +00005841
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005842 ImplicitConversionSequence ConversionState
5843 = TryCopyInitialization(*this, argExpr, param->getType(),
5844 /*SuppressUserConversions*/false,
5845 /*InOverloadResolution=*/true,
5846 /*AllowObjCWritebackConversion=*/
5847 getLangOpts().ObjCAutoRefCount,
5848 /*AllowExplicit*/false);
5849 if (ConversionState.isBad()) {
5850 Match = false;
5851 break;
5852 }
5853 }
5854 // Promote additional arguments to variadic methods.
5855 if (Match && Method->isVariadic()) {
5856 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5857 if (Args[i]->isTypeDependent()) {
5858 Match = false;
5859 break;
5860 }
5861 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5862 nullptr);
5863 if (Arg.isInvalid()) {
5864 Match = false;
5865 break;
5866 }
5867 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005868 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005869 // Check for extra arguments to non-variadic methods.
5870 if (Args.size() != NumNamedArgs)
5871 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005872 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5873 // Special case when selectors have no argument. In this case, select
5874 // one with the most general result type of 'id'.
5875 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5876 QualType ReturnT = Methods[b]->getReturnType();
5877 if (ReturnT->isObjCIdType())
5878 return Methods[b];
5879 }
5880 }
5881 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005882
5883 if (Match)
5884 return Method;
5885 }
5886 return nullptr;
5887}
5888
George Burgess IV2a6150d2015-10-16 01:17:38 +00005889// specific_attr_iterator iterates over enable_if attributes in reverse, and
5890// enable_if is order-sensitive. As a result, we need to reverse things
5891// sometimes. Size of 4 elements is arbitrary.
5892static SmallVector<EnableIfAttr *, 4>
5893getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5894 SmallVector<EnableIfAttr *, 4> Result;
5895 if (!Function->hasAttrs())
5896 return Result;
5897
5898 const auto &FuncAttrs = Function->getAttrs();
5899 for (Attr *Attr : FuncAttrs)
5900 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5901 Result.push_back(EnableIf);
5902
5903 std::reverse(Result.begin(), Result.end());
5904 return Result;
5905}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005906
5907EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5908 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005909 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5910 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005911 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005912
5913 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005914 SmallVector<Expr *, 16> ConvertedArgs;
5915 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005916 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005917
5918 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005919 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5920 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005921 !cast<CXXMethodDecl>(Function)->isStatic() &&
5922 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005923 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5924 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005925 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005926 Method, Method);
5927 if (R.isInvalid()) {
5928 InitializationFailed = true;
5929 break;
5930 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005931 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005932 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005933 } else {
5934 ExprResult R =
5935 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5936 Context,
5937 Function->getParamDecl(i)),
5938 SourceLocation(),
5939 Args[i]);
5940 if (R.isInvalid()) {
5941 InitializationFailed = true;
5942 break;
5943 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005944 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005945 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005946 }
5947 }
5948
5949 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005950 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005951
Nick Lewyckye283c552015-08-25 22:33:16 +00005952 // Push default arguments if needed.
5953 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5954 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5955 ParmVarDecl *P = Function->getParamDecl(i);
5956 ExprResult R = PerformCopyInitialization(
5957 InitializedEntity::InitializeParameter(Context,
5958 Function->getParamDecl(i)),
5959 SourceLocation(),
5960 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5961 : P->getDefaultArg());
5962 if (R.isInvalid()) {
5963 InitializationFailed = true;
5964 break;
5965 }
5966 ContainsValueDependentExpr |= R.get()->isValueDependent();
5967 ConvertedArgs.push_back(R.get());
5968 }
5969
5970 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005971 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00005972 }
5973
George Burgess IV2a6150d2015-10-16 01:17:38 +00005974 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005975 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005976 if (EIA->getCond()->isValueDependent()) {
5977 // Don't even try now, we'll examine it after instantiation.
5978 continue;
5979 }
5980
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005981 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005982 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5983 if (!ContainsValueDependentExpr)
5984 return EIA;
5985 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005986 return EIA;
5987 }
5988 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005989 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005990}
5991
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005992/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005993/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005994void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005995 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005996 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005997 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005998 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005999 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006000 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006001 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6002 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006003 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006004 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006005 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006006 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006007 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006008 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006009 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006010 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006011 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006012 } else {
John McCalla0296f72010-03-19 07:35:19 +00006013 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006014 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6015 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006016 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006017 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006018 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006019 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006020 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006021 CandidateSet, SuppressUserConversions,
6022 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006023 else
John McCalla0296f72010-03-19 07:35:19 +00006024 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006025 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006026 CandidateSet, SuppressUserConversions,
6027 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006028 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006029 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006030}
6031
John McCallf0f1cf02009-11-17 07:50:12 +00006032/// AddMethodCandidate - Adds a named decl (which is some kind of
6033/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006034void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006035 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006036 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006037 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006038 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006039 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006040 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006041 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006042
6043 if (isa<UsingShadowDecl>(Decl))
6044 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045
John McCallf0f1cf02009-11-17 07:50:12 +00006046 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6047 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6048 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006049 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006050 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006051 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006052 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006053 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006054 } else {
John McCalla0296f72010-03-19 07:35:19 +00006055 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006056 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006057 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006058 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006059 }
6060}
6061
Douglas Gregor436424c2008-11-18 23:14:02 +00006062/// AddMethodCandidate - Adds the given C++ member function to the set
6063/// of candidate functions, using the given function call arguments
6064/// and the object argument (@c Object). For example, in a call
6065/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6066/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6067/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006068/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006069void
John McCalla0296f72010-03-19 07:35:19 +00006070Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006071 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006072 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006073 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006074 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006075 bool SuppressUserConversions,
6076 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006077 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006078 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006079 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006080 assert(!isa<CXXConstructorDecl>(Method) &&
6081 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006082
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006083 if (!CandidateSet.isNewCandidate(Method))
6084 return;
6085
Richard Smith8b86f2d2013-11-04 01:48:18 +00006086 // C++11 [class.copy]p23: [DR1402]
6087 // A defaulted move assignment operator that is defined as deleted is
6088 // ignored by overload resolution.
6089 if (Method->isDefaulted() && Method->isDeleted() &&
6090 Method->isMoveAssignmentOperator())
6091 return;
6092
Douglas Gregor27381f32009-11-23 12:27:39 +00006093 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006094 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006095
Douglas Gregor436424c2008-11-18 23:14:02 +00006096 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006097 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006098 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006099 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006100 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006101 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006102 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006103
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006104 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006105
6106 // (C++ 13.3.2p2): A candidate function having fewer than m
6107 // parameters is viable only if it has an ellipsis in its parameter
6108 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006109 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6110 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006111 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006112 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006113 return;
6114 }
6115
6116 // (C++ 13.3.2p2): A candidate function having more than m parameters
6117 // is viable only if the (m+1)st parameter has a default argument
6118 // (8.3.6). For the purposes of overload resolution, the
6119 // parameter list is truncated on the right, so that there are
6120 // exactly m parameters.
6121 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006122 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006123 // Not enough arguments.
6124 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006125 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006126 return;
6127 }
6128
6129 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006130
John McCall6e9f8f62009-12-03 04:06:58 +00006131 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006132 // The implicit object argument is ignored.
6133 Candidate.IgnoreObjectArgument = true;
6134 else {
6135 // Determine the implicit conversion sequence for the object
6136 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006137 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6138 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6139 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006140 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006141 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006142 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006143 return;
6144 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006145 }
6146
Eli Bendersky291a57e2014-09-25 23:59:08 +00006147 // (CUDA B.1): Check for invalid calls between targets.
6148 if (getLangOpts().CUDA)
6149 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6150 if (CheckCUDATarget(Caller, Method)) {
6151 Candidate.Viable = false;
6152 Candidate.FailureKind = ovl_fail_bad_target;
6153 return;
6154 }
6155
Douglas Gregor436424c2008-11-18 23:14:02 +00006156 // Determine the implicit conversion sequences for each of the
6157 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006158 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006159 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006160 // (C++ 13.3.2p3): for F to be a viable function, there shall
6161 // exist for each argument an implicit conversion sequence
6162 // (13.3.3.1) that converts that argument to the corresponding
6163 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006164 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006165 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006166 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006167 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006168 /*InOverloadResolution=*/true,
6169 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006170 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006171 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006172 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006173 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006174 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006175 }
6176 } else {
6177 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6178 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006179 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006180 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006181 }
6182 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006183
6184 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6185 Candidate.Viable = false;
6186 Candidate.FailureKind = ovl_fail_enable_if;
6187 Candidate.DeductionFailure.Data = FailedAttr;
6188 return;
6189 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006190}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191
Douglas Gregor97628d62009-08-21 00:16:32 +00006192/// \brief Add a C++ member function template as a candidate to the candidate
6193/// set, using template argument deduction to produce an appropriate member
6194/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006195void
Douglas Gregor97628d62009-08-21 00:16:32 +00006196Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006197 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006198 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006199 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006200 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006201 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006202 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006203 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006204 bool SuppressUserConversions,
6205 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006206 if (!CandidateSet.isNewCandidate(MethodTmpl))
6207 return;
6208
Douglas Gregor97628d62009-08-21 00:16:32 +00006209 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006210 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006211 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006212 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006213 // candidate functions in the usual way.113) A given name can refer to one
6214 // or more function templates and also to a set of overloaded non-template
6215 // functions. In such a case, the candidate functions generated from each
6216 // function template are combined with the set of non-template candidate
6217 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006218 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006219 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006220 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006221 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006222 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006223 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006224 Candidate.FoundDecl = FoundDecl;
6225 Candidate.Function = MethodTmpl->getTemplatedDecl();
6226 Candidate.Viable = false;
6227 Candidate.FailureKind = ovl_fail_bad_deduction;
6228 Candidate.IsSurrogate = false;
6229 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006230 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006231 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006232 Info);
6233 return;
6234 }
Mike Stump11289f42009-09-09 15:08:12 +00006235
Douglas Gregor97628d62009-08-21 00:16:32 +00006236 // Add the function template specialization produced by template argument
6237 // deduction as a candidate.
6238 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006239 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006240 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006241 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006242 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006243 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006244}
6245
Douglas Gregor05155d82009-08-21 23:19:43 +00006246/// \brief Add a C++ function template specialization as a candidate
6247/// in the candidate set, using template argument deduction to produce
6248/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006249void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006250Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006251 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006252 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006253 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006254 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006255 bool SuppressUserConversions,
6256 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006257 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6258 return;
6259
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006260 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006261 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006262 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006263 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006264 // candidate functions in the usual way.113) A given name can refer to one
6265 // or more function templates and also to a set of overloaded non-template
6266 // functions. In such a case, the candidate functions generated from each
6267 // function template are combined with the set of non-template candidate
6268 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006269 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006270 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006271 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006272 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006273 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006274 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006275 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006276 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6277 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006278 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006279 Candidate.IsSurrogate = false;
6280 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006281 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006282 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006283 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006284 return;
6285 }
Mike Stump11289f42009-09-09 15:08:12 +00006286
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006287 // Add the function template specialization produced by template argument
6288 // deduction as a candidate.
6289 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006290 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006291 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006292}
Mike Stump11289f42009-09-09 15:08:12 +00006293
Douglas Gregor4b60a152013-11-07 22:34:54 +00006294/// Determine whether this is an allowable conversion from the result
6295/// of an explicit conversion operator to the expected type, per C++
6296/// [over.match.conv]p1 and [over.match.ref]p1.
6297///
6298/// \param ConvType The return type of the conversion function.
6299///
6300/// \param ToType The type we are converting to.
6301///
6302/// \param AllowObjCPointerConversion Allow a conversion from one
6303/// Objective-C pointer to another.
6304///
6305/// \returns true if the conversion is allowable, false otherwise.
6306static bool isAllowableExplicitConversion(Sema &S,
6307 QualType ConvType, QualType ToType,
6308 bool AllowObjCPointerConversion) {
6309 QualType ToNonRefType = ToType.getNonReferenceType();
6310
6311 // Easy case: the types are the same.
6312 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6313 return true;
6314
6315 // Allow qualification conversions.
6316 bool ObjCLifetimeConversion;
6317 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6318 ObjCLifetimeConversion))
6319 return true;
6320
6321 // If we're not allowed to consider Objective-C pointer conversions,
6322 // we're done.
6323 if (!AllowObjCPointerConversion)
6324 return false;
6325
6326 // Is this an Objective-C pointer conversion?
6327 bool IncompatibleObjC = false;
6328 QualType ConvertedType;
6329 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6330 IncompatibleObjC);
6331}
6332
Douglas Gregora1f013e2008-11-07 22:36:19 +00006333/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006334/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006335/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006336/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006337/// (which may or may not be the same type as the type that the
6338/// conversion function produces).
6339void
6340Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006341 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006342 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006343 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006344 OverloadCandidateSet& CandidateSet,
6345 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006346 assert(!Conversion->getDescribedFunctionTemplate() &&
6347 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006348 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006349 if (!CandidateSet.isNewCandidate(Conversion))
6350 return;
6351
Richard Smith2a7d4812013-05-04 07:00:32 +00006352 // If the conversion function has an undeduced return type, trigger its
6353 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006354 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006355 if (DeduceReturnType(Conversion, From->getExprLoc()))
6356 return;
6357 ConvType = Conversion->getConversionType().getNonReferenceType();
6358 }
6359
Richard Smith089c3162013-09-21 21:55:46 +00006360 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6361 // operator is only a candidate if its return type is the target type or
6362 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006363 if (Conversion->isExplicit() &&
6364 !isAllowableExplicitConversion(*this, ConvType, ToType,
6365 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006366 return;
6367
Douglas Gregor27381f32009-11-23 12:27:39 +00006368 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006369 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006370
Douglas Gregora1f013e2008-11-07 22:36:19 +00006371 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006372 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006373 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006374 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006375 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006376 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006377 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006378 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006379 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006380 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006381 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006382
Douglas Gregor6affc782010-08-19 15:37:02 +00006383 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006384 // For conversion functions, the function is considered to be a member of
6385 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006386 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006387 //
6388 // Determine the implicit conversion sequence for the implicit
6389 // object parameter.
6390 QualType ImplicitParamType = From->getType();
6391 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6392 ImplicitParamType = FromPtrType->getPointeeType();
6393 CXXRecordDecl *ConversionContext
6394 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006395
Richard Smith0f59cb32015-12-18 21:45:41 +00006396 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6397 *this, CandidateSet.getLocation(), From->getType(),
6398 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399
John McCall0d1da222010-01-12 00:44:57 +00006400 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006401 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006402 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006403 return;
6404 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006405
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006406 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006407 // derived to base as such conversions are given Conversion Rank. They only
6408 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6409 QualType FromCanon
6410 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6411 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006412 if (FromCanon == ToCanon ||
6413 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006414 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006415 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006416 return;
6417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006418
Douglas Gregora1f013e2008-11-07 22:36:19 +00006419 // To determine what the conversion from the result of calling the
6420 // conversion function to the type we're eventually trying to
6421 // convert to (ToType), we need to synthesize a call to the
6422 // conversion function and attempt copy initialization from it. This
6423 // makes sure that we get the right semantics with respect to
6424 // lvalues/rvalues and the type. Fortunately, we can allocate this
6425 // call on the stack and we don't need its arguments to be
6426 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006427 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006428 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006429 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6430 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006431 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006432 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006433
Richard Smith48d24642011-07-13 22:53:21 +00006434 QualType ConversionType = Conversion->getConversionType();
6435 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006436 Candidate.Viable = false;
6437 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6438 return;
6439 }
6440
Richard Smith48d24642011-07-13 22:53:21 +00006441 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006442
Mike Stump11289f42009-09-09 15:08:12 +00006443 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006444 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6445 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006446 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006447 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006448 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006449 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006450 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006451 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006452 /*InOverloadResolution=*/false,
6453 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006454
John McCall0d1da222010-01-12 00:44:57 +00006455 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006456 case ImplicitConversionSequence::StandardConversion:
6457 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006459 // C++ [over.ics.user]p3:
6460 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006461 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006462 // shall have exact match rank.
6463 if (Conversion->getPrimaryTemplate() &&
6464 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6465 Candidate.Viable = false;
6466 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006467 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469
Douglas Gregorcba72b12011-01-21 05:18:22 +00006470 // C++0x [dcl.init.ref]p5:
6471 // In the second case, if the reference is an rvalue reference and
6472 // the second standard conversion sequence of the user-defined
6473 // conversion sequence includes an lvalue-to-rvalue conversion, the
6474 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006476 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6477 Candidate.Viable = false;
6478 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006479 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006480 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006481 break;
6482
6483 case ImplicitConversionSequence::BadConversion:
6484 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006485 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006486 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006487
6488 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006489 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006490 "Can only end up with a standard conversion sequence or failure");
6491 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006492
Craig Topper5fc8fc22014-08-27 06:28:36 +00006493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006494 Candidate.Viable = false;
6495 Candidate.FailureKind = ovl_fail_enable_if;
6496 Candidate.DeductionFailure.Data = FailedAttr;
6497 return;
6498 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006499}
6500
Douglas Gregor05155d82009-08-21 23:19:43 +00006501/// \brief Adds a conversion function template specialization
6502/// candidate to the overload set, using template argument deduction
6503/// to deduce the template arguments of the conversion function
6504/// template from the type that we are converting to (C++
6505/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006506void
Douglas Gregor05155d82009-08-21 23:19:43 +00006507Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006508 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006509 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006510 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006511 OverloadCandidateSet &CandidateSet,
6512 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006513 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6514 "Only conversion function templates permitted here");
6515
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006516 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6517 return;
6518
Craig Toppere6706e42012-09-19 02:26:47 +00006519 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006520 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006521 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006522 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006523 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006524 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006525 Candidate.FoundDecl = FoundDecl;
6526 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6527 Candidate.Viable = false;
6528 Candidate.FailureKind = ovl_fail_bad_deduction;
6529 Candidate.IsSurrogate = false;
6530 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006531 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006533 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006534 return;
6535 }
Mike Stump11289f42009-09-09 15:08:12 +00006536
Douglas Gregor05155d82009-08-21 23:19:43 +00006537 // Add the conversion function template specialization produced by
6538 // template argument deduction as a candidate.
6539 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006540 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006541 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006542}
6543
Douglas Gregorab7897a2008-11-19 22:57:39 +00006544/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6545/// converts the given @c Object to a function pointer via the
6546/// conversion function @c Conversion, and then attempts to call it
6547/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6548/// the type of function that we'll eventually be calling.
6549void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006550 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006551 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006552 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006553 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006554 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006555 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006556 if (!CandidateSet.isNewCandidate(Conversion))
6557 return;
6558
Douglas Gregor27381f32009-11-23 12:27:39 +00006559 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006560 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006561
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006562 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006563 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006564 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006565 Candidate.Surrogate = Conversion;
6566 Candidate.Viable = true;
6567 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006568 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006569 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006570
6571 // Determine the implicit conversion sequence for the implicit
6572 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006573 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6574 *this, CandidateSet.getLocation(), Object->getType(),
6575 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006576 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006577 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006578 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006579 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006580 return;
6581 }
6582
6583 // The first conversion is actually a user-defined conversion whose
6584 // first conversion is ObjectInit's standard conversion (which is
6585 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006586 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006587 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006588 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006589 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006590 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006591 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006592 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006593 = Candidate.Conversions[0].UserDefined.Before;
6594 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6595
Mike Stump11289f42009-09-09 15:08:12 +00006596 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006597 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006598
6599 // (C++ 13.3.2p2): A candidate function having fewer than m
6600 // parameters is viable only if it has an ellipsis in its parameter
6601 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006602 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006603 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006604 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006605 return;
6606 }
6607
6608 // Function types don't have any default arguments, so just check if
6609 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006610 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006611 // Not enough arguments.
6612 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006613 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006614 return;
6615 }
6616
6617 // Determine the implicit conversion sequences for each of the
6618 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006619 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006620 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006621 // (C++ 13.3.2p3): for F to be a viable function, there shall
6622 // exist for each argument an implicit conversion sequence
6623 // (13.3.3.1) that converts that argument to the corresponding
6624 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006625 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006626 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006627 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006628 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006629 /*InOverloadResolution=*/false,
6630 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006631 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006632 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006633 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006634 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006635 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006636 }
6637 } else {
6638 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6639 // argument for which there is no corresponding parameter is
6640 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006641 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006642 }
6643 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006644
Craig Topper5fc8fc22014-08-27 06:28:36 +00006645 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006646 Candidate.Viable = false;
6647 Candidate.FailureKind = ovl_fail_enable_if;
6648 Candidate.DeductionFailure.Data = FailedAttr;
6649 return;
6650 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006651}
6652
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006653/// \brief Add overload candidates for overloaded operators that are
6654/// member functions.
6655///
6656/// Add the overloaded operator candidates that are member functions
6657/// for the operator Op that was used in an operator expression such
6658/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6659/// CandidateSet will store the added overload candidates. (C++
6660/// [over.match.oper]).
6661void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6662 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006663 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006664 OverloadCandidateSet& CandidateSet,
6665 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006666 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6667
6668 // C++ [over.match.oper]p3:
6669 // For a unary operator @ with an operand of a type whose
6670 // cv-unqualified version is T1, and for a binary operator @ with
6671 // a left operand of a type whose cv-unqualified version is T1 and
6672 // a right operand of a type whose cv-unqualified version is T2,
6673 // three sets of candidate functions, designated member
6674 // candidates, non-member candidates and built-in candidates, are
6675 // constructed as follows:
6676 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006677
Richard Smith0feaf0c2013-04-20 12:41:22 +00006678 // -- If T1 is a complete class type or a class currently being
6679 // defined, the set of member candidates is the result of the
6680 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6681 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006682 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006683 // Complete the type if it can be completed.
Richard Smith82b8d4e2015-12-18 22:19:11 +00006684 if (RequireCompleteType(OpLoc, T1, 0) && !T1Rec->isBeingDefined())
6685 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006686 // If the type is neither complete nor being defined, bail out now.
6687 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006688 return;
Mike Stump11289f42009-09-09 15:08:12 +00006689
John McCall27b18f82009-11-17 02:14:36 +00006690 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6691 LookupQualifiedName(Operators, T1Rec->getDecl());
6692 Operators.suppressDiagnostics();
6693
Mike Stump11289f42009-09-09 15:08:12 +00006694 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006695 OperEnd = Operators.end();
6696 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006697 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006698 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006699 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006700 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006701 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006702 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006703 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006704}
6705
Douglas Gregora11693b2008-11-12 17:17:38 +00006706/// AddBuiltinCandidate - Add a candidate for a built-in
6707/// operator. ResultTy and ParamTys are the result and parameter types
6708/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006709/// arguments being passed to the candidate. IsAssignmentOperator
6710/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006711/// operator. NumContextualBoolArguments is the number of arguments
6712/// (at the beginning of the argument list) that will be contextually
6713/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006714void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006715 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006716 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006717 bool IsAssignmentOperator,
6718 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006719 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006720 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006721
Douglas Gregora11693b2008-11-12 17:17:38 +00006722 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006723 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006724 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6725 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006726 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006727 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006728 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006729 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006730 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6731
6732 // Determine the implicit conversion sequences for each of the
6733 // arguments.
6734 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006735 Candidate.ExplicitCallArguments = Args.size();
6736 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006737 // C++ [over.match.oper]p4:
6738 // For the built-in assignment operators, conversions of the
6739 // left operand are restricted as follows:
6740 // -- no temporaries are introduced to hold the left operand, and
6741 // -- no user-defined conversions are applied to the left
6742 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006743 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006744 //
6745 // We block these conversions by turning off user-defined
6746 // conversions, since that is the only way that initialization of
6747 // a reference to a non-class type can occur from something that
6748 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006749 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006750 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006751 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006752 Candidate.Conversions[ArgIdx]
6753 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006754 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006755 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006756 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006757 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006758 /*InOverloadResolution=*/false,
6759 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006760 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006761 }
John McCall0d1da222010-01-12 00:44:57 +00006762 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006764 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006765 break;
6766 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006767 }
6768}
6769
Craig Toppercd7b0332013-07-01 06:29:40 +00006770namespace {
6771
Douglas Gregora11693b2008-11-12 17:17:38 +00006772/// BuiltinCandidateTypeSet - A set of types that will be used for the
6773/// candidate operator functions for built-in operators (C++
6774/// [over.built]). The types are separated into pointer types and
6775/// enumeration types.
6776class BuiltinCandidateTypeSet {
6777 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006778 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006779
6780 /// PointerTypes - The set of pointer types that will be used in the
6781 /// built-in candidates.
6782 TypeSet PointerTypes;
6783
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006784 /// MemberPointerTypes - The set of member pointer types that will be
6785 /// used in the built-in candidates.
6786 TypeSet MemberPointerTypes;
6787
Douglas Gregora11693b2008-11-12 17:17:38 +00006788 /// EnumerationTypes - The set of enumeration types that will be
6789 /// used in the built-in candidates.
6790 TypeSet EnumerationTypes;
6791
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006793 /// candidates.
6794 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006795
6796 /// \brief A flag indicating non-record types are viable candidates
6797 bool HasNonRecordTypes;
6798
6799 /// \brief A flag indicating whether either arithmetic or enumeration types
6800 /// were present in the candidate set.
6801 bool HasArithmeticOrEnumeralTypes;
6802
Douglas Gregor80af3132011-05-21 23:15:46 +00006803 /// \brief A flag indicating whether the nullptr type was present in the
6804 /// candidate set.
6805 bool HasNullPtrType;
6806
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006807 /// Sema - The semantic analysis instance where we are building the
6808 /// candidate type set.
6809 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006810
Douglas Gregora11693b2008-11-12 17:17:38 +00006811 /// Context - The AST context in which we will build the type sets.
6812 ASTContext &Context;
6813
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006814 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6815 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006816 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006817
6818public:
6819 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006820 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006821
Mike Stump11289f42009-09-09 15:08:12 +00006822 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006823 : HasNonRecordTypes(false),
6824 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006825 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006826 SemaRef(SemaRef),
6827 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006828
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006829 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006830 SourceLocation Loc,
6831 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006832 bool AllowExplicitConversions,
6833 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006834
6835 /// pointer_begin - First pointer type found;
6836 iterator pointer_begin() { return PointerTypes.begin(); }
6837
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006838 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006839 iterator pointer_end() { return PointerTypes.end(); }
6840
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006841 /// member_pointer_begin - First member pointer type found;
6842 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6843
6844 /// member_pointer_end - Past the last member pointer type found;
6845 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6846
Douglas Gregora11693b2008-11-12 17:17:38 +00006847 /// enumeration_begin - First enumeration type found;
6848 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6849
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006850 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006851 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006853 iterator vector_begin() { return VectorTypes.begin(); }
6854 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006855
6856 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6857 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006858 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006859};
6860
Craig Toppercd7b0332013-07-01 06:29:40 +00006861} // end anonymous namespace
6862
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006863/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006864/// the set of pointer types along with any more-qualified variants of
6865/// that type. For example, if @p Ty is "int const *", this routine
6866/// will add "int const *", "int const volatile *", "int const
6867/// restrict *", and "int const volatile restrict *" to the set of
6868/// pointer types. Returns true if the add of @p Ty itself succeeded,
6869/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006870///
6871/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006872bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006873BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6874 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006875
Douglas Gregora11693b2008-11-12 17:17:38 +00006876 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006877 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006878 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006880 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006881 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006882 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006883 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006884 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6885 PointeeTy = PTy->getPointeeType();
6886 buildObjCPtr = true;
6887 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006888 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006889 }
6890
Sebastian Redl4990a632009-11-18 20:39:26 +00006891 // Don't add qualified variants of arrays. For one, they're not allowed
6892 // (the qualifier would sink to the element type), and for another, the
6893 // only overload situation where it matters is subscript or pointer +- int,
6894 // and those shouldn't have qualifier variants anyway.
6895 if (PointeeTy->isArrayType())
6896 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006897
John McCall8ccfcb52009-09-24 19:53:00 +00006898 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006899 bool hasVolatile = VisibleQuals.hasVolatile();
6900 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
John McCall8ccfcb52009-09-24 19:53:00 +00006902 // Iterate through all strict supersets of BaseCVR.
6903 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6904 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006905 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006906 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006907
6908 // Skip over restrict if no restrict found anywhere in the types, or if
6909 // the type cannot be restrict-qualified.
6910 if ((CVR & Qualifiers::Restrict) &&
6911 (!hasRestrict ||
6912 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6913 continue;
6914
6915 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006916 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006917
6918 // Build qualified pointer type.
6919 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006920 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006921 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006922 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006923 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6924
6925 // Insert qualified pointer type.
6926 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006927 }
6928
6929 return true;
6930}
6931
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006932/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6933/// to the set of pointer types along with any more-qualified variants of
6934/// that type. For example, if @p Ty is "int const *", this routine
6935/// will add "int const *", "int const volatile *", "int const
6936/// restrict *", and "int const volatile restrict *" to the set of
6937/// pointer types. Returns true if the add of @p Ty itself succeeded,
6938/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006939///
6940/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006941bool
6942BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6943 QualType Ty) {
6944 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006945 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006946 return false;
6947
John McCall8ccfcb52009-09-24 19:53:00 +00006948 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6949 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006950
John McCall8ccfcb52009-09-24 19:53:00 +00006951 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006952 // Don't add qualified variants of arrays. For one, they're not allowed
6953 // (the qualifier would sink to the element type), and for another, the
6954 // only overload situation where it matters is subscript or pointer +- int,
6955 // and those shouldn't have qualifier variants anyway.
6956 if (PointeeTy->isArrayType())
6957 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006958 const Type *ClassTy = PointerTy->getClass();
6959
6960 // Iterate through all strict supersets of the pointee type's CVR
6961 // qualifiers.
6962 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6963 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6964 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
John McCall8ccfcb52009-09-24 19:53:00 +00006966 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006967 MemberPointerTypes.insert(
6968 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006969 }
6970
6971 return true;
6972}
6973
Douglas Gregora11693b2008-11-12 17:17:38 +00006974/// AddTypesConvertedFrom - Add each of the types to which the type @p
6975/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006976/// primarily interested in pointer types and enumeration types. We also
6977/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006978/// AllowUserConversions is true if we should look at the conversion
6979/// functions of a class type, and AllowExplicitConversions if we
6980/// should also include the explicit conversion functions of a class
6981/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006982void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006983BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006984 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006985 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006986 bool AllowExplicitConversions,
6987 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006988 // Only deal with canonical types.
6989 Ty = Context.getCanonicalType(Ty);
6990
6991 // Look through reference types; they aren't part of the type of an
6992 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006993 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006994 Ty = RefTy->getPointeeType();
6995
John McCall33ddac02011-01-19 10:06:00 +00006996 // If we're dealing with an array type, decay to the pointer.
6997 if (Ty->isArrayType())
6998 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6999
7000 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007001 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007002
Chandler Carruth00a38332010-12-13 01:44:01 +00007003 // Flag if we ever add a non-record type.
7004 const RecordType *TyRec = Ty->getAs<RecordType>();
7005 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7006
Chandler Carruth00a38332010-12-13 01:44:01 +00007007 // Flag if we encounter an arithmetic type.
7008 HasArithmeticOrEnumeralTypes =
7009 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7010
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007011 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7012 PointerTypes.insert(Ty);
7013 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007014 // Insert our type, and its more-qualified variants, into the set
7015 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007016 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007017 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007018 } else if (Ty->isMemberPointerType()) {
7019 // Member pointers are far easier, since the pointee can't be converted.
7020 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7021 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007022 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007023 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007024 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007025 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007026 // We treat vector types as arithmetic types in many contexts as an
7027 // extension.
7028 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007029 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007030 } else if (Ty->isNullPtrType()) {
7031 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007032 } else if (AllowUserConversions && TyRec) {
7033 // No conversion functions in incomplete types.
7034 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
7035 return;
Mike Stump11289f42009-09-09 15:08:12 +00007036
Chandler Carruth00a38332010-12-13 01:44:01 +00007037 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007038 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007039 if (isa<UsingShadowDecl>(D))
7040 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007041
Chandler Carruth00a38332010-12-13 01:44:01 +00007042 // Skip conversion function templates; they don't tell us anything
7043 // about which builtin types we can convert to.
7044 if (isa<FunctionTemplateDecl>(D))
7045 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007046
Chandler Carruth00a38332010-12-13 01:44:01 +00007047 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7048 if (AllowExplicitConversions || !Conv->isExplicit()) {
7049 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7050 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007051 }
7052 }
7053 }
7054}
7055
Douglas Gregor84605ae2009-08-24 13:43:27 +00007056/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7057/// the volatile- and non-volatile-qualified assignment operators for the
7058/// given type to the candidate set.
7059static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7060 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007061 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007062 OverloadCandidateSet &CandidateSet) {
7063 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007064
Douglas Gregor84605ae2009-08-24 13:43:27 +00007065 // T& operator=(T&, T)
7066 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7067 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007068 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007069 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007070
Douglas Gregor84605ae2009-08-24 13:43:27 +00007071 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7072 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007073 ParamTypes[0]
7074 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007075 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007076 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007077 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007078 }
7079}
Mike Stump11289f42009-09-09 15:08:12 +00007080
Sebastian Redl1054fae2009-10-25 17:03:50 +00007081/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7082/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007083static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7084 Qualifiers VRQuals;
7085 const RecordType *TyRec;
7086 if (const MemberPointerType *RHSMPType =
7087 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007088 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007089 else
7090 TyRec = ArgExpr->getType()->getAs<RecordType>();
7091 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007092 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007093 VRQuals.addVolatile();
7094 VRQuals.addRestrict();
7095 return VRQuals;
7096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007098 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007099 if (!ClassDecl->hasDefinition())
7100 return VRQuals;
7101
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007102 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007103 if (isa<UsingShadowDecl>(D))
7104 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7105 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007106 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7107 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7108 CanTy = ResTypeRef->getPointeeType();
7109 // Need to go down the pointer/mempointer chain and add qualifiers
7110 // as see them.
7111 bool done = false;
7112 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007113 if (CanTy.isRestrictQualified())
7114 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007115 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7116 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007118 CanTy->getAs<MemberPointerType>())
7119 CanTy = ResTypeMPtr->getPointeeType();
7120 else
7121 done = true;
7122 if (CanTy.isVolatileQualified())
7123 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007124 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7125 return VRQuals;
7126 }
7127 }
7128 }
7129 return VRQuals;
7130}
John McCall52872982010-11-13 05:51:15 +00007131
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007132namespace {
John McCall52872982010-11-13 05:51:15 +00007133
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007134/// \brief Helper class to manage the addition of builtin operator overload
7135/// candidates. It provides shared state and utility methods used throughout
7136/// the process, as well as a helper method to add each group of builtin
7137/// operator overloads from the standard to a candidate set.
7138class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007139 // Common instance state available to all overload candidate addition methods.
7140 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007141 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007142 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007143 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007144 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007145 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007146
Chandler Carruthc6586e52010-12-12 10:35:00 +00007147 // Define some constants used to index and iterate over the arithemetic types
7148 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007149 // The "promoted arithmetic types" are the arithmetic
7150 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007151 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007152 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007153 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007154 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007155 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007156 LastPromotedArithmeticType = 11;
7157 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007158
Chandler Carruthc6586e52010-12-12 10:35:00 +00007159 /// \brief Get the canonical type for a given arithmetic type index.
7160 CanQualType getArithmeticType(unsigned index) {
7161 assert(index < NumArithmeticTypes);
7162 static CanQualType ASTContext::* const
7163 ArithmeticTypes[NumArithmeticTypes] = {
7164 // Start of promoted types.
7165 &ASTContext::FloatTy,
7166 &ASTContext::DoubleTy,
7167 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007168
Chandler Carruthc6586e52010-12-12 10:35:00 +00007169 // Start of integral types.
7170 &ASTContext::IntTy,
7171 &ASTContext::LongTy,
7172 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007173 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007174 &ASTContext::UnsignedIntTy,
7175 &ASTContext::UnsignedLongTy,
7176 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007177 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007178 // End of promoted types.
7179
7180 &ASTContext::BoolTy,
7181 &ASTContext::CharTy,
7182 &ASTContext::WCharTy,
7183 &ASTContext::Char16Ty,
7184 &ASTContext::Char32Ty,
7185 &ASTContext::SignedCharTy,
7186 &ASTContext::ShortTy,
7187 &ASTContext::UnsignedCharTy,
7188 &ASTContext::UnsignedShortTy,
7189 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007190 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007191 };
7192 return S.Context.*ArithmeticTypes[index];
7193 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007194
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007195 /// \brief Gets the canonical type resulting from the usual arithemetic
7196 /// converions for the given arithmetic types.
7197 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7198 // Accelerator table for performing the usual arithmetic conversions.
7199 // The rules are basically:
7200 // - if either is floating-point, use the wider floating-point
7201 // - if same signedness, use the higher rank
7202 // - if same size, use unsigned of the higher rank
7203 // - use the larger type
7204 // These rules, together with the axiom that higher ranks are
7205 // never smaller, are sufficient to precompute all of these results
7206 // *except* when dealing with signed types of higher rank.
7207 // (we could precompute SLL x UI for all known platforms, but it's
7208 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007209 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007210 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007211 Dep=-1,
7212 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007213 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007214 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007215 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007216/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7217/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7218/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7219/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7220/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7221/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7222/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7223/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7224/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7225/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7226/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007227 };
7228
7229 assert(L < LastPromotedArithmeticType);
7230 assert(R < LastPromotedArithmeticType);
7231 int Idx = ConversionsTable[L][R];
7232
7233 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007234 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007235
7236 // Slow path: we need to compare widths.
7237 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007238 CanQualType LT = getArithmeticType(L),
7239 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007240 unsigned LW = S.Context.getIntWidth(LT),
7241 RW = S.Context.getIntWidth(RT);
7242
7243 // If they're different widths, use the signed type.
7244 if (LW > RW) return LT;
7245 else if (LW < RW) return RT;
7246
7247 // Otherwise, use the unsigned type of the signed type's rank.
7248 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7249 assert(L == SLL || R == SLL);
7250 return S.Context.UnsignedLongLongTy;
7251 }
7252
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007253 /// \brief Helper method to factor out the common pattern of adding overloads
7254 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007255 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007256 bool HasVolatile,
7257 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007258 QualType ParamTypes[2] = {
7259 S.Context.getLValueReferenceType(CandidateTy),
7260 S.Context.IntTy
7261 };
7262
7263 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007264 if (Args.size() == 1)
7265 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007266 else
Richard Smithe54c3072013-05-05 15:51:06 +00007267 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007268
7269 // Use a heuristic to reduce number of builtin candidates in the set:
7270 // add volatile version only if there are conversions to a volatile type.
7271 if (HasVolatile) {
7272 ParamTypes[0] =
7273 S.Context.getLValueReferenceType(
7274 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007275 if (Args.size() == 1)
7276 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007277 else
Richard Smithe54c3072013-05-05 15:51:06 +00007278 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007279 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007280
7281 // Add restrict version only if there are conversions to a restrict type
7282 // and our candidate type is a non-restrict-qualified pointer.
7283 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7284 !CandidateTy.isRestrictQualified()) {
7285 ParamTypes[0]
7286 = S.Context.getLValueReferenceType(
7287 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007288 if (Args.size() == 1)
7289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007290 else
Richard Smithe54c3072013-05-05 15:51:06 +00007291 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007292
7293 if (HasVolatile) {
7294 ParamTypes[0]
7295 = S.Context.getLValueReferenceType(
7296 S.Context.getCVRQualifiedType(CandidateTy,
7297 (Qualifiers::Volatile |
7298 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007299 if (Args.size() == 1)
7300 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007301 else
Richard Smithe54c3072013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007303 }
7304 }
7305
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 }
7307
7308public:
7309 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007310 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007311 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007312 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007313 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007314 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007315 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007317 HasArithmeticOrEnumeralCandidateType(
7318 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007319 CandidateTypes(CandidateTypes),
7320 CandidateSet(CandidateSet) {
7321 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007322 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007323 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007324 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007325 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007326 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007327 assert(getArithmeticType(FirstPromotedArithmeticType)
7328 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007329 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007330 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007331 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007332 "Invalid last promoted arithmetic type");
7333 }
7334
7335 // C++ [over.built]p3:
7336 //
7337 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7338 // is either volatile or empty, there exist candidate operator
7339 // functions of the form
7340 //
7341 // VQ T& operator++(VQ T&);
7342 // T operator++(VQ T&, int);
7343 //
7344 // C++ [over.built]p4:
7345 //
7346 // For every pair (T, VQ), where T is an arithmetic type other
7347 // than bool, and VQ is either volatile or empty, there exist
7348 // candidate operator functions of the form
7349 //
7350 // VQ T& operator--(VQ T&);
7351 // T operator--(VQ T&, int);
7352 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007353 if (!HasArithmeticOrEnumeralCandidateType)
7354 return;
7355
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7357 Arith < NumArithmeticTypes; ++Arith) {
7358 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007359 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007360 VisibleTypeConversionsQuals.hasVolatile(),
7361 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007362 }
7363 }
7364
7365 // C++ [over.built]p5:
7366 //
7367 // For every pair (T, VQ), where T is a cv-qualified or
7368 // cv-unqualified object type, and VQ is either volatile or
7369 // empty, there exist candidate operator functions of the form
7370 //
7371 // T*VQ& operator++(T*VQ&);
7372 // T*VQ& operator--(T*VQ&);
7373 // T* operator++(T*VQ&, int);
7374 // T* operator--(T*VQ&, int);
7375 void addPlusPlusMinusMinusPointerOverloads() {
7376 for (BuiltinCandidateTypeSet::iterator
7377 Ptr = CandidateTypes[0].pointer_begin(),
7378 PtrEnd = CandidateTypes[0].pointer_end();
7379 Ptr != PtrEnd; ++Ptr) {
7380 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007381 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007382 continue;
7383
7384 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007385 (!(*Ptr).isVolatileQualified() &&
7386 VisibleTypeConversionsQuals.hasVolatile()),
7387 (!(*Ptr).isRestrictQualified() &&
7388 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007389 }
7390 }
7391
7392 // C++ [over.built]p6:
7393 // For every cv-qualified or cv-unqualified object type T, there
7394 // exist candidate operator functions of the form
7395 //
7396 // T& operator*(T*);
7397 //
7398 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007399 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007400 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 // T& operator*(T*);
7402 void addUnaryStarPointerOverloads() {
7403 for (BuiltinCandidateTypeSet::iterator
7404 Ptr = CandidateTypes[0].pointer_begin(),
7405 PtrEnd = CandidateTypes[0].pointer_end();
7406 Ptr != PtrEnd; ++Ptr) {
7407 QualType ParamTy = *Ptr;
7408 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007409 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7410 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007411
Douglas Gregor02824322011-01-26 19:30:28 +00007412 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7413 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7414 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007415
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007417 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007418 }
7419 }
7420
7421 // C++ [over.built]p9:
7422 // For every promoted arithmetic type T, there exist candidate
7423 // operator functions of the form
7424 //
7425 // T operator+(T);
7426 // T operator-(T);
7427 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007428 if (!HasArithmeticOrEnumeralCandidateType)
7429 return;
7430
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007431 for (unsigned Arith = FirstPromotedArithmeticType;
7432 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007433 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007434 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007435 }
7436
7437 // Extension: We also add these operators for vector types.
7438 for (BuiltinCandidateTypeSet::iterator
7439 Vec = CandidateTypes[0].vector_begin(),
7440 VecEnd = CandidateTypes[0].vector_end();
7441 Vec != VecEnd; ++Vec) {
7442 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007443 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007444 }
7445 }
7446
7447 // C++ [over.built]p8:
7448 // For every type T, there exist candidate operator functions of
7449 // the form
7450 //
7451 // T* operator+(T*);
7452 void addUnaryPlusPointerOverloads() {
7453 for (BuiltinCandidateTypeSet::iterator
7454 Ptr = CandidateTypes[0].pointer_begin(),
7455 PtrEnd = CandidateTypes[0].pointer_end();
7456 Ptr != PtrEnd; ++Ptr) {
7457 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007458 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459 }
7460 }
7461
7462 // C++ [over.built]p10:
7463 // For every promoted integral type T, there exist candidate
7464 // operator functions of the form
7465 //
7466 // T operator~(T);
7467 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007468 if (!HasArithmeticOrEnumeralCandidateType)
7469 return;
7470
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007471 for (unsigned Int = FirstPromotedIntegralType;
7472 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007473 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007474 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007475 }
7476
7477 // Extension: We also add this operator for vector types.
7478 for (BuiltinCandidateTypeSet::iterator
7479 Vec = CandidateTypes[0].vector_begin(),
7480 VecEnd = CandidateTypes[0].vector_end();
7481 Vec != VecEnd; ++Vec) {
7482 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007483 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007484 }
7485 }
7486
7487 // C++ [over.match.oper]p16:
7488 // For every pointer to member type T, there exist candidate operator
7489 // functions of the form
7490 //
7491 // bool operator==(T,T);
7492 // bool operator!=(T,T);
7493 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7494 /// Set of (canonical) types that we've already handled.
7495 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7496
Richard Smithe54c3072013-05-05 15:51:06 +00007497 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007498 for (BuiltinCandidateTypeSet::iterator
7499 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7500 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7501 MemPtr != MemPtrEnd;
7502 ++MemPtr) {
7503 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007504 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 continue;
7506
7507 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007508 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007509 }
7510 }
7511 }
7512
7513 // C++ [over.built]p15:
7514 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007515 // For every T, where T is an enumeration type, a pointer type, or
7516 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 //
7518 // bool operator<(T, T);
7519 // bool operator>(T, T);
7520 // bool operator<=(T, T);
7521 // bool operator>=(T, T);
7522 // bool operator==(T, T);
7523 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007524 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007525 // C++ [over.match.oper]p3:
7526 // [...]the built-in candidates include all of the candidate operator
7527 // functions defined in 13.6 that, compared to the given operator, [...]
7528 // do not have the same parameter-type-list as any non-template non-member
7529 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007530 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007531 // Note that in practice, this only affects enumeration types because there
7532 // aren't any built-in candidates of record type, and a user-defined operator
7533 // must have an operand of record or enumeration type. Also, the only other
7534 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007535 // cannot be overloaded for enumeration types, so this is the only place
7536 // where we must suppress candidates like this.
7537 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7538 UserDefinedBinaryOperators;
7539
Richard Smithe54c3072013-05-05 15:51:06 +00007540 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007541 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7542 CandidateTypes[ArgIdx].enumeration_end()) {
7543 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7544 CEnd = CandidateSet.end();
7545 C != CEnd; ++C) {
7546 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7547 continue;
7548
Eli Friedman14f082b2012-09-18 21:52:24 +00007549 if (C->Function->isFunctionTemplateSpecialization())
7550 continue;
7551
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007552 QualType FirstParamType =
7553 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7554 QualType SecondParamType =
7555 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7556
7557 // Skip if either parameter isn't of enumeral type.
7558 if (!FirstParamType->isEnumeralType() ||
7559 !SecondParamType->isEnumeralType())
7560 continue;
7561
7562 // Add this operator to the set of known user-defined operators.
7563 UserDefinedBinaryOperators.insert(
7564 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7565 S.Context.getCanonicalType(SecondParamType)));
7566 }
7567 }
7568 }
7569
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007570 /// Set of (canonical) types that we've already handled.
7571 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7572
Richard Smithe54c3072013-05-05 15:51:06 +00007573 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007574 for (BuiltinCandidateTypeSet::iterator
7575 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7576 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7577 Ptr != PtrEnd; ++Ptr) {
7578 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007579 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580 continue;
7581
7582 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007583 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007584 }
7585 for (BuiltinCandidateTypeSet::iterator
7586 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7587 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7588 Enum != EnumEnd; ++Enum) {
7589 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7590
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007591 // Don't add the same builtin candidate twice, or if a user defined
7592 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007593 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007594 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7595 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007596 continue;
7597
7598 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007599 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007600 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007601
7602 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7603 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007604 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007605 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007606 NullPtrTy))) {
7607 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007608 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007609 CandidateSet);
7610 }
7611 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007612 }
7613 }
7614
7615 // C++ [over.built]p13:
7616 //
7617 // For every cv-qualified or cv-unqualified object type T
7618 // there exist candidate operator functions of the form
7619 //
7620 // T* operator+(T*, ptrdiff_t);
7621 // T& operator[](T*, ptrdiff_t); [BELOW]
7622 // T* operator-(T*, ptrdiff_t);
7623 // T* operator+(ptrdiff_t, T*);
7624 // T& operator[](ptrdiff_t, T*); [BELOW]
7625 //
7626 // C++ [over.built]p14:
7627 //
7628 // For every T, where T is a pointer to object type, there
7629 // exist candidate operator functions of the form
7630 //
7631 // ptrdiff_t operator-(T, T);
7632 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7633 /// Set of (canonical) types that we've already handled.
7634 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7635
7636 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007637 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007638 S.Context.getPointerDiffType(),
7639 S.Context.getPointerDiffType(),
7640 };
7641 for (BuiltinCandidateTypeSet::iterator
7642 Ptr = CandidateTypes[Arg].pointer_begin(),
7643 PtrEnd = CandidateTypes[Arg].pointer_end();
7644 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007645 QualType PointeeTy = (*Ptr)->getPointeeType();
7646 if (!PointeeTy->isObjectType())
7647 continue;
7648
Eric Christopher9207a522015-08-21 16:24:01 +00007649 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 if (Arg == 0 || Op == OO_Plus) {
7651 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7652 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007653 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654 }
7655 if (Op == OO_Minus) {
7656 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007657 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007658 continue;
7659
7660 QualType ParamTypes[2] = { *Ptr, *Ptr };
7661 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007662 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007663 }
7664 }
7665 }
7666 }
7667
7668 // C++ [over.built]p12:
7669 //
7670 // For every pair of promoted arithmetic types L and R, there
7671 // exist candidate operator functions of the form
7672 //
7673 // LR operator*(L, R);
7674 // LR operator/(L, R);
7675 // LR operator+(L, R);
7676 // LR operator-(L, R);
7677 // bool operator<(L, R);
7678 // bool operator>(L, R);
7679 // bool operator<=(L, R);
7680 // bool operator>=(L, R);
7681 // bool operator==(L, R);
7682 // bool operator!=(L, R);
7683 //
7684 // where LR is the result of the usual arithmetic conversions
7685 // between types L and R.
7686 //
7687 // C++ [over.built]p24:
7688 //
7689 // For every pair of promoted arithmetic types L and R, there exist
7690 // candidate operator functions of the form
7691 //
7692 // LR operator?(bool, L, R);
7693 //
7694 // where LR is the result of the usual arithmetic conversions
7695 // between types L and R.
7696 // Our candidates ignore the first parameter.
7697 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007698 if (!HasArithmeticOrEnumeralCandidateType)
7699 return;
7700
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007701 for (unsigned Left = FirstPromotedArithmeticType;
7702 Left < LastPromotedArithmeticType; ++Left) {
7703 for (unsigned Right = FirstPromotedArithmeticType;
7704 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007705 QualType LandR[2] = { getArithmeticType(Left),
7706 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007707 QualType Result =
7708 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007709 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007710 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007711 }
7712 }
7713
7714 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7715 // conditional operator for vector types.
7716 for (BuiltinCandidateTypeSet::iterator
7717 Vec1 = CandidateTypes[0].vector_begin(),
7718 Vec1End = CandidateTypes[0].vector_end();
7719 Vec1 != Vec1End; ++Vec1) {
7720 for (BuiltinCandidateTypeSet::iterator
7721 Vec2 = CandidateTypes[1].vector_begin(),
7722 Vec2End = CandidateTypes[1].vector_end();
7723 Vec2 != Vec2End; ++Vec2) {
7724 QualType LandR[2] = { *Vec1, *Vec2 };
7725 QualType Result = S.Context.BoolTy;
7726 if (!isComparison) {
7727 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7728 Result = *Vec1;
7729 else
7730 Result = *Vec2;
7731 }
7732
Richard Smithe54c3072013-05-05 15:51:06 +00007733 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007734 }
7735 }
7736 }
7737
7738 // C++ [over.built]p17:
7739 //
7740 // For every pair of promoted integral types L and R, there
7741 // exist candidate operator functions of the form
7742 //
7743 // LR operator%(L, R);
7744 // LR operator&(L, R);
7745 // LR operator^(L, R);
7746 // LR operator|(L, R);
7747 // L operator<<(L, R);
7748 // L operator>>(L, R);
7749 //
7750 // where LR is the result of the usual arithmetic conversions
7751 // between types L and R.
7752 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007753 if (!HasArithmeticOrEnumeralCandidateType)
7754 return;
7755
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007756 for (unsigned Left = FirstPromotedIntegralType;
7757 Left < LastPromotedIntegralType; ++Left) {
7758 for (unsigned Right = FirstPromotedIntegralType;
7759 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007760 QualType LandR[2] = { getArithmeticType(Left),
7761 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7763 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007764 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007765 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 }
7767 }
7768 }
7769
7770 // C++ [over.built]p20:
7771 //
7772 // For every pair (T, VQ), where T is an enumeration or
7773 // pointer to member type and VQ is either volatile or
7774 // empty, there exist candidate operator functions of the form
7775 //
7776 // VQ T& operator=(VQ T&, T);
7777 void addAssignmentMemberPointerOrEnumeralOverloads() {
7778 /// Set of (canonical) types that we've already handled.
7779 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7780
7781 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7782 for (BuiltinCandidateTypeSet::iterator
7783 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7784 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7785 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007786 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 continue;
7788
Richard Smithe54c3072013-05-05 15:51:06 +00007789 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 }
7791
7792 for (BuiltinCandidateTypeSet::iterator
7793 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7794 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7795 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007796 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 continue;
7798
Richard Smithe54c3072013-05-05 15:51:06 +00007799 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 }
7801 }
7802 }
7803
7804 // C++ [over.built]p19:
7805 //
7806 // For every pair (T, VQ), where T is any type and VQ is either
7807 // volatile or empty, there exist candidate operator functions
7808 // of the form
7809 //
7810 // T*VQ& operator=(T*VQ&, T*);
7811 //
7812 // C++ [over.built]p21:
7813 //
7814 // For every pair (T, VQ), where T is a cv-qualified or
7815 // cv-unqualified object type and VQ is either volatile or
7816 // empty, there exist candidate operator functions of the form
7817 //
7818 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7819 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7820 void addAssignmentPointerOverloads(bool isEqualOp) {
7821 /// Set of (canonical) types that we've already handled.
7822 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7823
7824 for (BuiltinCandidateTypeSet::iterator
7825 Ptr = CandidateTypes[0].pointer_begin(),
7826 PtrEnd = CandidateTypes[0].pointer_end();
7827 Ptr != PtrEnd; ++Ptr) {
7828 // If this is operator=, keep track of the builtin candidates we added.
7829 if (isEqualOp)
7830 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007831 else if (!(*Ptr)->getPointeeType()->isObjectType())
7832 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833
7834 // non-volatile version
7835 QualType ParamTypes[2] = {
7836 S.Context.getLValueReferenceType(*Ptr),
7837 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7838 };
Richard Smithe54c3072013-05-05 15:51:06 +00007839 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007840 /*IsAssigmentOperator=*/ isEqualOp);
7841
Douglas Gregor5bee2582012-06-04 00:15:09 +00007842 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7843 VisibleTypeConversionsQuals.hasVolatile();
7844 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007845 // volatile version
7846 ParamTypes[0] =
7847 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007848 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007849 /*IsAssigmentOperator=*/isEqualOp);
7850 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007851
7852 if (!(*Ptr).isRestrictQualified() &&
7853 VisibleTypeConversionsQuals.hasRestrict()) {
7854 // restrict version
7855 ParamTypes[0]
7856 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007857 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007858 /*IsAssigmentOperator=*/isEqualOp);
7859
7860 if (NeedVolatile) {
7861 // volatile restrict version
7862 ParamTypes[0]
7863 = S.Context.getLValueReferenceType(
7864 S.Context.getCVRQualifiedType(*Ptr,
7865 (Qualifiers::Volatile |
7866 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007867 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007868 /*IsAssigmentOperator=*/isEqualOp);
7869 }
7870 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 }
7872
7873 if (isEqualOp) {
7874 for (BuiltinCandidateTypeSet::iterator
7875 Ptr = CandidateTypes[1].pointer_begin(),
7876 PtrEnd = CandidateTypes[1].pointer_end();
7877 Ptr != PtrEnd; ++Ptr) {
7878 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007879 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 continue;
7881
Chandler Carruth8e543b32010-12-12 08:17:55 +00007882 QualType ParamTypes[2] = {
7883 S.Context.getLValueReferenceType(*Ptr),
7884 *Ptr,
7885 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007886
7887 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007888 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007889 /*IsAssigmentOperator=*/true);
7890
Douglas Gregor5bee2582012-06-04 00:15:09 +00007891 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7892 VisibleTypeConversionsQuals.hasVolatile();
7893 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007894 // volatile version
7895 ParamTypes[0] =
7896 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007897 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7898 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007900
7901 if (!(*Ptr).isRestrictQualified() &&
7902 VisibleTypeConversionsQuals.hasRestrict()) {
7903 // restrict version
7904 ParamTypes[0]
7905 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7907 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007908
7909 if (NeedVolatile) {
7910 // volatile restrict version
7911 ParamTypes[0]
7912 = S.Context.getLValueReferenceType(
7913 S.Context.getCVRQualifiedType(*Ptr,
7914 (Qualifiers::Volatile |
7915 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007916 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7917 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007918 }
7919 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 }
7921 }
7922 }
7923
7924 // C++ [over.built]p18:
7925 //
7926 // For every triple (L, VQ, R), where L is an arithmetic type,
7927 // VQ is either volatile or empty, and R is a promoted
7928 // arithmetic type, there exist candidate operator functions of
7929 // the form
7930 //
7931 // VQ L& operator=(VQ L&, R);
7932 // VQ L& operator*=(VQ L&, R);
7933 // VQ L& operator/=(VQ L&, R);
7934 // VQ L& operator+=(VQ L&, R);
7935 // VQ L& operator-=(VQ L&, R);
7936 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007937 if (!HasArithmeticOrEnumeralCandidateType)
7938 return;
7939
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007940 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7941 for (unsigned Right = FirstPromotedArithmeticType;
7942 Right < LastPromotedArithmeticType; ++Right) {
7943 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007944 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945
7946 // Add this built-in operator as a candidate (VQ is empty).
7947 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007948 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 /*IsAssigmentOperator=*/isEqualOp);
7951
7952 // Add this built-in operator as a candidate (VQ is 'volatile').
7953 if (VisibleTypeConversionsQuals.hasVolatile()) {
7954 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007955 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007956 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007957 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 /*IsAssigmentOperator=*/isEqualOp);
7959 }
7960 }
7961 }
7962
7963 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7964 for (BuiltinCandidateTypeSet::iterator
7965 Vec1 = CandidateTypes[0].vector_begin(),
7966 Vec1End = CandidateTypes[0].vector_end();
7967 Vec1 != Vec1End; ++Vec1) {
7968 for (BuiltinCandidateTypeSet::iterator
7969 Vec2 = CandidateTypes[1].vector_begin(),
7970 Vec2End = CandidateTypes[1].vector_end();
7971 Vec2 != Vec2End; ++Vec2) {
7972 QualType ParamTypes[2];
7973 ParamTypes[1] = *Vec2;
7974 // Add this built-in operator as a candidate (VQ is empty).
7975 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007976 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 /*IsAssigmentOperator=*/isEqualOp);
7978
7979 // Add this built-in operator as a candidate (VQ is 'volatile').
7980 if (VisibleTypeConversionsQuals.hasVolatile()) {
7981 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7982 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007983 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007984 /*IsAssigmentOperator=*/isEqualOp);
7985 }
7986 }
7987 }
7988 }
7989
7990 // C++ [over.built]p22:
7991 //
7992 // For every triple (L, VQ, R), where L is an integral type, VQ
7993 // is either volatile or empty, and R is a promoted integral
7994 // type, there exist candidate operator functions of the form
7995 //
7996 // VQ L& operator%=(VQ L&, R);
7997 // VQ L& operator<<=(VQ L&, R);
7998 // VQ L& operator>>=(VQ L&, R);
7999 // VQ L& operator&=(VQ L&, R);
8000 // VQ L& operator^=(VQ L&, R);
8001 // VQ L& operator|=(VQ L&, R);
8002 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008003 if (!HasArithmeticOrEnumeralCandidateType)
8004 return;
8005
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008006 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8007 for (unsigned Right = FirstPromotedIntegralType;
8008 Right < LastPromotedIntegralType; ++Right) {
8009 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008010 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008011
8012 // Add this built-in operator as a candidate (VQ is empty).
8013 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008014 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008016 if (VisibleTypeConversionsQuals.hasVolatile()) {
8017 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008018 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008019 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8020 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008021 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022 }
8023 }
8024 }
8025 }
8026
8027 // C++ [over.operator]p23:
8028 //
8029 // There also exist candidate operator functions of the form
8030 //
8031 // bool operator!(bool);
8032 // bool operator&&(bool, bool);
8033 // bool operator||(bool, bool);
8034 void addExclaimOverload() {
8035 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008036 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 /*IsAssignmentOperator=*/false,
8038 /*NumContextualBoolArguments=*/1);
8039 }
8040 void addAmpAmpOrPipePipeOverload() {
8041 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008042 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 /*IsAssignmentOperator=*/false,
8044 /*NumContextualBoolArguments=*/2);
8045 }
8046
8047 // C++ [over.built]p13:
8048 //
8049 // For every cv-qualified or cv-unqualified object type T there
8050 // exist candidate operator functions of the form
8051 //
8052 // T* operator+(T*, ptrdiff_t); [ABOVE]
8053 // T& operator[](T*, ptrdiff_t);
8054 // T* operator-(T*, ptrdiff_t); [ABOVE]
8055 // T* operator+(ptrdiff_t, T*); [ABOVE]
8056 // T& operator[](ptrdiff_t, T*);
8057 void addSubscriptOverloads() {
8058 for (BuiltinCandidateTypeSet::iterator
8059 Ptr = CandidateTypes[0].pointer_begin(),
8060 PtrEnd = CandidateTypes[0].pointer_end();
8061 Ptr != PtrEnd; ++Ptr) {
8062 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8063 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008064 if (!PointeeType->isObjectType())
8065 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008067 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8068
8069 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008070 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008071 }
8072
8073 for (BuiltinCandidateTypeSet::iterator
8074 Ptr = CandidateTypes[1].pointer_begin(),
8075 PtrEnd = CandidateTypes[1].pointer_end();
8076 Ptr != PtrEnd; ++Ptr) {
8077 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8078 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008079 if (!PointeeType->isObjectType())
8080 continue;
8081
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8083
8084 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008085 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 }
8087 }
8088
8089 // C++ [over.built]p11:
8090 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8091 // C1 is the same type as C2 or is a derived class of C2, T is an object
8092 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8093 // there exist candidate operator functions of the form
8094 //
8095 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8096 //
8097 // where CV12 is the union of CV1 and CV2.
8098 void addArrowStarOverloads() {
8099 for (BuiltinCandidateTypeSet::iterator
8100 Ptr = CandidateTypes[0].pointer_begin(),
8101 PtrEnd = CandidateTypes[0].pointer_end();
8102 Ptr != PtrEnd; ++Ptr) {
8103 QualType C1Ty = (*Ptr);
8104 QualType C1;
8105 QualifierCollector Q1;
8106 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8107 if (!isa<RecordType>(C1))
8108 continue;
8109 // heuristic to reduce number of builtin candidates in the set.
8110 // Add volatile/restrict version only if there are conversions to a
8111 // volatile/restrict type.
8112 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8113 continue;
8114 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8115 continue;
8116 for (BuiltinCandidateTypeSet::iterator
8117 MemPtr = CandidateTypes[1].member_pointer_begin(),
8118 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8119 MemPtr != MemPtrEnd; ++MemPtr) {
8120 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8121 QualType C2 = QualType(mptr->getClass(), 0);
8122 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008123 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008124 break;
8125 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8126 // build CV12 T&
8127 QualType T = mptr->getPointeeType();
8128 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8129 T.isVolatileQualified())
8130 continue;
8131 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8132 T.isRestrictQualified())
8133 continue;
8134 T = Q1.apply(S.Context, T);
8135 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008136 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 }
8138 }
8139 }
8140
8141 // Note that we don't consider the first argument, since it has been
8142 // contextually converted to bool long ago. The candidates below are
8143 // therefore added as binary.
8144 //
8145 // C++ [over.built]p25:
8146 // For every type T, where T is a pointer, pointer-to-member, or scoped
8147 // enumeration type, there exist candidate operator functions of the form
8148 //
8149 // T operator?(bool, T, T);
8150 //
8151 void addConditionalOperatorOverloads() {
8152 /// Set of (canonical) types that we've already handled.
8153 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8154
8155 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8156 for (BuiltinCandidateTypeSet::iterator
8157 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8158 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8159 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008160 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008161 continue;
8162
8163 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008164 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008165 }
8166
8167 for (BuiltinCandidateTypeSet::iterator
8168 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8169 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8170 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008171 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008172 continue;
8173
8174 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008175 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008176 }
8177
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008178 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008179 for (BuiltinCandidateTypeSet::iterator
8180 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8181 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8182 Enum != EnumEnd; ++Enum) {
8183 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8184 continue;
8185
David Blaikie82e95a32014-11-19 07:49:47 +00008186 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008187 continue;
8188
8189 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008190 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008191 }
8192 }
8193 }
8194 }
8195};
8196
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008197} // end anonymous namespace
8198
8199/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8200/// operator overloads to the candidate set (C++ [over.built]), based
8201/// on the operator @p Op and the arguments given. For example, if the
8202/// operator is a binary '+', this routine might add "int
8203/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008204void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8205 SourceLocation OpLoc,
8206 ArrayRef<Expr *> Args,
8207 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008208 // Find all of the types that the arguments can convert to, but only
8209 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008210 // that make use of these types. Also record whether we encounter non-record
8211 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008212 Qualifiers VisibleTypeConversionsQuals;
8213 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008214 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008215 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008216
8217 bool HasNonRecordCandidateType = false;
8218 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008219 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008220 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008221 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008222 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8223 OpLoc,
8224 true,
8225 (Op == OO_Exclaim ||
8226 Op == OO_AmpAmp ||
8227 Op == OO_PipePipe),
8228 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008229 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8230 CandidateTypes[ArgIdx].hasNonRecordTypes();
8231 HasArithmeticOrEnumeralCandidateType =
8232 HasArithmeticOrEnumeralCandidateType ||
8233 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008234 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008235
Chandler Carruth00a38332010-12-13 01:44:01 +00008236 // Exit early when no non-record types have been added to the candidate set
8237 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008238 //
8239 // We can't exit early for !, ||, or &&, since there we have always have
8240 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008241 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008242 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008243 return;
8244
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008245 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008246 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008247 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008248 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008249 CandidateTypes, CandidateSet);
8250
8251 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008252 switch (Op) {
8253 case OO_None:
8254 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008255 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008256
Chandler Carruth5184de02010-12-12 08:51:33 +00008257 case OO_New:
8258 case OO_Delete:
8259 case OO_Array_New:
8260 case OO_Array_Delete:
8261 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008262 llvm_unreachable(
8263 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008264
8265 case OO_Comma:
8266 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008267 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008268 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008269 // -- For the operator ',', the unary operator '&', the
8270 // operator '->', or the operator 'co_await', the
8271 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008272 break;
8273
8274 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008275 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008276 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008277 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008278
8279 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008280 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008282 } else {
8283 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8284 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8285 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008286 break;
8287
Chandler Carruth5184de02010-12-12 08:51:33 +00008288 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008289 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008290 OpBuilder.addUnaryStarPointerOverloads();
8291 else
8292 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8293 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008294
Chandler Carruth5184de02010-12-12 08:51:33 +00008295 case OO_Slash:
8296 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008297 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008298
8299 case OO_PlusPlus:
8300 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008301 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8302 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008303 break;
8304
Douglas Gregor84605ae2009-08-24 13:43:27 +00008305 case OO_EqualEqual:
8306 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008308 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008309
Douglas Gregora11693b2008-11-12 17:17:38 +00008310 case OO_Less:
8311 case OO_Greater:
8312 case OO_LessEqual:
8313 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008314 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008315 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8316 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008317
Douglas Gregora11693b2008-11-12 17:17:38 +00008318 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008319 case OO_Caret:
8320 case OO_Pipe:
8321 case OO_LessLess:
8322 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008323 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008324 break;
8325
Chandler Carruth5184de02010-12-12 08:51:33 +00008326 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008327 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008328 // C++ [over.match.oper]p3:
8329 // -- For the operator ',', the unary operator '&', or the
8330 // operator '->', the built-in candidates set is empty.
8331 break;
8332
8333 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8334 break;
8335
8336 case OO_Tilde:
8337 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8338 break;
8339
Douglas Gregora11693b2008-11-12 17:17:38 +00008340 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008341 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008342 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008343
8344 case OO_PlusEqual:
8345 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008347 // Fall through.
8348
8349 case OO_StarEqual:
8350 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008351 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008352 break;
8353
8354 case OO_PercentEqual:
8355 case OO_LessLessEqual:
8356 case OO_GreaterGreaterEqual:
8357 case OO_AmpEqual:
8358 case OO_CaretEqual:
8359 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008360 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008361 break;
8362
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008363 case OO_Exclaim:
8364 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008365 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008366
Douglas Gregora11693b2008-11-12 17:17:38 +00008367 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 case OO_PipePipe:
8369 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008370 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008371
8372 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008373 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008374 break;
8375
8376 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008377 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008378 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008379
8380 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008381 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008382 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8383 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008384 }
8385}
8386
Douglas Gregore254f902009-02-04 00:32:51 +00008387/// \brief Add function candidates found via argument-dependent lookup
8388/// to the set of overloading candidates.
8389///
8390/// This routine performs argument-dependent name lookup based on the
8391/// given function name (which may also be an operator name) and adds
8392/// all of the overload candidates found by ADL to the overload
8393/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008394void
Douglas Gregore254f902009-02-04 00:32:51 +00008395Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008396 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008397 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008398 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008399 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008400 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008401 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008402
John McCall91f61fc2010-01-26 06:04:06 +00008403 // FIXME: This approach for uniquing ADL results (and removing
8404 // redundant candidates from the set) relies on pointer-equality,
8405 // which means we need to key off the canonical decl. However,
8406 // always going back to the canonical decl might not get us the
8407 // right set of default arguments. What default arguments are
8408 // we supposed to consider on ADL candidates, anyway?
8409
Douglas Gregorcabea402009-09-22 15:41:20 +00008410 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008411 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008412
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008413 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008414 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8415 CandEnd = CandidateSet.end();
8416 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008417 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008418 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008419 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008420 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008421 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008422
8423 // For each of the ADL candidates we found, add it to the overload
8424 // set.
John McCall8fe68082010-01-26 07:16:45 +00008425 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008426 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008427 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008428 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008429 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008430
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008431 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8432 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008433 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008434 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008435 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008436 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008437 }
Douglas Gregore254f902009-02-04 00:32:51 +00008438}
8439
George Burgess IV2a6150d2015-10-16 01:17:38 +00008440// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8441// Cand2 for overloading. This function assumes that all of the enable_if attrs
8442// on Cand1 and Cand2 have conditions that evaluate to true.
8443//
8444// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8445// Cand1's first N enable_if attributes have precisely the same conditions as
8446// Cand2's first N enable_if attributes (where N = the number of enable_if
8447// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8448static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8449 const FunctionDecl *Cand2) {
8450
8451 // FIXME: The next several lines are just
8452 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8453 // instead of reverse order which is how they're stored in the AST.
8454 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8455 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8456
8457 // Candidate 1 is better if it has strictly more attributes and
8458 // the common sequence is identical.
8459 if (Cand1Attrs.size() <= Cand2Attrs.size())
8460 return false;
8461
8462 auto Cand1I = Cand1Attrs.begin();
8463 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8464 for (auto &Cand2A : Cand2Attrs) {
8465 Cand1ID.clear();
8466 Cand2ID.clear();
8467
8468 auto &Cand1A = *Cand1I++;
8469 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8470 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8471 if (Cand1ID != Cand2ID)
8472 return false;
8473 }
8474
8475 return true;
8476}
8477
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008478/// isBetterOverloadCandidate - Determines whether the first overload
8479/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008480bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8481 const OverloadCandidate &Cand2,
8482 SourceLocation Loc,
8483 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008484 // Define viable functions to be better candidates than non-viable
8485 // functions.
8486 if (!Cand2.Viable)
8487 return Cand1.Viable;
8488 else if (!Cand1.Viable)
8489 return false;
8490
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008491 // C++ [over.match.best]p1:
8492 //
8493 // -- if F is a static member function, ICS1(F) is defined such
8494 // that ICS1(F) is neither better nor worse than ICS1(G) for
8495 // any function G, and, symmetrically, ICS1(G) is neither
8496 // better nor worse than ICS1(F).
8497 unsigned StartArg = 0;
8498 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8499 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008500
Douglas Gregord3cb3562009-07-07 23:38:56 +00008501 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008502 // A viable function F1 is defined to be a better function than another
8503 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008504 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008505 unsigned NumArgs = Cand1.NumConversions;
8506 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008507 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008508 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008509 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008510 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008511 Cand2.Conversions[ArgIdx])) {
8512 case ImplicitConversionSequence::Better:
8513 // Cand1 has a better conversion sequence.
8514 HasBetterConversion = true;
8515 break;
8516
8517 case ImplicitConversionSequence::Worse:
8518 // Cand1 can't be better than Cand2.
8519 return false;
8520
8521 case ImplicitConversionSequence::Indistinguishable:
8522 // Do nothing.
8523 break;
8524 }
8525 }
8526
Mike Stump11289f42009-09-09 15:08:12 +00008527 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008528 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008529 if (HasBetterConversion)
8530 return true;
8531
Douglas Gregora1f013e2008-11-07 22:36:19 +00008532 // -- the context is an initialization by user-defined conversion
8533 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8534 // from the return type of F1 to the destination type (i.e.,
8535 // the type of the entity being initialized) is a better
8536 // conversion sequence than the standard conversion sequence
8537 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008538 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008539 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008540 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008541 // First check whether we prefer one of the conversion functions over the
8542 // other. This only distinguishes the results in non-standard, extension
8543 // cases such as the conversion from a lambda closure type to a function
8544 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008545 ImplicitConversionSequence::CompareKind Result =
8546 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8547 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008548 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008549 Cand1.FinalConversion,
8550 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008551
Richard Smithec2748a2014-05-17 04:36:39 +00008552 if (Result != ImplicitConversionSequence::Indistinguishable)
8553 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008554
8555 // FIXME: Compare kind of reference binding if conversion functions
8556 // convert to a reference type used in direct reference binding, per
8557 // C++14 [over.match.best]p1 section 2 bullet 3.
8558 }
8559
8560 // -- F1 is a non-template function and F2 is a function template
8561 // specialization, or, if not that,
8562 bool Cand1IsSpecialization = Cand1.Function &&
8563 Cand1.Function->getPrimaryTemplate();
8564 bool Cand2IsSpecialization = Cand2.Function &&
8565 Cand2.Function->getPrimaryTemplate();
8566 if (Cand1IsSpecialization != Cand2IsSpecialization)
8567 return Cand2IsSpecialization;
8568
8569 // -- F1 and F2 are function template specializations, and the function
8570 // template for F1 is more specialized than the template for F2
8571 // according to the partial ordering rules described in 14.5.5.2, or,
8572 // if not that,
8573 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8574 if (FunctionTemplateDecl *BetterTemplate
8575 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8576 Cand2.Function->getPrimaryTemplate(),
8577 Loc,
8578 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8579 : TPOC_Call,
8580 Cand1.ExplicitCallArguments,
8581 Cand2.ExplicitCallArguments))
8582 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008583 }
8584
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008585 // Check for enable_if value-based overload resolution.
8586 if (Cand1.Function && Cand2.Function &&
8587 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008588 Cand2.Function->hasAttr<EnableIfAttr>()))
8589 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008590
Artem Belevich94a55e82015-09-22 17:22:59 +00008591 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8592 Cand1.Function && Cand2.Function) {
8593 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8594 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8595 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8596 }
8597
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008598 bool HasPS1 = Cand1.Function != nullptr &&
8599 functionHasPassObjectSizeParams(Cand1.Function);
8600 bool HasPS2 = Cand2.Function != nullptr &&
8601 functionHasPassObjectSizeParams(Cand2.Function);
8602 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008603}
8604
Richard Smith2dbe4042015-11-04 19:26:32 +00008605/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008606/// name lookup and overload resolution. This applies when the same internal/no
8607/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008608/// the same header). In such a case, we don't consider the declarations to
8609/// declare the same entity, but we also don't want lookups with both
8610/// declarations visible to be ambiguous in some cases (this happens when using
8611/// a modularized libstdc++).
8612bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8613 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008614 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8615 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8616 if (!VA || !VB)
8617 return false;
8618
8619 // The declarations must be declaring the same name as an internal linkage
8620 // entity in different modules.
8621 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8622 VB->getDeclContext()->getRedeclContext()) ||
8623 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8624 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8625 VA->isExternallyVisible() || VB->isExternallyVisible())
8626 return false;
8627
8628 // Check that the declarations appear to be equivalent.
8629 //
8630 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8631 // For constants and functions, we should check the initializer or body is
8632 // the same. For non-constant variables, we shouldn't allow it at all.
8633 if (Context.hasSameType(VA->getType(), VB->getType()))
8634 return true;
8635
8636 // Enum constants within unnamed enumerations will have different types, but
8637 // may still be similar enough to be interchangeable for our purposes.
8638 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8639 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8640 // Only handle anonymous enums. If the enumerations were named and
8641 // equivalent, they would have been merged to the same type.
8642 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8643 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8644 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8645 !Context.hasSameType(EnumA->getIntegerType(),
8646 EnumB->getIntegerType()))
8647 return false;
8648 // Allow this only if the value is the same for both enumerators.
8649 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8650 }
8651 }
8652
8653 // Nothing else is sufficiently similar.
8654 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008655}
8656
8657void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8658 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8659 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8660
8661 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8662 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8663 << !M << (M ? M->getFullModuleName() : "");
8664
8665 for (auto *E : Equiv) {
8666 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8667 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8668 << !M << (M ? M->getFullModuleName() : "");
8669 }
Richard Smith896c66e2015-10-21 07:13:52 +00008670}
8671
Mike Stump11289f42009-09-09 15:08:12 +00008672/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008673/// within an overload candidate set.
8674///
James Dennettffad8b72012-06-22 08:10:18 +00008675/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008676/// which overload resolution occurs.
8677///
James Dennettffad8b72012-06-22 08:10:18 +00008678/// \param Best If overload resolution was successful or found a deleted
8679/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008680///
8681/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008682OverloadingResult
8683OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008684 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008685 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008686 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008687 Best = end();
8688 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8689 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008690 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008691 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008692 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008693 }
8694
8695 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008696 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008697 return OR_No_Viable_Function;
8698
Richard Smith2dbe4042015-11-04 19:26:32 +00008699 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008700
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008701 // Make sure that this function is better than every other viable
8702 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008703 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008704 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008705 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008706 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008707 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008708 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8709 Cand->Function)) {
8710 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008711 continue;
8712 }
8713
John McCall5c32be02010-08-24 20:38:10 +00008714 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008715 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008717 }
Mike Stump11289f42009-09-09 15:08:12 +00008718
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008719 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008720 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008721 (Best->Function->isDeleted() ||
8722 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008723 return OR_Deleted;
8724
Richard Smith2dbe4042015-11-04 19:26:32 +00008725 if (!EquivalentCands.empty())
8726 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8727 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008728
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008729 return OR_Success;
8730}
8731
John McCall53262c92010-01-12 02:15:36 +00008732namespace {
8733
8734enum OverloadCandidateKind {
8735 oc_function,
8736 oc_method,
8737 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008738 oc_function_template,
8739 oc_method_template,
8740 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008741 oc_implicit_default_constructor,
8742 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008743 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008744 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008745 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008746 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008747};
8748
John McCalle1ac8d12010-01-13 00:25:19 +00008749OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8750 FunctionDecl *Fn,
8751 std::string &Description) {
8752 bool isTemplate = false;
8753
8754 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8755 isTemplate = true;
8756 Description = S.getTemplateArgumentBindingsText(
8757 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8758 }
John McCallfd0b2f82010-01-06 09:43:14 +00008759
8760 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008761 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008762 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008763
Sebastian Redl08905022011-02-05 19:23:19 +00008764 if (Ctor->getInheritedConstructor())
8765 return oc_implicit_inherited_constructor;
8766
Alexis Hunt119c10e2011-05-25 23:16:36 +00008767 if (Ctor->isDefaultConstructor())
8768 return oc_implicit_default_constructor;
8769
8770 if (Ctor->isMoveConstructor())
8771 return oc_implicit_move_constructor;
8772
8773 assert(Ctor->isCopyConstructor() &&
8774 "unexpected sort of implicit constructor");
8775 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008776 }
8777
8778 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8779 // This actually gets spelled 'candidate function' for now, but
8780 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008781 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008782 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008783
Alexis Hunt119c10e2011-05-25 23:16:36 +00008784 if (Meth->isMoveAssignmentOperator())
8785 return oc_implicit_move_assignment;
8786
Douglas Gregor12695102012-02-10 08:36:38 +00008787 if (Meth->isCopyAssignmentOperator())
8788 return oc_implicit_copy_assignment;
8789
8790 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8791 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008792 }
8793
John McCalle1ac8d12010-01-13 00:25:19 +00008794 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008795}
8796
Larisse Voufo98b20f12013-07-19 23:00:19 +00008797void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008798 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8799 if (!Ctor) return;
8800
8801 Ctor = Ctor->getInheritedConstructor();
8802 if (!Ctor) return;
8803
8804 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8805}
8806
John McCall53262c92010-01-12 02:15:36 +00008807} // end anonymous namespace
8808
George Burgess IV5f21c712015-10-12 19:57:04 +00008809static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8810 const FunctionDecl *FD) {
8811 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8812 bool AlwaysTrue;
8813 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8814 return false;
8815 if (!AlwaysTrue)
8816 return false;
8817 }
8818 return true;
8819}
8820
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008821/// \brief Returns true if we can take the address of the function.
8822///
8823/// \param Complain - If true, we'll emit a diagnostic
8824/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8825/// we in overload resolution?
8826/// \param Loc - The location of the statement we're complaining about. Ignored
8827/// if we're not complaining, or if we're in overload resolution.
8828static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8829 bool Complain,
8830 bool InOverloadResolution,
8831 SourceLocation Loc) {
8832 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8833 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008834 if (InOverloadResolution)
8835 S.Diag(FD->getLocStart(),
8836 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8837 else
8838 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8839 }
8840 return false;
8841 }
8842
8843 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8844 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8845 if (I == FD->param_end())
8846 return true;
8847
8848 if (Complain) {
8849 // Add one to ParamNo because it's user-facing
8850 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8851 if (InOverloadResolution)
8852 S.Diag(FD->getLocation(),
8853 diag::note_ovl_candidate_has_pass_object_size_params)
8854 << ParamNo;
8855 else
8856 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8857 << FD << ParamNo;
8858 }
8859 return false;
8860}
8861
8862static bool checkAddressOfCandidateIsAvailable(Sema &S,
8863 const FunctionDecl *FD) {
8864 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8865 /*InOverloadResolution=*/true,
8866 /*Loc=*/SourceLocation());
8867}
8868
8869bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8870 bool Complain,
8871 SourceLocation Loc) {
8872 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8873 /*InOverloadResolution=*/false,
8874 Loc);
8875}
8876
John McCall53262c92010-01-12 02:15:36 +00008877// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008878void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8879 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008880 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8881 return;
8882
John McCalle1ac8d12010-01-13 00:25:19 +00008883 std::string FnDesc;
8884 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008885 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8886 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008887
8888 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008889 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008890 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008891}
8892
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008893// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008894// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008895void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8896 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008897 assert(OverloadedExpr->getType() == Context.OverloadTy);
8898
8899 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8900 OverloadExpr *OvlExpr = Ovl.Expression;
8901
8902 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8903 IEnd = OvlExpr->decls_end();
8904 I != IEnd; ++I) {
8905 if (FunctionTemplateDecl *FunTmpl =
8906 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008907 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8908 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008909 } else if (FunctionDecl *Fun
8910 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008911 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008912 }
8913 }
8914}
8915
John McCall0d1da222010-01-12 00:44:57 +00008916/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8917/// "lead" diagnostic; it will be given two arguments, the source and
8918/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008919void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8920 Sema &S,
8921 SourceLocation CaretLoc,
8922 const PartialDiagnostic &PDiag) const {
8923 S.Diag(CaretLoc, PDiag)
8924 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008925 // FIXME: The note limiting machinery is borrowed from
8926 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8927 // refactoring here.
8928 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8929 unsigned CandsShown = 0;
8930 AmbiguousConversionSequence::const_iterator I, E;
8931 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8932 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8933 break;
8934 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008935 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008936 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008937 if (I != E)
8938 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008939}
8940
Richard Smith17c00b42014-11-12 01:24:00 +00008941static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008942 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00008943 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8944 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008945 assert(Cand->Function && "for now, candidate must be a function");
8946 FunctionDecl *Fn = Cand->Function;
8947
8948 // There's a conversion slot for the object argument if this is a
8949 // non-constructor method. Note that 'I' corresponds the
8950 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008951 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008952 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008953 if (I == 0)
8954 isObjectArgument = true;
8955 else
8956 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008957 }
8958
John McCalle1ac8d12010-01-13 00:25:19 +00008959 std::string FnDesc;
8960 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8961
John McCall6a61b522010-01-13 09:16:55 +00008962 Expr *FromExpr = Conv.Bad.FromExpr;
8963 QualType FromTy = Conv.Bad.getFromType();
8964 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008965
John McCallfb7ad0f2010-02-02 02:42:52 +00008966 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008967 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008968 Expr *E = FromExpr->IgnoreParens();
8969 if (isa<UnaryOperator>(E))
8970 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008971 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008972
8973 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8974 << (unsigned) FnKind << FnDesc
8975 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8976 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008977 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008978 return;
8979 }
8980
John McCall6d174642010-01-23 08:10:49 +00008981 // Do some hand-waving analysis to see if the non-viability is due
8982 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008983 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8984 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8985 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8986 CToTy = RT->getPointeeType();
8987 else {
8988 // TODO: detect and diagnose the full richness of const mismatches.
8989 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8990 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8991 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8992 }
8993
8994 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8995 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008996 Qualifiers FromQs = CFromTy.getQualifiers();
8997 Qualifiers ToQs = CToTy.getQualifiers();
8998
8999 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9000 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9001 << (unsigned) FnKind << FnDesc
9002 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9003 << FromTy
9004 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9005 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009006 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009007 return;
9008 }
9009
John McCall31168b02011-06-15 23:02:42 +00009010 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009011 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009012 << (unsigned) FnKind << FnDesc
9013 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9014 << FromTy
9015 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9016 << (unsigned) isObjectArgument << I+1;
9017 MaybeEmitInheritedConstructorNote(S, Fn);
9018 return;
9019 }
9020
Douglas Gregoraec25842011-04-26 23:16:46 +00009021 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9022 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9023 << (unsigned) FnKind << FnDesc
9024 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9025 << FromTy
9026 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9027 << (unsigned) isObjectArgument << I+1;
9028 MaybeEmitInheritedConstructorNote(S, Fn);
9029 return;
9030 }
9031
John McCall47000992010-01-14 03:28:57 +00009032 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9033 assert(CVR && "unexpected qualifiers mismatch");
9034
9035 if (isObjectArgument) {
9036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9037 << (unsigned) FnKind << FnDesc
9038 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9039 << FromTy << (CVR - 1);
9040 } else {
9041 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9042 << (unsigned) FnKind << FnDesc
9043 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9044 << FromTy << (CVR - 1) << I+1;
9045 }
Sebastian Redl08905022011-02-05 19:23:19 +00009046 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009047 return;
9048 }
9049
Sebastian Redla72462c2011-09-24 17:48:32 +00009050 // Special diagnostic for failure to convert an initializer list, since
9051 // telling the user that it has type void is not useful.
9052 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9054 << (unsigned) FnKind << FnDesc
9055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9056 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9057 MaybeEmitInheritedConstructorNote(S, Fn);
9058 return;
9059 }
9060
John McCall6d174642010-01-23 08:10:49 +00009061 // Diagnose references or pointers to incomplete types differently,
9062 // since it's far from impossible that the incompleteness triggered
9063 // the failure.
9064 QualType TempFromTy = FromTy.getNonReferenceType();
9065 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9066 TempFromTy = PTy->getPointeeType();
9067 if (TempFromTy->isIncompleteType()) {
9068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9069 << (unsigned) FnKind << FnDesc
9070 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9071 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009072 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009073 return;
9074 }
9075
Douglas Gregor56f2e342010-06-30 23:01:39 +00009076 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009077 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009078 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9079 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9080 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9081 FromPtrTy->getPointeeType()) &&
9082 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9083 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009084 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009085 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009086 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009087 }
9088 } else if (const ObjCObjectPointerType *FromPtrTy
9089 = FromTy->getAs<ObjCObjectPointerType>()) {
9090 if (const ObjCObjectPointerType *ToPtrTy
9091 = ToTy->getAs<ObjCObjectPointerType>())
9092 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9093 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9094 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9095 FromPtrTy->getPointeeType()) &&
9096 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009097 BaseToDerivedConversion = 2;
9098 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009099 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9100 !FromTy->isIncompleteType() &&
9101 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009102 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009103 BaseToDerivedConversion = 3;
9104 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9105 ToTy.getNonReferenceType().getCanonicalType() ==
9106 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9108 << (unsigned) FnKind << FnDesc
9109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9110 << (unsigned) isObjectArgument << I + 1;
9111 MaybeEmitInheritedConstructorNote(S, Fn);
9112 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009113 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009115
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009116 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009117 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009118 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009119 << (unsigned) FnKind << FnDesc
9120 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009121 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009122 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009123 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009124 return;
9125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009126
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009127 if (isa<ObjCObjectPointerType>(CFromTy) &&
9128 isa<PointerType>(CToTy)) {
9129 Qualifiers FromQs = CFromTy.getQualifiers();
9130 Qualifiers ToQs = CToTy.getQualifiers();
9131 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9132 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9133 << (unsigned) FnKind << FnDesc
9134 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9135 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9136 MaybeEmitInheritedConstructorNote(S, Fn);
9137 return;
9138 }
9139 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009140
9141 if (TakingCandidateAddress &&
9142 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9143 return;
9144
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009145 // Emit the generic diagnostic and, optionally, add the hints to it.
9146 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9147 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009148 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009149 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9150 << (unsigned) (Cand->Fix.Kind);
9151
9152 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009153 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9154 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009155 FDiag << *HI;
9156 S.Diag(Fn->getLocation(), FDiag);
9157
Sebastian Redl08905022011-02-05 19:23:19 +00009158 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009159}
9160
Larisse Voufo98b20f12013-07-19 23:00:19 +00009161/// Additional arity mismatch diagnosis specific to a function overload
9162/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9163/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009164static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9165 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009166 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009167 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009168
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009169 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009170 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009171 // right number of arguments, because only overloaded operators have
9172 // the weird behavior of overloading member and non-member functions.
9173 // Just don't report anything.
9174 if (Fn->isInvalidDecl() &&
9175 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009176 return true;
9177
9178 if (NumArgs < MinParams) {
9179 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9180 (Cand->FailureKind == ovl_fail_bad_deduction &&
9181 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9182 } else {
9183 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9184 (Cand->FailureKind == ovl_fail_bad_deduction &&
9185 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9186 }
9187
9188 return false;
9189}
9190
9191/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009192static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009193 assert(isa<FunctionDecl>(D) &&
9194 "The templated declaration should at least be a function"
9195 " when diagnosing bad template argument deduction due to too many"
9196 " or too few arguments");
9197
9198 FunctionDecl *Fn = cast<FunctionDecl>(D);
9199
9200 // TODO: treat calls to a missing default constructor as a special case
9201 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9202 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009203
John McCall6a61b522010-01-13 09:16:55 +00009204 // at least / at most / exactly
9205 unsigned mode, modeCount;
9206 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009207 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9208 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009209 mode = 0; // "at least"
9210 else
9211 mode = 2; // "exactly"
9212 modeCount = MinParams;
9213 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009214 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009215 mode = 1; // "at most"
9216 else
9217 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009218 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009219 }
9220
9221 std::string Description;
9222 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9223
Richard Smith10ff50d2012-05-11 05:16:41 +00009224 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9225 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009226 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9227 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009228 else
9229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009230 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9231 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009232 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009233}
9234
Larisse Voufo98b20f12013-07-19 23:00:19 +00009235/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009236static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9237 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009238 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9239 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9240}
Larisse Voufo47c08452013-07-19 22:53:23 +00009241
Richard Smith17c00b42014-11-12 01:24:00 +00009242static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9244 return FD->getDescribedFunctionTemplate();
9245 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9246 return RD->getDescribedClassTemplate();
9247
9248 llvm_unreachable("Unsupported: Getting the described template declaration"
9249 " for bad deduction diagnosis");
9250}
9251
9252/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009253static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9254 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009255 unsigned NumArgs,
9256 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009257 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009258 NamedDecl *ParamD;
9259 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9260 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9261 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009262 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009263 case Sema::TDK_Success:
9264 llvm_unreachable("TDK_success while diagnosing bad deduction");
9265
9266 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009267 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009268 S.Diag(Templated->getLocation(),
9269 diag::note_ovl_candidate_incomplete_deduction)
9270 << ParamD->getDeclName();
9271 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009272 return;
9273 }
9274
John McCall42d7d192010-08-05 09:05:08 +00009275 case Sema::TDK_Underqualified: {
9276 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9277 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9278
Larisse Voufo98b20f12013-07-19 23:00:19 +00009279 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009280
9281 // Param will have been canonicalized, but it should just be a
9282 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009283 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009284 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009285 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009286 assert(S.Context.hasSameType(Param, NonCanonParam));
9287
9288 // Arg has also been canonicalized, but there's nothing we can do
9289 // about that. It also doesn't matter as much, because it won't
9290 // have any template parameters in it (because deduction isn't
9291 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009292 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009293
Larisse Voufo98b20f12013-07-19 23:00:19 +00009294 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9295 << ParamD->getDeclName() << Arg << NonCanonParam;
9296 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009297 return;
9298 }
9299
9300 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009301 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009302 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009303 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009304 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009305 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009306 which = 1;
9307 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009308 which = 2;
9309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009310
Larisse Voufo98b20f12013-07-19 23:00:19 +00009311 S.Diag(Templated->getLocation(),
9312 diag::note_ovl_candidate_inconsistent_deduction)
9313 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9314 << *DeductionFailure.getSecondArg();
9315 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009316 return;
9317 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009318
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009319 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009320 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009321 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009322 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009323 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009324 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009325 else {
9326 int index = 0;
9327 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9328 index = TTP->getIndex();
9329 else if (NonTypeTemplateParmDecl *NTTP
9330 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9331 index = NTTP->getIndex();
9332 else
9333 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009334 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009335 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009336 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009337 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009338 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009339 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009340
Douglas Gregor02eb4832010-05-08 18:13:28 +00009341 case Sema::TDK_TooManyArguments:
9342 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009343 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009344 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009345
9346 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009347 S.Diag(Templated->getLocation(),
9348 diag::note_ovl_candidate_instantiation_depth);
9349 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009350 return;
9351
9352 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009353 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009354 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009355 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009356 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009357 TemplateArgString = " ";
9358 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009359 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009360 }
9361
Richard Smith6f8d2c62012-05-09 05:17:00 +00009362 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009363 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009364 if (PDiag && PDiag->second.getDiagID() ==
9365 diag::err_typename_nested_not_found_enable_if) {
9366 // FIXME: Use the source range of the condition, and the fully-qualified
9367 // name of the enable_if template. These are both present in PDiag.
9368 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9369 << "'enable_if'" << TemplateArgString;
9370 return;
9371 }
9372
Richard Smith9ca64612012-05-07 09:03:25 +00009373 // Format the SFINAE diagnostic into the argument string.
9374 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9375 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009376 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009377 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009378 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009379 SFINAEArgString = ": ";
9380 R = SourceRange(PDiag->first, PDiag->first);
9381 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9382 }
9383
Larisse Voufo98b20f12013-07-19 23:00:19 +00009384 S.Diag(Templated->getLocation(),
9385 diag::note_ovl_candidate_substitution_failure)
9386 << TemplateArgString << SFINAEArgString << R;
9387 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009388 return;
9389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009390
Richard Smith8c6eeb92013-01-31 04:03:12 +00009391 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009392 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9393 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009394 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009395 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009396 return;
9397 }
9398
Richard Trieue3732352013-04-08 21:11:40 +00009399 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009400 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009401 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9402 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009403 if (FirstTA.getKind() == TemplateArgument::Template &&
9404 SecondTA.getKind() == TemplateArgument::Template) {
9405 TemplateName FirstTN = FirstTA.getAsTemplate();
9406 TemplateName SecondTN = SecondTA.getAsTemplate();
9407 if (FirstTN.getKind() == TemplateName::Template &&
9408 SecondTN.getKind() == TemplateName::Template) {
9409 if (FirstTN.getAsTemplateDecl()->getName() ==
9410 SecondTN.getAsTemplateDecl()->getName()) {
9411 // FIXME: This fixes a bad diagnostic where both templates are named
9412 // the same. This particular case is a bit difficult since:
9413 // 1) It is passed as a string to the diagnostic printer.
9414 // 2) The diagnostic printer only attempts to find a better
9415 // name for types, not decls.
9416 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009417 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009418 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9419 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9420 return;
9421 }
9422 }
9423 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009424
9425 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9426 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9427 return;
9428
Faisal Vali2b391ab2013-09-26 19:54:12 +00009429 // FIXME: For generic lambda parameters, check if the function is a lambda
9430 // call operator, and if so, emit a prettier and more informative
9431 // diagnostic that mentions 'auto' and lambda in addition to
9432 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009433 S.Diag(Templated->getLocation(),
9434 diag::note_ovl_candidate_non_deduced_mismatch)
9435 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009436 return;
Richard Trieue3732352013-04-08 21:11:40 +00009437 }
John McCall8b9ed552010-02-01 18:53:26 +00009438 // TODO: diagnose these individually, then kill off
9439 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009440 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009441 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9442 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009443 return;
9444 }
9445}
9446
Larisse Voufo98b20f12013-07-19 23:00:19 +00009447/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009448static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009449 unsigned NumArgs,
9450 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009451 unsigned TDK = Cand->DeductionFailure.Result;
9452 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9453 if (CheckArityMismatch(S, Cand, NumArgs))
9454 return;
9455 }
9456 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009457 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009458}
9459
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009460/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009461static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009462 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9463 FunctionDecl *Callee = Cand->Function;
9464
9465 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9466 CalleeTarget = S.IdentifyCUDATarget(Callee);
9467
9468 std::string FnDesc;
9469 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9470
9471 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009472 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9473
9474 // This could be an implicit constructor for which we could not infer the
9475 // target due to a collsion. Diagnose that case.
9476 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9477 if (Meth != nullptr && Meth->isImplicit()) {
9478 CXXRecordDecl *ParentClass = Meth->getParent();
9479 Sema::CXXSpecialMember CSM;
9480
9481 switch (FnKind) {
9482 default:
9483 return;
9484 case oc_implicit_default_constructor:
9485 CSM = Sema::CXXDefaultConstructor;
9486 break;
9487 case oc_implicit_copy_constructor:
9488 CSM = Sema::CXXCopyConstructor;
9489 break;
9490 case oc_implicit_move_constructor:
9491 CSM = Sema::CXXMoveConstructor;
9492 break;
9493 case oc_implicit_copy_assignment:
9494 CSM = Sema::CXXCopyAssignment;
9495 break;
9496 case oc_implicit_move_assignment:
9497 CSM = Sema::CXXMoveAssignment;
9498 break;
9499 };
9500
9501 bool ConstRHS = false;
9502 if (Meth->getNumParams()) {
9503 if (const ReferenceType *RT =
9504 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9505 ConstRHS = RT->getPointeeType().isConstQualified();
9506 }
9507 }
9508
9509 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9510 /* ConstRHS */ ConstRHS,
9511 /* Diagnose */ true);
9512 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009513}
9514
Richard Smith17c00b42014-11-12 01:24:00 +00009515static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009516 FunctionDecl *Callee = Cand->Function;
9517 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9518
9519 S.Diag(Callee->getLocation(),
9520 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9521 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9522}
9523
John McCall8b9ed552010-02-01 18:53:26 +00009524/// Generates a 'note' diagnostic for an overload candidate. We've
9525/// already generated a primary error at the call site.
9526///
9527/// It really does need to be a single diagnostic with its caret
9528/// pointed at the candidate declaration. Yes, this creates some
9529/// major challenges of technical writing. Yes, this makes pointing
9530/// out problems with specific arguments quite awkward. It's still
9531/// better than generating twenty screens of text for every failed
9532/// overload.
9533///
9534/// It would be great to be able to express per-candidate problems
9535/// more richly for those diagnostic clients that cared, but we'd
9536/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009537static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009538 unsigned NumArgs,
9539 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009540 FunctionDecl *Fn = Cand->Function;
9541
John McCall12f97bc2010-01-08 04:41:39 +00009542 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009543 if (Cand->Viable && (Fn->isDeleted() ||
9544 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009545 std::string FnDesc;
9546 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009547
9548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009549 << FnKind << FnDesc
9550 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009551 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009552 return;
John McCall12f97bc2010-01-08 04:41:39 +00009553 }
9554
John McCalle1ac8d12010-01-13 00:25:19 +00009555 // We don't really have anything else to say about viable candidates.
9556 if (Cand->Viable) {
9557 S.NoteOverloadCandidate(Fn);
9558 return;
9559 }
John McCall0d1da222010-01-12 00:44:57 +00009560
John McCall6a61b522010-01-13 09:16:55 +00009561 switch (Cand->FailureKind) {
9562 case ovl_fail_too_many_arguments:
9563 case ovl_fail_too_few_arguments:
9564 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009565
John McCall6a61b522010-01-13 09:16:55 +00009566 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009567 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009568
John McCall578a1f82014-12-14 01:46:53 +00009569 case ovl_fail_illegal_constructor: {
9570 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9571 << (Fn->getPrimaryTemplate() ? 1 : 0);
9572 MaybeEmitInheritedConstructorNote(S, Fn);
9573 return;
9574 }
9575
John McCallfe796dd2010-01-23 05:17:32 +00009576 case ovl_fail_trivial_conversion:
9577 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009578 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009579 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009580
John McCall65eb8792010-02-25 01:37:24 +00009581 case ovl_fail_bad_conversion: {
9582 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009583 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009584 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009585 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009586
John McCall6a61b522010-01-13 09:16:55 +00009587 // FIXME: this currently happens when we're called from SemaInit
9588 // when user-conversion overload fails. Figure out how to handle
9589 // those conditions and diagnose them well.
9590 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009591 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009592
9593 case ovl_fail_bad_target:
9594 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009595
9596 case ovl_fail_enable_if:
9597 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009598 }
John McCalld3224162010-01-08 00:58:21 +00009599}
9600
Richard Smith17c00b42014-11-12 01:24:00 +00009601static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009602 // Desugar the type of the surrogate down to a function type,
9603 // retaining as many typedefs as possible while still showing
9604 // the function type (and, therefore, its parameter types).
9605 QualType FnType = Cand->Surrogate->getConversionType();
9606 bool isLValueReference = false;
9607 bool isRValueReference = false;
9608 bool isPointer = false;
9609 if (const LValueReferenceType *FnTypeRef =
9610 FnType->getAs<LValueReferenceType>()) {
9611 FnType = FnTypeRef->getPointeeType();
9612 isLValueReference = true;
9613 } else if (const RValueReferenceType *FnTypeRef =
9614 FnType->getAs<RValueReferenceType>()) {
9615 FnType = FnTypeRef->getPointeeType();
9616 isRValueReference = true;
9617 }
9618 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9619 FnType = FnTypePtr->getPointeeType();
9620 isPointer = true;
9621 }
9622 // Desugar down to a function type.
9623 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9624 // Reconstruct the pointer/reference as appropriate.
9625 if (isPointer) FnType = S.Context.getPointerType(FnType);
9626 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9627 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9628
9629 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9630 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009631 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009632}
9633
Richard Smith17c00b42014-11-12 01:24:00 +00009634static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9635 SourceLocation OpLoc,
9636 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009637 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009638 std::string TypeStr("operator");
9639 TypeStr += Opc;
9640 TypeStr += "(";
9641 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009642 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009643 TypeStr += ")";
9644 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9645 } else {
9646 TypeStr += ", ";
9647 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9648 TypeStr += ")";
9649 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9650 }
9651}
9652
Richard Smith17c00b42014-11-12 01:24:00 +00009653static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9654 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009655 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009656 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9657 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009658 if (ICS.isBad()) break; // all meaningless after first invalid
9659 if (!ICS.isAmbiguous()) continue;
9660
John McCall5c32be02010-08-24 20:38:10 +00009661 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009662 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009663 }
9664}
9665
Larisse Voufo98b20f12013-07-19 23:00:19 +00009666static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009667 if (Cand->Function)
9668 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009669 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009670 return Cand->Surrogate->getLocation();
9671 return SourceLocation();
9672}
9673
Larisse Voufo98b20f12013-07-19 23:00:19 +00009674static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009675 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009676 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009677 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009678
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009679 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009680 case Sema::TDK_Incomplete:
9681 return 1;
9682
9683 case Sema::TDK_Underqualified:
9684 case Sema::TDK_Inconsistent:
9685 return 2;
9686
9687 case Sema::TDK_SubstitutionFailure:
9688 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009689 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009690 return 3;
9691
9692 case Sema::TDK_InstantiationDepth:
9693 case Sema::TDK_FailedOverloadResolution:
9694 return 4;
9695
9696 case Sema::TDK_InvalidExplicitArguments:
9697 return 5;
9698
9699 case Sema::TDK_TooManyArguments:
9700 case Sema::TDK_TooFewArguments:
9701 return 6;
9702 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009703 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009704}
9705
Richard Smith17c00b42014-11-12 01:24:00 +00009706namespace {
John McCallad2587a2010-01-12 00:48:53 +00009707struct CompareOverloadCandidatesForDisplay {
9708 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009709 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009710 size_t NumArgs;
9711
Richard Smith0f59cb32015-12-18 21:45:41 +00009712 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009713 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009714
9715 bool operator()(const OverloadCandidate *L,
9716 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009717 // Fast-path this check.
9718 if (L == R) return false;
9719
John McCall12f97bc2010-01-08 04:41:39 +00009720 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009721 if (L->Viable) {
9722 if (!R->Viable) return true;
9723
9724 // TODO: introduce a tri-valued comparison for overload
9725 // candidates. Would be more worthwhile if we had a sort
9726 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009727 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9728 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009729 } else if (R->Viable)
9730 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009731
John McCall3712d9e2010-01-15 23:32:50 +00009732 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009733
John McCall3712d9e2010-01-15 23:32:50 +00009734 // Criteria by which we can sort non-viable candidates:
9735 if (!L->Viable) {
9736 // 1. Arity mismatches come after other candidates.
9737 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009738 L->FailureKind == ovl_fail_too_few_arguments) {
9739 if (R->FailureKind == ovl_fail_too_many_arguments ||
9740 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009741 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9742 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9743 if (LDist == RDist) {
9744 if (L->FailureKind == R->FailureKind)
9745 // Sort non-surrogates before surrogates.
9746 return !L->IsSurrogate && R->IsSurrogate;
9747 // Sort candidates requiring fewer parameters than there were
9748 // arguments given after candidates requiring more parameters
9749 // than there were arguments given.
9750 return L->FailureKind == ovl_fail_too_many_arguments;
9751 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009752 return LDist < RDist;
9753 }
John McCall3712d9e2010-01-15 23:32:50 +00009754 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009755 }
John McCall3712d9e2010-01-15 23:32:50 +00009756 if (R->FailureKind == ovl_fail_too_many_arguments ||
9757 R->FailureKind == ovl_fail_too_few_arguments)
9758 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009759
John McCallfe796dd2010-01-23 05:17:32 +00009760 // 2. Bad conversions come first and are ordered by the number
9761 // of bad conversions and quality of good conversions.
9762 if (L->FailureKind == ovl_fail_bad_conversion) {
9763 if (R->FailureKind != ovl_fail_bad_conversion)
9764 return true;
9765
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009766 // The conversion that can be fixed with a smaller number of changes,
9767 // comes first.
9768 unsigned numLFixes = L->Fix.NumConversionsFixed;
9769 unsigned numRFixes = R->Fix.NumConversionsFixed;
9770 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9771 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009772 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009773 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009774 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009775
John McCallfe796dd2010-01-23 05:17:32 +00009776 // If there's any ordering between the defined conversions...
9777 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009778 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009779
9780 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009781 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009782 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009783 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009784 L->Conversions[I],
9785 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009786 case ImplicitConversionSequence::Better:
9787 leftBetter++;
9788 break;
9789
9790 case ImplicitConversionSequence::Worse:
9791 leftBetter--;
9792 break;
9793
9794 case ImplicitConversionSequence::Indistinguishable:
9795 break;
9796 }
9797 }
9798 if (leftBetter > 0) return true;
9799 if (leftBetter < 0) return false;
9800
9801 } else if (R->FailureKind == ovl_fail_bad_conversion)
9802 return false;
9803
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009804 if (L->FailureKind == ovl_fail_bad_deduction) {
9805 if (R->FailureKind != ovl_fail_bad_deduction)
9806 return true;
9807
9808 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9809 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009810 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009811 } else if (R->FailureKind == ovl_fail_bad_deduction)
9812 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009813
John McCall3712d9e2010-01-15 23:32:50 +00009814 // TODO: others?
9815 }
9816
9817 // Sort everything else by location.
9818 SourceLocation LLoc = GetLocationForCandidate(L);
9819 SourceLocation RLoc = GetLocationForCandidate(R);
9820
9821 // Put candidates without locations (e.g. builtins) at the end.
9822 if (LLoc.isInvalid()) return false;
9823 if (RLoc.isInvalid()) return true;
9824
9825 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009826 }
9827};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009828}
John McCall12f97bc2010-01-08 04:41:39 +00009829
John McCallfe796dd2010-01-23 05:17:32 +00009830/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009831/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009832static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9833 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009834 assert(!Cand->Viable);
9835
9836 // Don't do anything on failures other than bad conversion.
9837 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9838
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009839 // We only want the FixIts if all the arguments can be corrected.
9840 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009841 // Use a implicit copy initialization to check conversion fixes.
9842 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009843
John McCallfe796dd2010-01-23 05:17:32 +00009844 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009845 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009846 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009847 while (true) {
9848 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9849 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009850 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009851 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009852 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009853 }
John McCallfe796dd2010-01-23 05:17:32 +00009854 }
9855
9856 if (ConvIdx == ConvCount)
9857 return;
9858
John McCall65eb8792010-02-25 01:37:24 +00009859 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9860 "remaining conversion is initialized?");
9861
Douglas Gregoradc7a702010-04-16 17:45:54 +00009862 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009863 // operation somehow.
9864 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009865
9866 const FunctionProtoType* Proto;
9867 unsigned ArgIdx = ConvIdx;
9868
9869 if (Cand->IsSurrogate) {
9870 QualType ConvType
9871 = Cand->Surrogate->getConversionType().getNonReferenceType();
9872 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9873 ConvType = ConvPtrType->getPointeeType();
9874 Proto = ConvType->getAs<FunctionProtoType>();
9875 ArgIdx--;
9876 } else if (Cand->Function) {
9877 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9878 if (isa<CXXMethodDecl>(Cand->Function) &&
9879 !isa<CXXConstructorDecl>(Cand->Function))
9880 ArgIdx--;
9881 } else {
9882 // Builtin binary operator with a bad first conversion.
9883 assert(ConvCount <= 3);
9884 for (; ConvIdx != ConvCount; ++ConvIdx)
9885 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009886 = TryCopyInitialization(S, Args[ConvIdx],
9887 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009888 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009889 /*InOverloadResolution*/ true,
9890 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009891 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009892 return;
9893 }
9894
9895 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009896 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009897 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009898 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009899 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9900 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9901 /*InOverloadResolution=*/true,
9902 /*AllowObjCWritebackConversion=*/
9903 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009904 // Store the FixIt in the candidate if it exists.
9905 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009906 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009907 }
John McCallfe796dd2010-01-23 05:17:32 +00009908 else
9909 Cand->Conversions[ConvIdx].setEllipsis();
9910 }
9911}
9912
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009913/// PrintOverloadCandidates - When overload resolution fails, prints
9914/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009915/// set.
John McCall5c32be02010-08-24 20:38:10 +00009916void OverloadCandidateSet::NoteCandidates(Sema &S,
9917 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009918 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009919 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009920 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009921 // Sort the candidates by viability and position. Sorting directly would
9922 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009923 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009924 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9925 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009926 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009927 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009928 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009929 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009930 if (Cand->Function || Cand->IsSurrogate)
9931 Cands.push_back(Cand);
9932 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9933 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009934 }
9935 }
9936
John McCallad2587a2010-01-12 00:48:53 +00009937 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +00009938 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009939
John McCall0d1da222010-01-12 00:44:57 +00009940 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009941
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009942 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009943 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009944 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009945 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9946 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009947
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009948 // Set an arbitrary limit on the number of candidate functions we'll spam
9949 // the user with. FIXME: This limit should depend on details of the
9950 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009951 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009952 break;
9953 }
9954 ++CandsShown;
9955
John McCalld3224162010-01-08 00:58:21 +00009956 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009957 NoteFunctionCandidate(S, Cand, Args.size(),
9958 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +00009959 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009960 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009961 else {
9962 assert(Cand->Viable &&
9963 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009964 // Generally we only see ambiguities including viable builtin
9965 // operators if overload resolution got screwed up by an
9966 // ambiguous user-defined conversion.
9967 //
9968 // FIXME: It's quite possible for different conversions to see
9969 // different ambiguities, though.
9970 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009971 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009972 ReportedAmbiguousConversions = true;
9973 }
John McCalld3224162010-01-08 00:58:21 +00009974
John McCall0d1da222010-01-12 00:44:57 +00009975 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009976 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009977 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009978 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009979
9980 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009981 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009982}
9983
Larisse Voufo98b20f12013-07-19 23:00:19 +00009984static SourceLocation
9985GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9986 return Cand->Specialization ? Cand->Specialization->getLocation()
9987 : SourceLocation();
9988}
9989
Richard Smith17c00b42014-11-12 01:24:00 +00009990namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009991struct CompareTemplateSpecCandidatesForDisplay {
9992 Sema &S;
9993 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9994
9995 bool operator()(const TemplateSpecCandidate *L,
9996 const TemplateSpecCandidate *R) {
9997 // Fast-path this check.
9998 if (L == R)
9999 return false;
10000
10001 // Assuming that both candidates are not matches...
10002
10003 // Sort by the ranking of deduction failures.
10004 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10005 return RankDeductionFailure(L->DeductionFailure) <
10006 RankDeductionFailure(R->DeductionFailure);
10007
10008 // Sort everything else by location.
10009 SourceLocation LLoc = GetLocationForCandidate(L);
10010 SourceLocation RLoc = GetLocationForCandidate(R);
10011
10012 // Put candidates without locations (e.g. builtins) at the end.
10013 if (LLoc.isInvalid())
10014 return false;
10015 if (RLoc.isInvalid())
10016 return true;
10017
10018 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10019 }
10020};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010021}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010022
10023/// Diagnose a template argument deduction failure.
10024/// We are treating these failures as overload failures due to bad
10025/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010026void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10027 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010028 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010029 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010030}
10031
10032void TemplateSpecCandidateSet::destroyCandidates() {
10033 for (iterator i = begin(), e = end(); i != e; ++i) {
10034 i->DeductionFailure.Destroy();
10035 }
10036}
10037
10038void TemplateSpecCandidateSet::clear() {
10039 destroyCandidates();
10040 Candidates.clear();
10041}
10042
10043/// NoteCandidates - When no template specialization match is found, prints
10044/// diagnostic messages containing the non-matching specializations that form
10045/// the candidate set.
10046/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10047/// OCD == OCD_AllCandidates and Cand->Viable == false.
10048void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10049 // Sort the candidates by position (assuming no candidate is a match).
10050 // Sorting directly would be prohibitive, so we make a set of pointers
10051 // and sort those.
10052 SmallVector<TemplateSpecCandidate *, 32> Cands;
10053 Cands.reserve(size());
10054 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10055 if (Cand->Specialization)
10056 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010057 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010058 // in general, want to list every possible builtin candidate.
10059 }
10060
10061 std::sort(Cands.begin(), Cands.end(),
10062 CompareTemplateSpecCandidatesForDisplay(S));
10063
10064 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10065 // for generalization purposes (?).
10066 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10067
10068 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10069 unsigned CandsShown = 0;
10070 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10071 TemplateSpecCandidate *Cand = *I;
10072
10073 // Set an arbitrary limit on the number of candidates we'll spam
10074 // the user with. FIXME: This limit should depend on details of the
10075 // candidate list.
10076 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10077 break;
10078 ++CandsShown;
10079
10080 assert(Cand->Specialization &&
10081 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010082 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010083 }
10084
10085 if (I != E)
10086 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10087}
10088
Douglas Gregorb491ed32011-02-19 21:32:49 +000010089// [PossiblyAFunctionType] --> [Return]
10090// NonFunctionType --> NonFunctionType
10091// R (A) --> R(A)
10092// R (*)(A) --> R (A)
10093// R (&)(A) --> R (A)
10094// R (S::*)(A) --> R (A)
10095QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10096 QualType Ret = PossiblyAFunctionType;
10097 if (const PointerType *ToTypePtr =
10098 PossiblyAFunctionType->getAs<PointerType>())
10099 Ret = ToTypePtr->getPointeeType();
10100 else if (const ReferenceType *ToTypeRef =
10101 PossiblyAFunctionType->getAs<ReferenceType>())
10102 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010103 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010104 PossiblyAFunctionType->getAs<MemberPointerType>())
10105 Ret = MemTypePtr->getPointeeType();
10106 Ret =
10107 Context.getCanonicalType(Ret).getUnqualifiedType();
10108 return Ret;
10109}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010110
Richard Smith17c00b42014-11-12 01:24:00 +000010111namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010112// A helper class to help with address of function resolution
10113// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010114class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010115 Sema& S;
10116 Expr* SourceExpr;
10117 const QualType& TargetType;
10118 QualType TargetFunctionType; // Extracted function type from target type
10119
10120 bool Complain;
10121 //DeclAccessPair& ResultFunctionAccessPair;
10122 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010123
Douglas Gregorb491ed32011-02-19 21:32:49 +000010124 bool TargetTypeIsNonStaticMemberFunction;
10125 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010126 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010127 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010128
Douglas Gregorb491ed32011-02-19 21:32:49 +000010129 OverloadExpr::FindResult OvlExprInfo;
10130 OverloadExpr *OvlExpr;
10131 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010132 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010133 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010134
Douglas Gregorb491ed32011-02-19 21:32:49 +000010135public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010136 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10137 const QualType &TargetType, bool Complain)
10138 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10139 Complain(Complain), Context(S.getASTContext()),
10140 TargetTypeIsNonStaticMemberFunction(
10141 !!TargetType->getAs<MemberPointerType>()),
10142 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010143 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010144 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010145 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10146 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010147 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010148 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010149
David Majnemera4f7c7a2013-08-01 06:13:59 +000010150 if (TargetFunctionType->isFunctionType()) {
10151 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10152 if (!UME->isImplicitAccess() &&
10153 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10154 StaticMemberFunctionFromBoundPointer = true;
10155 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10156 DeclAccessPair dap;
10157 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10158 OvlExpr, false, &dap)) {
10159 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10160 if (!Method->isStatic()) {
10161 // If the target type is a non-function type and the function found
10162 // is a non-static member function, pretend as if that was the
10163 // target, it's the only possible type to end up with.
10164 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010165
David Majnemera4f7c7a2013-08-01 06:13:59 +000010166 // And skip adding the function if its not in the proper form.
10167 // We'll diagnose this due to an empty set of functions.
10168 if (!OvlExprInfo.HasFormOfMemberPointer)
10169 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010170 }
10171
David Majnemera4f7c7a2013-08-01 06:13:59 +000010172 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010173 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010174 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010175 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010176
10177 if (OvlExpr->hasExplicitTemplateArgs())
10178 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010179
Douglas Gregorb491ed32011-02-19 21:32:49 +000010180 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10181 // C++ [over.over]p4:
10182 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010183 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010184 if (FoundNonTemplateFunction)
10185 EliminateAllTemplateMatches();
10186 else
10187 EliminateAllExceptMostSpecializedTemplate();
10188 }
10189 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010190
10191 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10192 Matches.size() > 1)
10193 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010194 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010195
10196 bool hasComplained() const { return HasComplained; }
10197
Douglas Gregorb491ed32011-02-19 21:32:49 +000010198private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010199 // Is A considered a better overload candidate for the desired type than B?
10200 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10201 return hasBetterEnableIfAttrs(S, A, B);
10202 }
10203
10204 // Returns true if we've eliminated any (read: all but one) candidates, false
10205 // otherwise.
10206 bool eliminiateSuboptimalOverloadCandidates() {
10207 // Same algorithm as overload resolution -- one pass to pick the "best",
10208 // another pass to be sure that nothing is better than the best.
10209 auto Best = Matches.begin();
10210 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10211 if (isBetterCandidate(I->second, Best->second))
10212 Best = I;
10213
10214 const FunctionDecl *BestFn = Best->second;
10215 auto IsBestOrInferiorToBest = [this, BestFn](
10216 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10217 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10218 };
10219
10220 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10221 // option, so we can potentially give the user a better error
10222 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10223 return false;
10224 Matches[0] = *Best;
10225 Matches.resize(1);
10226 return true;
10227 }
10228
Douglas Gregorb491ed32011-02-19 21:32:49 +000010229 bool isTargetTypeAFunction() const {
10230 return TargetFunctionType->isFunctionType();
10231 }
10232
10233 // [ToType] [Return]
10234
10235 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10236 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10237 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10238 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10239 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10240 }
10241
10242 // return true if any matching specializations were found
10243 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10244 const DeclAccessPair& CurAccessFunPair) {
10245 if (CXXMethodDecl *Method
10246 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10247 // Skip non-static function templates when converting to pointer, and
10248 // static when converting to member pointer.
10249 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10250 return false;
10251 }
10252 else if (TargetTypeIsNonStaticMemberFunction)
10253 return false;
10254
10255 // C++ [over.over]p2:
10256 // If the name is a function template, template argument deduction is
10257 // done (14.8.2.2), and if the argument deduction succeeds, the
10258 // resulting template argument list is used to generate a single
10259 // function template specialization, which is added to the set of
10260 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010261 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010262 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010263 if (Sema::TemplateDeductionResult Result
10264 = S.DeduceTemplateArguments(FunctionTemplate,
10265 &OvlExplicitTemplateArgs,
10266 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010267 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010268 // Make a note of the failed deduction for diagnostics.
10269 FailedCandidates.addCandidate()
10270 .set(FunctionTemplate->getTemplatedDecl(),
10271 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010272 return false;
10273 }
10274
Douglas Gregor19a41f12013-04-17 08:45:07 +000010275 // Template argument deduction ensures that we have an exact match or
10276 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010277 // This function template specicalization works.
10278 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010279 assert(S.isSameOrCompatibleFunctionType(
10280 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010281 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010282
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010283 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010284 return false;
10285
Douglas Gregorb491ed32011-02-19 21:32:49 +000010286 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10287 return true;
10288 }
10289
10290 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10291 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010293 // Skip non-static functions when converting to pointer, and static
10294 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010295 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10296 return false;
10297 }
10298 else if (TargetTypeIsNonStaticMemberFunction)
10299 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010300
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010301 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010302 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010303 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010304 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010305 return false;
10306
Richard Smith2a7d4812013-05-04 07:00:32 +000010307 // If any candidate has a placeholder return type, trigger its deduction
10308 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010309 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010310 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010311 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10312 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010313 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010314 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010315
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010316 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010317 return false;
10318
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010319 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010320 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10321 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010322 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010323 ResultTy) ||
10324 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10325 Matches.push_back(std::make_pair(
10326 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010327 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010328 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010329 }
Mike Stump11289f42009-09-09 15:08:12 +000010330 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010331
10332 return false;
10333 }
10334
10335 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10336 bool Ret = false;
10337
10338 // If the overload expression doesn't have the form of a pointer to
10339 // member, don't try to convert it to a pointer-to-member type.
10340 if (IsInvalidFormOfPointerToMemberFunction())
10341 return false;
10342
10343 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10344 E = OvlExpr->decls_end();
10345 I != E; ++I) {
10346 // Look through any using declarations to find the underlying function.
10347 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10348
10349 // C++ [over.over]p3:
10350 // Non-member functions and static member functions match
10351 // targets of type "pointer-to-function" or "reference-to-function."
10352 // Nonstatic member functions match targets of
10353 // type "pointer-to-member-function."
10354 // Note that according to DR 247, the containing class does not matter.
10355 if (FunctionTemplateDecl *FunctionTemplate
10356 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10357 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10358 Ret = true;
10359 }
10360 // If we have explicit template arguments supplied, skip non-templates.
10361 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10362 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10363 Ret = true;
10364 }
10365 assert(Ret || Matches.empty());
10366 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010367 }
10368
Douglas Gregorb491ed32011-02-19 21:32:49 +000010369 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010370 // [...] and any given function template specialization F1 is
10371 // eliminated if the set contains a second function template
10372 // specialization whose function template is more specialized
10373 // than the function template of F1 according to the partial
10374 // ordering rules of 14.5.5.2.
10375
10376 // The algorithm specified above is quadratic. We instead use a
10377 // two-pass algorithm (similar to the one used to identify the
10378 // best viable function in an overload set) that identifies the
10379 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010380
10381 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10382 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10383 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010384
Larisse Voufo98b20f12013-07-19 23:00:19 +000010385 // TODO: It looks like FailedCandidates does not serve much purpose
10386 // here, since the no_viable diagnostic has index 0.
10387 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010388 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010389 SourceExpr->getLocStart(), S.PDiag(),
10390 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10391 .second->getDeclName(),
10392 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10393 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010394
Douglas Gregorb491ed32011-02-19 21:32:49 +000010395 if (Result != MatchesCopy.end()) {
10396 // Make it the first and only element
10397 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10398 Matches[0].second = cast<FunctionDecl>(*Result);
10399 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010400 } else
10401 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010403
Douglas Gregorb491ed32011-02-19 21:32:49 +000010404 void EliminateAllTemplateMatches() {
10405 // [...] any function template specializations in the set are
10406 // eliminated if the set also contains a non-template function, [...]
10407 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010408 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010409 ++I;
10410 else {
10411 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010412 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010413 }
10414 }
10415 }
10416
Artem Belevich94a55e82015-09-22 17:22:59 +000010417 void EliminateSuboptimalCudaMatches() {
10418 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10419 }
10420
Douglas Gregorb491ed32011-02-19 21:32:49 +000010421public:
10422 void ComplainNoMatchesFound() const {
10423 assert(Matches.empty());
10424 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10425 << OvlExpr->getName() << TargetFunctionType
10426 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010427 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010428 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10429 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010430 else {
10431 // We have some deduction failure messages. Use them to diagnose
10432 // the function templates, and diagnose the non-template candidates
10433 // normally.
10434 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10435 IEnd = OvlExpr->decls_end();
10436 I != IEnd; ++I)
10437 if (FunctionDecl *Fun =
10438 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010439 if (!functionHasPassObjectSizeParams(Fun))
10440 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10441 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010442 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10443 }
10444 }
10445
Douglas Gregorb491ed32011-02-19 21:32:49 +000010446 bool IsInvalidFormOfPointerToMemberFunction() const {
10447 return TargetTypeIsNonStaticMemberFunction &&
10448 !OvlExprInfo.HasFormOfMemberPointer;
10449 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010450
Douglas Gregorb491ed32011-02-19 21:32:49 +000010451 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10452 // TODO: Should we condition this on whether any functions might
10453 // have matched, or is it more appropriate to do that in callers?
10454 // TODO: a fixit wouldn't hurt.
10455 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10456 << TargetType << OvlExpr->getSourceRange();
10457 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010458
10459 bool IsStaticMemberFunctionFromBoundPointer() const {
10460 return StaticMemberFunctionFromBoundPointer;
10461 }
10462
10463 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10464 S.Diag(OvlExpr->getLocStart(),
10465 diag::err_invalid_form_pointer_member_function)
10466 << OvlExpr->getSourceRange();
10467 }
10468
Douglas Gregorb491ed32011-02-19 21:32:49 +000010469 void ComplainOfInvalidConversion() const {
10470 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10471 << OvlExpr->getName() << TargetType;
10472 }
10473
10474 void ComplainMultipleMatchesFound() const {
10475 assert(Matches.size() > 1);
10476 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10477 << OvlExpr->getName()
10478 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010479 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10480 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010481 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010482
10483 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10484
Douglas Gregorb491ed32011-02-19 21:32:49 +000010485 int getNumMatches() const { return Matches.size(); }
10486
10487 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010488 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010489 return Matches[0].second;
10490 }
10491
10492 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010493 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010494 return &Matches[0].first;
10495 }
10496};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010497}
Richard Smith17c00b42014-11-12 01:24:00 +000010498
Douglas Gregorb491ed32011-02-19 21:32:49 +000010499/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10500/// an overloaded function (C++ [over.over]), where @p From is an
10501/// expression with overloaded function type and @p ToType is the type
10502/// we're trying to resolve to. For example:
10503///
10504/// @code
10505/// int f(double);
10506/// int f(int);
10507///
10508/// int (*pfd)(double) = f; // selects f(double)
10509/// @endcode
10510///
10511/// This routine returns the resulting FunctionDecl if it could be
10512/// resolved, and NULL otherwise. When @p Complain is true, this
10513/// routine will emit diagnostics if there is an error.
10514FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010515Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10516 QualType TargetType,
10517 bool Complain,
10518 DeclAccessPair &FoundResult,
10519 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010520 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010521
10522 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10523 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010524 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010525 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010526 bool ShouldComplain = Complain && !Resolver.hasComplained();
10527 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010528 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10529 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10530 else
10531 Resolver.ComplainNoMatchesFound();
10532 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010533 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010534 Resolver.ComplainMultipleMatchesFound();
10535 else if (NumMatches == 1) {
10536 Fn = Resolver.getMatchingFunctionDecl();
10537 assert(Fn);
10538 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010539 if (Complain) {
10540 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10541 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10542 else
10543 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10544 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010545 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010546
10547 if (pHadMultipleCandidates)
10548 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010549 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010550}
10551
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010552/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010553/// resolve that overloaded function expression down to a single function.
10554///
10555/// This routine can only resolve template-ids that refer to a single function
10556/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010557/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010558/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010559///
10560/// If no template-ids are found, no diagnostics are emitted and NULL is
10561/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010562FunctionDecl *
10563Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10564 bool Complain,
10565 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010566 // C++ [over.over]p1:
10567 // [...] [Note: any redundant set of parentheses surrounding the
10568 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010569 // C++ [over.over]p1:
10570 // [...] The overloaded function name can be preceded by the &
10571 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010572
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010573 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010574 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010575 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010576
10577 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010578 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010579 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010580
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010581 // Look through all of the overloaded functions, searching for one
10582 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010583 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010584 for (UnresolvedSetIterator I = ovl->decls_begin(),
10585 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010586 // C++0x [temp.arg.explicit]p3:
10587 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010588 // where deduction is not done, if a template argument list is
10589 // specified and it, along with any default template arguments,
10590 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010591 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010592 FunctionTemplateDecl *FunctionTemplate
10593 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010594
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010595 // C++ [over.over]p2:
10596 // If the name is a function template, template argument deduction is
10597 // done (14.8.2.2), and if the argument deduction succeeds, the
10598 // resulting template argument list is used to generate a single
10599 // function template specialization, which is added to the set of
10600 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010601 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010602 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010603 if (TemplateDeductionResult Result
10604 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010605 Specialization, Info,
10606 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010607 // Make a note of the failed deduction for diagnostics.
10608 // TODO: Actually use the failed-deduction info?
10609 FailedCandidates.addCandidate()
10610 .set(FunctionTemplate->getTemplatedDecl(),
10611 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010612 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010613 }
10614
John McCall0009fcc2011-04-26 20:42:42 +000010615 assert(Specialization && "no specialization and no error?");
10616
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010617 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010618 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010619 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010620 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10621 << ovl->getName();
10622 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010623 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010624 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010625 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010626
John McCall0009fcc2011-04-26 20:42:42 +000010627 Matched = Specialization;
10628 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010630
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010631 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010632 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010633 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010634 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010635
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010636 return Matched;
10637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010638
Douglas Gregor1beec452011-03-12 01:48:56 +000010639
10640
10641
John McCall50a2c2c2011-10-11 23:14:30 +000010642// Resolve and fix an overloaded expression that can be resolved
10643// because it identifies a single function template specialization.
10644//
Douglas Gregor1beec452011-03-12 01:48:56 +000010645// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010646//
10647// Return true if it was logically possible to so resolve the
10648// expression, regardless of whether or not it succeeded. Always
10649// returns true if 'complain' is set.
10650bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10651 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010652 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010653 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010654 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010655 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010656
John McCall50a2c2c2011-10-11 23:14:30 +000010657 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010658
John McCall0009fcc2011-04-26 20:42:42 +000010659 DeclAccessPair found;
10660 ExprResult SingleFunctionExpression;
10661 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10662 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010663 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010664 SrcExpr = ExprError();
10665 return true;
10666 }
John McCall0009fcc2011-04-26 20:42:42 +000010667
10668 // It is only correct to resolve to an instance method if we're
10669 // resolving a form that's permitted to be a pointer to member.
10670 // Otherwise we'll end up making a bound member expression, which
10671 // is illegal in all the contexts we resolve like this.
10672 if (!ovl.HasFormOfMemberPointer &&
10673 isa<CXXMethodDecl>(fn) &&
10674 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010675 if (!complain) return false;
10676
10677 Diag(ovl.Expression->getExprLoc(),
10678 diag::err_bound_member_function)
10679 << 0 << ovl.Expression->getSourceRange();
10680
10681 // TODO: I believe we only end up here if there's a mix of
10682 // static and non-static candidates (otherwise the expression
10683 // would have 'bound member' type, not 'overload' type).
10684 // Ideally we would note which candidate was chosen and why
10685 // the static candidates were rejected.
10686 SrcExpr = ExprError();
10687 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010688 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010689
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010690 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010691 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010692 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010693
10694 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010695 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010696 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010697 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010698 if (SingleFunctionExpression.isInvalid()) {
10699 SrcExpr = ExprError();
10700 return true;
10701 }
10702 }
John McCall0009fcc2011-04-26 20:42:42 +000010703 }
10704
10705 if (!SingleFunctionExpression.isUsable()) {
10706 if (complain) {
10707 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10708 << ovl.Expression->getName()
10709 << DestTypeForComplaining
10710 << OpRangeForComplaining
10711 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010712 NoteAllOverloadCandidates(SrcExpr.get());
10713
10714 SrcExpr = ExprError();
10715 return true;
10716 }
10717
10718 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010719 }
10720
John McCall50a2c2c2011-10-11 23:14:30 +000010721 SrcExpr = SingleFunctionExpression;
10722 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010723}
10724
Douglas Gregorcabea402009-09-22 15:41:20 +000010725/// \brief Add a single candidate to the overload set.
10726static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010727 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010728 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010729 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010730 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010731 bool PartialOverloading,
10732 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010733 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010734 if (isa<UsingShadowDecl>(Callee))
10735 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10736
Douglas Gregorcabea402009-09-22 15:41:20 +000010737 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010738 if (ExplicitTemplateArgs) {
10739 assert(!KnownValid && "Explicit template arguments?");
10740 return;
10741 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010742 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10743 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010744 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010745 return;
John McCalld14a8642009-11-21 08:51:07 +000010746 }
10747
10748 if (FunctionTemplateDecl *FuncTemplate
10749 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010750 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010751 ExplicitTemplateArgs, Args, CandidateSet,
10752 /*SuppressUsedConversions=*/false,
10753 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010754 return;
10755 }
10756
Richard Smith95ce4f62011-06-26 22:19:54 +000010757 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010758}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010759
Douglas Gregorcabea402009-09-22 15:41:20 +000010760/// \brief Add the overload candidates named by callee and/or found by argument
10761/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010762void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010763 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010764 OverloadCandidateSet &CandidateSet,
10765 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010766
10767#ifndef NDEBUG
10768 // Verify that ArgumentDependentLookup is consistent with the rules
10769 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010770 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010771 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10772 // and let Y be the lookup set produced by argument dependent
10773 // lookup (defined as follows). If X contains
10774 //
10775 // -- a declaration of a class member, or
10776 //
10777 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010778 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010779 //
10780 // -- a declaration that is neither a function or a function
10781 // template
10782 //
10783 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010784
John McCall57500772009-12-16 12:17:52 +000010785 if (ULE->requiresADL()) {
10786 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10787 E = ULE->decls_end(); I != E; ++I) {
10788 assert(!(*I)->getDeclContext()->isRecord());
10789 assert(isa<UsingShadowDecl>(*I) ||
10790 !(*I)->getDeclContext()->isFunctionOrMethod());
10791 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010792 }
10793 }
10794#endif
10795
John McCall57500772009-12-16 12:17:52 +000010796 // It would be nice to avoid this copy.
10797 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010798 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010799 if (ULE->hasExplicitTemplateArgs()) {
10800 ULE->copyTemplateArgumentsInto(TABuffer);
10801 ExplicitTemplateArgs = &TABuffer;
10802 }
10803
10804 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10805 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010806 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10807 CandidateSet, PartialOverloading,
10808 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010809
John McCall57500772009-12-16 12:17:52 +000010810 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010811 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010812 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010813 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010814}
John McCalld681c392009-12-16 08:11:27 +000010815
Richard Smith0603bbb2013-06-12 22:56:54 +000010816/// Determine whether a declaration with the specified name could be moved into
10817/// a different namespace.
10818static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10819 switch (Name.getCXXOverloadedOperator()) {
10820 case OO_New: case OO_Array_New:
10821 case OO_Delete: case OO_Array_Delete:
10822 return false;
10823
10824 default:
10825 return true;
10826 }
10827}
10828
Richard Smith998a5912011-06-05 22:42:48 +000010829/// Attempt to recover from an ill-formed use of a non-dependent name in a
10830/// template, where the non-dependent name was declared after the template
10831/// was defined. This is common in code written for a compilers which do not
10832/// correctly implement two-stage name lookup.
10833///
10834/// Returns true if a viable candidate was found and a diagnostic was issued.
10835static bool
10836DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10837 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010838 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010839 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010840 ArrayRef<Expr *> Args,
10841 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010842 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10843 return false;
10844
10845 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010846 if (DC->isTransparentContext())
10847 continue;
10848
Richard Smith998a5912011-06-05 22:42:48 +000010849 SemaRef.LookupQualifiedName(R, DC);
10850
10851 if (!R.empty()) {
10852 R.suppressDiagnostics();
10853
10854 if (isa<CXXRecordDecl>(DC)) {
10855 // Don't diagnose names we find in classes; we get much better
10856 // diagnostics for these from DiagnoseEmptyLookup.
10857 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010858 if (DoDiagnoseEmptyLookup)
10859 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010860 return false;
10861 }
10862
Richard Smith100b24a2014-04-17 01:52:14 +000010863 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010864 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10865 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010866 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010867 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010868
10869 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010870 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010871 // No viable functions. Don't bother the user with notes for functions
10872 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010873 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010874 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010875 }
Richard Smith998a5912011-06-05 22:42:48 +000010876
10877 // Find the namespaces where ADL would have looked, and suggest
10878 // declaring the function there instead.
10879 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10880 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010881 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010882 AssociatedNamespaces,
10883 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010884 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010885 if (canBeDeclaredInNamespace(R.getLookupName())) {
10886 DeclContext *Std = SemaRef.getStdNamespace();
10887 for (Sema::AssociatedNamespaceSet::iterator
10888 it = AssociatedNamespaces.begin(),
10889 end = AssociatedNamespaces.end(); it != end; ++it) {
10890 // Never suggest declaring a function within namespace 'std'.
10891 if (Std && Std->Encloses(*it))
10892 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010893
Richard Smith0603bbb2013-06-12 22:56:54 +000010894 // Never suggest declaring a function within a namespace with a
10895 // reserved name, like __gnu_cxx.
10896 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10897 if (NS &&
10898 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10899 continue;
10900
10901 SuggestedNamespaces.insert(*it);
10902 }
Richard Smith998a5912011-06-05 22:42:48 +000010903 }
10904
10905 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10906 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010907 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010908 SemaRef.Diag(Best->Function->getLocation(),
10909 diag::note_not_found_by_two_phase_lookup)
10910 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010911 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010912 SemaRef.Diag(Best->Function->getLocation(),
10913 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010914 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010915 } else {
10916 // FIXME: It would be useful to list the associated namespaces here,
10917 // but the diagnostics infrastructure doesn't provide a way to produce
10918 // a localized representation of a list of items.
10919 SemaRef.Diag(Best->Function->getLocation(),
10920 diag::note_not_found_by_two_phase_lookup)
10921 << R.getLookupName() << 2;
10922 }
10923
10924 // Try to recover by calling this function.
10925 return true;
10926 }
10927
10928 R.clear();
10929 }
10930
10931 return false;
10932}
10933
10934/// Attempt to recover from ill-formed use of a non-dependent operator in a
10935/// template, where the non-dependent operator was declared after the template
10936/// was defined.
10937///
10938/// Returns true if a viable candidate was found and a diagnostic was issued.
10939static bool
10940DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10941 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010942 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010943 DeclarationName OpName =
10944 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10945 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10946 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010947 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010948 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010949}
10950
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010951namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010952class BuildRecoveryCallExprRAII {
10953 Sema &SemaRef;
10954public:
10955 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10956 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10957 SemaRef.IsBuildingRecoveryCallExpr = true;
10958 }
10959
10960 ~BuildRecoveryCallExprRAII() {
10961 SemaRef.IsBuildingRecoveryCallExpr = false;
10962 }
10963};
10964
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010965}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010966
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010967static std::unique_ptr<CorrectionCandidateCallback>
10968MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10969 bool HasTemplateArgs, bool AllowTypoCorrection) {
10970 if (!AllowTypoCorrection)
10971 return llvm::make_unique<NoTypoCorrectionCCC>();
10972 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10973 HasTemplateArgs, ME);
10974}
10975
John McCalld681c392009-12-16 08:11:27 +000010976/// Attempts to recover from a call where no functions were found.
10977///
10978/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010979static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010980BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010981 UnresolvedLookupExpr *ULE,
10982 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010983 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010984 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010985 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010986 // Do not try to recover if it is already building a recovery call.
10987 // This stops infinite loops for template instantiations like
10988 //
10989 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10990 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10991 //
10992 if (SemaRef.IsBuildingRecoveryCallExpr)
10993 return ExprError();
10994 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010995
10996 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010997 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010998 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010999
John McCall57500772009-12-16 12:17:52 +000011000 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011001 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011002 if (ULE->hasExplicitTemplateArgs()) {
11003 ULE->copyTemplateArgumentsInto(TABuffer);
11004 ExplicitTemplateArgs = &TABuffer;
11005 }
11006
John McCalld681c392009-12-16 08:11:27 +000011007 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11008 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011009 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011010 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011011 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011012 ExplicitTemplateArgs, Args,
11013 &DoDiagnoseEmptyLookup) &&
11014 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11015 S, SS, R,
11016 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11017 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11018 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011019 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011020
John McCall57500772009-12-16 12:17:52 +000011021 assert(!R.empty() && "lookup results empty despite recovery");
11022
11023 // Build an implicit member call if appropriate. Just drop the
11024 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011025 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011026 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011027 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11028 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011029 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011030 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011031 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011032 else
11033 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11034
11035 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011036 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011037
11038 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011039 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011040 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011041 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011042 MultiExprArg(Args.data(), Args.size()),
11043 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011044}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011045
Sam Panzer0f384432012-08-21 00:52:01 +000011046/// \brief Constructs and populates an OverloadedCandidateSet from
11047/// the given function.
11048/// \returns true when an the ExprResult output parameter has been set.
11049bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11050 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011051 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011052 SourceLocation RParenLoc,
11053 OverloadCandidateSet *CandidateSet,
11054 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011055#ifndef NDEBUG
11056 if (ULE->requiresADL()) {
11057 // To do ADL, we must have found an unqualified name.
11058 assert(!ULE->getQualifier() && "qualified name with ADL");
11059
11060 // We don't perform ADL for implicit declarations of builtins.
11061 // Verify that this was correctly set up.
11062 FunctionDecl *F;
11063 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11064 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11065 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011066 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011067
John McCall57500772009-12-16 12:17:52 +000011068 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011069 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011070 }
John McCall57500772009-12-16 12:17:52 +000011071#endif
11072
John McCall4124c492011-10-17 18:40:02 +000011073 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011074 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011075 *Result = ExprError();
11076 return true;
11077 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011078
John McCall57500772009-12-16 12:17:52 +000011079 // Add the functions denoted by the callee to the set of candidate
11080 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011081 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011082
Hans Wennborgb2747382015-06-12 21:23:23 +000011083 if (getLangOpts().MSVCCompat &&
11084 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011085 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11086
11087 OverloadCandidateSet::iterator Best;
11088 if (CandidateSet->empty() ||
11089 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11090 OR_No_Viable_Function) {
11091 // In Microsoft mode, if we are inside a template class member function then
11092 // create a type dependent CallExpr. The goal is to postpone name lookup
11093 // to instantiation time to be able to search into type dependent base
11094 // classes.
11095 CallExpr *CE = new (Context) CallExpr(
11096 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011097 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011098 CE->setValueDependent(true);
11099 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011100 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011101 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011102 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011103 }
John McCalld681c392009-12-16 08:11:27 +000011104
Hans Wennborg64937c62015-06-11 21:21:57 +000011105 if (CandidateSet->empty())
11106 return false;
11107
John McCall4124c492011-10-17 18:40:02 +000011108 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011109 return false;
11110}
John McCall4124c492011-10-17 18:40:02 +000011111
Sam Panzer0f384432012-08-21 00:52:01 +000011112/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11113/// the completed call expression. If overload resolution fails, emits
11114/// diagnostics and returns ExprError()
11115static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11116 UnresolvedLookupExpr *ULE,
11117 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011118 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011119 SourceLocation RParenLoc,
11120 Expr *ExecConfig,
11121 OverloadCandidateSet *CandidateSet,
11122 OverloadCandidateSet::iterator *Best,
11123 OverloadingResult OverloadResult,
11124 bool AllowTypoCorrection) {
11125 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011126 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011127 RParenLoc, /*EmptyLookup=*/true,
11128 AllowTypoCorrection);
11129
11130 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011131 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011132 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011133 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011134 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11135 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011136 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011137 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11138 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011139 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011140
Richard Smith998a5912011-06-05 22:42:48 +000011141 case OR_No_Viable_Function: {
11142 // Try to recover by looking for viable functions which the user might
11143 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011144 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011145 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011146 /*EmptyLookup=*/false,
11147 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011148 if (!Recovery.isInvalid())
11149 return Recovery;
11150
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011151 // If the user passes in a function that we can't take the address of, we
11152 // generally end up emitting really bad error messages. Here, we attempt to
11153 // emit better ones.
11154 for (const Expr *Arg : Args) {
11155 if (!Arg->getType()->isFunctionType())
11156 continue;
11157 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11158 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11159 if (FD &&
11160 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11161 Arg->getExprLoc()))
11162 return ExprError();
11163 }
11164 }
11165
11166 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11167 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011168 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011169 break;
Richard Smith998a5912011-06-05 22:42:48 +000011170 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011171
11172 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011173 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011174 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011175 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011176 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011177
Sam Panzer0f384432012-08-21 00:52:01 +000011178 case OR_Deleted: {
11179 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11180 << (*Best)->Function->isDeleted()
11181 << ULE->getName()
11182 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11183 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011184 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011185
Sam Panzer0f384432012-08-21 00:52:01 +000011186 // We emitted an error for the unvailable/deleted function call but keep
11187 // the call in the AST.
11188 FunctionDecl *FDecl = (*Best)->Function;
11189 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011190 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11191 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011192 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011193 }
11194
Douglas Gregorb412e172010-07-25 18:17:45 +000011195 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011196 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011197}
11198
Sam Panzer0f384432012-08-21 00:52:01 +000011199/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11200/// (which eventually refers to the declaration Func) and the call
11201/// arguments Args/NumArgs, attempt to resolve the function call down
11202/// to a specific function. If overload resolution succeeds, returns
11203/// the call expression produced by overload resolution.
11204/// Otherwise, emits diagnostics and returns ExprError.
11205ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11206 UnresolvedLookupExpr *ULE,
11207 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011208 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011209 SourceLocation RParenLoc,
11210 Expr *ExecConfig,
11211 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000011212 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11213 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011214 ExprResult result;
11215
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011216 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11217 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011218 return result;
11219
11220 OverloadCandidateSet::iterator Best;
11221 OverloadingResult OverloadResult =
11222 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11223
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011224 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011225 RParenLoc, ExecConfig, &CandidateSet,
11226 &Best, OverloadResult,
11227 AllowTypoCorrection);
11228}
11229
John McCall4c4c1df2010-01-26 03:27:55 +000011230static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011231 return Functions.size() > 1 ||
11232 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11233}
11234
Douglas Gregor084d8552009-03-13 23:49:33 +000011235/// \brief Create a unary operation that may resolve to an overloaded
11236/// operator.
11237///
11238/// \param OpLoc The location of the operator itself (e.g., '*').
11239///
Craig Toppera92ffb02015-12-10 08:51:49 +000011240/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011241///
James Dennett18348b62012-06-22 08:52:37 +000011242/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011243/// considered by overload resolution. The caller needs to build this
11244/// set based on the context using, e.g.,
11245/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11246/// set should not contain any member functions; those will be added
11247/// by CreateOverloadedUnaryOp().
11248///
James Dennett91738ff2012-06-22 10:32:46 +000011249/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011250ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011251Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011252 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011253 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011254 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11255 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11256 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011257 // TODO: provide better source location info.
11258 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011259
John McCall4124c492011-10-17 18:40:02 +000011260 if (checkPlaceholderForOverload(*this, Input))
11261 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011262
Craig Topperc3ec1492014-05-26 06:22:03 +000011263 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011264 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011265
Douglas Gregor084d8552009-03-13 23:49:33 +000011266 // For post-increment and post-decrement, add the implicit '0' as
11267 // the second argument, so that we know this is a post-increment or
11268 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011269 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011270 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011271 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11272 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011273 NumArgs = 2;
11274 }
11275
Richard Smithe54c3072013-05-05 15:51:06 +000011276 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11277
Douglas Gregor084d8552009-03-13 23:49:33 +000011278 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011279 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011280 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11281 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011282
Craig Topperc3ec1492014-05-26 06:22:03 +000011283 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011284 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011285 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011286 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011287 /*ADL*/ true, IsOverloaded(Fns),
11288 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011289 return new (Context)
11290 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11291 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011292 }
11293
11294 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011295 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011296
11297 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011298 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011299
11300 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011301 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011302
John McCall4c4c1df2010-01-26 03:27:55 +000011303 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011304 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011305 /*ExplicitTemplateArgs*/nullptr,
11306 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011307
Douglas Gregor084d8552009-03-13 23:49:33 +000011308 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011309 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011310
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011311 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11312
Douglas Gregor084d8552009-03-13 23:49:33 +000011313 // Perform overload resolution.
11314 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011315 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011316 case OR_Success: {
11317 // We found a built-in operator or an overloaded operator.
11318 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011319
Douglas Gregor084d8552009-03-13 23:49:33 +000011320 if (FnDecl) {
11321 // We matched an overloaded operator. Build a call to that
11322 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011323
Douglas Gregor084d8552009-03-13 23:49:33 +000011324 // Convert the arguments.
11325 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011326 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011327
John Wiegley01296292011-04-08 18:41:53 +000011328 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011329 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011330 Best->FoundDecl, Method);
11331 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011332 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011333 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011334 } else {
11335 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011336 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011337 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011338 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011339 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011340 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011341 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011342 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011343 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011344 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011345 }
11346
Douglas Gregor084d8552009-03-13 23:49:33 +000011347 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011348 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011349 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011350 if (FnExpr.isInvalid())
11351 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011352
Richard Smithc1564702013-11-15 02:58:23 +000011353 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011354 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011355 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11356 ResultTy = ResultTy.getNonLValueExprType(Context);
11357
Eli Friedman030eee42009-11-18 03:58:17 +000011358 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011359 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011360 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011361 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011362
Alp Toker314cc812014-01-25 16:55:45 +000011363 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011364 return ExprError();
11365
John McCallb268a282010-08-23 23:25:46 +000011366 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011367 } else {
11368 // We matched a built-in operator. Convert the arguments, then
11369 // break out so that we will build the appropriate built-in
11370 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011371 ExprResult InputRes =
11372 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11373 Best->Conversions[0], AA_Passing);
11374 if (InputRes.isInvalid())
11375 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011376 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011377 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011378 }
John Wiegley01296292011-04-08 18:41:53 +000011379 }
11380
11381 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011382 // This is an erroneous use of an operator which can be overloaded by
11383 // a non-member function. Check for non-member operators which were
11384 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011385 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011386 // FIXME: Recover by calling the found function.
11387 return ExprError();
11388
John Wiegley01296292011-04-08 18:41:53 +000011389 // No viable function; fall through to handling this as a
11390 // built-in operator, which will produce an error message for us.
11391 break;
11392
11393 case OR_Ambiguous:
11394 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11395 << UnaryOperator::getOpcodeStr(Opc)
11396 << Input->getType()
11397 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011398 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011399 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11400 return ExprError();
11401
11402 case OR_Deleted:
11403 Diag(OpLoc, diag::err_ovl_deleted_oper)
11404 << Best->Function->isDeleted()
11405 << UnaryOperator::getOpcodeStr(Opc)
11406 << getDeletedOrUnavailableSuffix(Best->Function)
11407 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011408 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011409 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011410 return ExprError();
11411 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011412
11413 // Either we found no viable overloaded operator or we matched a
11414 // built-in operator. In either case, fall through to trying to
11415 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011416 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011417}
11418
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011419/// \brief Create a binary operation that may resolve to an overloaded
11420/// operator.
11421///
11422/// \param OpLoc The location of the operator itself (e.g., '+').
11423///
Craig Toppera92ffb02015-12-10 08:51:49 +000011424/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011425///
James Dennett18348b62012-06-22 08:52:37 +000011426/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011427/// considered by overload resolution. The caller needs to build this
11428/// set based on the context using, e.g.,
11429/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11430/// set should not contain any member functions; those will be added
11431/// by CreateOverloadedBinOp().
11432///
11433/// \param LHS Left-hand argument.
11434/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011435ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011436Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011437 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011438 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011439 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011440 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011441 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011442
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011443 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11444 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11445
11446 // If either side is type-dependent, create an appropriate dependent
11447 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011448 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011449 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011450 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011451 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011452 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011453 return new (Context) BinaryOperator(
11454 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11455 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011456
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011457 return new (Context) CompoundAssignOperator(
11458 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11459 Context.DependentTy, Context.DependentTy, OpLoc,
11460 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011461 }
John McCall4c4c1df2010-01-26 03:27:55 +000011462
11463 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011464 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011465 // TODO: provide better source location info in DNLoc component.
11466 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011467 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011468 = UnresolvedLookupExpr::Create(Context, NamingClass,
11469 NestedNameSpecifierLoc(), OpNameInfo,
11470 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011471 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011472 return new (Context)
11473 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11474 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011475 }
11476
John McCall4124c492011-10-17 18:40:02 +000011477 // Always do placeholder-like conversions on the RHS.
11478 if (checkPlaceholderForOverload(*this, Args[1]))
11479 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011480
John McCall526ab472011-10-25 17:37:35 +000011481 // Do placeholder-like conversion on the LHS; note that we should
11482 // not get here with a PseudoObject LHS.
11483 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011484 if (checkPlaceholderForOverload(*this, Args[0]))
11485 return ExprError();
11486
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011487 // If this is the assignment operator, we only perform overload resolution
11488 // if the left-hand side is a class or enumeration type. This is actually
11489 // a hack. The standard requires that we do overload resolution between the
11490 // various built-in candidates, but as DR507 points out, this can lead to
11491 // problems. So we do it this way, which pretty much follows what GCC does.
11492 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011493 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011494 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011495
John McCalle26a8722010-12-04 08:14:53 +000011496 // If this is the .* operator, which is not overloadable, just
11497 // create a built-in binary operator.
11498 if (Opc == BO_PtrMemD)
11499 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11500
Douglas Gregor084d8552009-03-13 23:49:33 +000011501 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011502 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011503
11504 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011505 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011506
11507 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011508 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011509
Richard Smith0daabd72014-09-23 20:31:39 +000011510 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11511 // performed for an assignment operator (nor for operator[] nor operator->,
11512 // which don't get here).
11513 if (Opc != BO_Assign)
11514 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11515 /*ExplicitTemplateArgs*/ nullptr,
11516 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011517
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011518 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011519 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011520
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011521 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11522
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011523 // Perform overload resolution.
11524 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011525 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011526 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011527 // We found a built-in operator or an overloaded operator.
11528 FunctionDecl *FnDecl = Best->Function;
11529
11530 if (FnDecl) {
11531 // We matched an overloaded operator. Build a call to that
11532 // operator.
11533
11534 // Convert the arguments.
11535 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011536 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011537 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011538
Chandler Carruth8e543b32010-12-12 08:17:55 +000011539 ExprResult Arg1 =
11540 PerformCopyInitialization(
11541 InitializedEntity::InitializeParameter(Context,
11542 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011543 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011544 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011545 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011546
John Wiegley01296292011-04-08 18:41:53 +000011547 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011548 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011549 Best->FoundDecl, Method);
11550 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011551 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011552 Args[0] = Arg0.getAs<Expr>();
11553 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011554 } else {
11555 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011556 ExprResult Arg0 = PerformCopyInitialization(
11557 InitializedEntity::InitializeParameter(Context,
11558 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011559 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011560 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011561 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011562
Chandler Carruth8e543b32010-12-12 08:17:55 +000011563 ExprResult Arg1 =
11564 PerformCopyInitialization(
11565 InitializedEntity::InitializeParameter(Context,
11566 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011567 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011568 if (Arg1.isInvalid())
11569 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011570 Args[0] = LHS = Arg0.getAs<Expr>();
11571 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011572 }
11573
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011574 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011575 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011576 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011577 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011578 if (FnExpr.isInvalid())
11579 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011580
Richard Smithc1564702013-11-15 02:58:23 +000011581 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011582 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011583 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11584 ResultTy = ResultTy.getNonLValueExprType(Context);
11585
John McCallb268a282010-08-23 23:25:46 +000011586 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011587 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011588 Args, ResultTy, VK, OpLoc,
11589 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011590
Alp Toker314cc812014-01-25 16:55:45 +000011591 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011592 FnDecl))
11593 return ExprError();
11594
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011595 ArrayRef<const Expr *> ArgsArray(Args, 2);
11596 // Cut off the implicit 'this'.
11597 if (isa<CXXMethodDecl>(FnDecl))
11598 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011599
11600 // Check for a self move.
11601 if (Op == OO_Equal)
11602 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11603
Douglas Gregorb4866e82015-06-19 18:13:19 +000011604 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011605 TheCall->getSourceRange(), VariadicDoesNotApply);
11606
John McCallb268a282010-08-23 23:25:46 +000011607 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011608 } else {
11609 // We matched a built-in operator. Convert the arguments, then
11610 // break out so that we will build the appropriate built-in
11611 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011612 ExprResult ArgsRes0 =
11613 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11614 Best->Conversions[0], AA_Passing);
11615 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011616 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011617 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011618
John Wiegley01296292011-04-08 18:41:53 +000011619 ExprResult ArgsRes1 =
11620 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11621 Best->Conversions[1], AA_Passing);
11622 if (ArgsRes1.isInvalid())
11623 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011624 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011625 break;
11626 }
11627 }
11628
Douglas Gregor66950a32009-09-30 21:46:01 +000011629 case OR_No_Viable_Function: {
11630 // C++ [over.match.oper]p9:
11631 // If the operator is the operator , [...] and there are no
11632 // viable functions, then the operator is assumed to be the
11633 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011634 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011635 break;
11636
Chandler Carruth8e543b32010-12-12 08:17:55 +000011637 // For class as left operand for assignment or compound assigment
11638 // operator do not fall through to handling in built-in, but report that
11639 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011640 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011641 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011642 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011643 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11644 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011645 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011646 if (Args[0]->getType()->isIncompleteType()) {
11647 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11648 << Args[0]->getType()
11649 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11650 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011651 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011652 // This is an erroneous use of an operator which can be overloaded by
11653 // a non-member function. Check for non-member operators which were
11654 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011655 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011656 // FIXME: Recover by calling the found function.
11657 return ExprError();
11658
Douglas Gregor66950a32009-09-30 21:46:01 +000011659 // No viable function; try to create a built-in operation, which will
11660 // produce an error. Then, show the non-viable candidates.
11661 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011663 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011664 "C++ binary operator overloading is missing candidates!");
11665 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011666 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011667 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011668 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011669 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011670
11671 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011672 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011673 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011674 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011675 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011676 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011677 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011678 return ExprError();
11679
11680 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011681 if (isImplicitlyDeleted(Best->Function)) {
11682 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11683 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011684 << Context.getRecordType(Method->getParent())
11685 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011686
Richard Smithde1a4872012-12-28 12:23:24 +000011687 // The user probably meant to call this special member. Just
11688 // explain why it's deleted.
11689 NoteDeletedFunction(Method);
11690 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011691 } else {
11692 Diag(OpLoc, diag::err_ovl_deleted_oper)
11693 << Best->Function->isDeleted()
11694 << BinaryOperator::getOpcodeStr(Opc)
11695 << getDeletedOrUnavailableSuffix(Best->Function)
11696 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11697 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011698 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011699 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011700 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011701 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011702
Douglas Gregor66950a32009-09-30 21:46:01 +000011703 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011704 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011705}
11706
John McCalldadc5752010-08-24 06:29:42 +000011707ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011708Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11709 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011710 Expr *Base, Expr *Idx) {
11711 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011712 DeclarationName OpName =
11713 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11714
11715 // If either side is type-dependent, create an appropriate dependent
11716 // expression.
11717 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11718
Craig Topperc3ec1492014-05-26 06:22:03 +000011719 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011720 // CHECKME: no 'operator' keyword?
11721 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11722 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011723 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011724 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011725 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011726 /*ADL*/ true, /*Overloaded*/ false,
11727 UnresolvedSetIterator(),
11728 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011729 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011730
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011731 return new (Context)
11732 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11733 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011734 }
11735
John McCall4124c492011-10-17 18:40:02 +000011736 // Handle placeholders on both operands.
11737 if (checkPlaceholderForOverload(*this, Args[0]))
11738 return ExprError();
11739 if (checkPlaceholderForOverload(*this, Args[1]))
11740 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011741
Sebastian Redladba46e2009-10-29 20:17:01 +000011742 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011743 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011744
11745 // Subscript can only be overloaded as a member function.
11746
11747 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011748 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011749
11750 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011751 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011752
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11754
Sebastian Redladba46e2009-10-29 20:17:01 +000011755 // Perform overload resolution.
11756 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011757 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011758 case OR_Success: {
11759 // We found a built-in operator or an overloaded operator.
11760 FunctionDecl *FnDecl = Best->Function;
11761
11762 if (FnDecl) {
11763 // We matched an overloaded operator. Build a call to that
11764 // operator.
11765
John McCalla0296f72010-03-19 07:35:19 +000011766 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011767
Sebastian Redladba46e2009-10-29 20:17:01 +000011768 // Convert the arguments.
11769 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011770 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011771 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011772 Best->FoundDecl, Method);
11773 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011774 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011775 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011776
Anders Carlssona68e51e2010-01-29 18:37:50 +000011777 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011778 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011779 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011780 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011781 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011782 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011783 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011784 if (InputInit.isInvalid())
11785 return ExprError();
11786
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011787 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011788
Sebastian Redladba46e2009-10-29 20:17:01 +000011789 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011790 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11791 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011792 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011793 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011794 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011795 OpLocInfo.getLoc(),
11796 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011797 if (FnExpr.isInvalid())
11798 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011799
Richard Smithc1564702013-11-15 02:58:23 +000011800 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011801 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011802 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11803 ResultTy = ResultTy.getNonLValueExprType(Context);
11804
John McCallb268a282010-08-23 23:25:46 +000011805 CXXOperatorCallExpr *TheCall =
11806 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011807 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011808 ResultTy, VK, RLoc,
11809 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011810
Alp Toker314cc812014-01-25 16:55:45 +000011811 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011812 return ExprError();
11813
John McCallb268a282010-08-23 23:25:46 +000011814 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011815 } else {
11816 // We matched a built-in operator. Convert the arguments, then
11817 // break out so that we will build the appropriate built-in
11818 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011819 ExprResult ArgsRes0 =
11820 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11821 Best->Conversions[0], AA_Passing);
11822 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011823 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011824 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011825
11826 ExprResult ArgsRes1 =
11827 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11828 Best->Conversions[1], AA_Passing);
11829 if (ArgsRes1.isInvalid())
11830 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011831 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011832
11833 break;
11834 }
11835 }
11836
11837 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011838 if (CandidateSet.empty())
11839 Diag(LLoc, diag::err_ovl_no_oper)
11840 << Args[0]->getType() << /*subscript*/ 0
11841 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11842 else
11843 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11844 << Args[0]->getType()
11845 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011846 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011847 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011848 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011849 }
11850
11851 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011852 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011853 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011854 << Args[0]->getType() << Args[1]->getType()
11855 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011856 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011857 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011858 return ExprError();
11859
11860 case OR_Deleted:
11861 Diag(LLoc, diag::err_ovl_deleted_oper)
11862 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011863 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011864 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011865 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011866 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011867 return ExprError();
11868 }
11869
11870 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011871 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011872}
11873
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011874/// BuildCallToMemberFunction - Build a call to a member
11875/// function. MemExpr is the expression that refers to the member
11876/// function (and includes the object parameter), Args/NumArgs are the
11877/// arguments to the function call (not including the object
11878/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011879/// expression refers to a non-static member function or an overloaded
11880/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011881ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011882Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011883 SourceLocation LParenLoc,
11884 MultiExprArg Args,
11885 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011886 assert(MemExprE->getType() == Context.BoundMemberTy ||
11887 MemExprE->getType() == Context.OverloadTy);
11888
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011889 // Dig out the member expression. This holds both the object
11890 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011891 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011892
John McCall0009fcc2011-04-26 20:42:42 +000011893 // Determine whether this is a call to a pointer-to-member function.
11894 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11895 assert(op->getType() == Context.BoundMemberTy);
11896 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11897
11898 QualType fnType =
11899 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11900
11901 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11902 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011903 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011904
11905 // Check that the object type isn't more qualified than the
11906 // member function we're calling.
11907 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11908
11909 QualType objectType = op->getLHS()->getType();
11910 if (op->getOpcode() == BO_PtrMemI)
11911 objectType = objectType->castAs<PointerType>()->getPointeeType();
11912 Qualifiers objectQuals = objectType.getQualifiers();
11913
11914 Qualifiers difference = objectQuals - funcQuals;
11915 difference.removeObjCGCAttr();
11916 difference.removeAddressSpace();
11917 if (difference) {
11918 std::string qualsString = difference.getAsString();
11919 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11920 << fnType.getUnqualifiedType()
11921 << qualsString
11922 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11923 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011924
John McCall0009fcc2011-04-26 20:42:42 +000011925 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011926 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011927 resultType, valueKind, RParenLoc);
11928
Alp Toker314cc812014-01-25 16:55:45 +000011929 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011930 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011931 return ExprError();
11932
Craig Topperc3ec1492014-05-26 06:22:03 +000011933 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011934 return ExprError();
11935
Richard Trieu9be9c682013-06-22 02:30:38 +000011936 if (CheckOtherCall(call, proto))
11937 return ExprError();
11938
John McCall0009fcc2011-04-26 20:42:42 +000011939 return MaybeBindToTemporary(call);
11940 }
11941
David Majnemerced8bdf2015-02-25 17:36:15 +000011942 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11943 return new (Context)
11944 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11945
John McCall4124c492011-10-17 18:40:02 +000011946 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011947 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011948 return ExprError();
11949
John McCall10eae182009-11-30 22:42:35 +000011950 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011951 CXXMethodDecl *Method = nullptr;
11952 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11953 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011954 if (isa<MemberExpr>(NakedMemExpr)) {
11955 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011956 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011957 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011958 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011959 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011960 } else {
11961 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011962 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011963
John McCall6e9f8f62009-12-03 04:06:58 +000011964 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011965 Expr::Classification ObjectClassification
11966 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11967 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011968
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011969 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011970 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11971 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011972
John McCall2d74de92009-12-01 22:10:20 +000011973 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011974 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011975 if (UnresExpr->hasExplicitTemplateArgs()) {
11976 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11977 TemplateArgs = &TemplateArgsBuffer;
11978 }
11979
John McCall10eae182009-11-30 22:42:35 +000011980 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11981 E = UnresExpr->decls_end(); I != E; ++I) {
11982
John McCall6e9f8f62009-12-03 04:06:58 +000011983 NamedDecl *Func = *I;
11984 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11985 if (isa<UsingShadowDecl>(Func))
11986 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11987
Douglas Gregor02824322011-01-26 19:30:28 +000011988
Francois Pichet64225792011-01-18 05:04:39 +000011989 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011990 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011991 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011992 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011993 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011994 // If explicit template arguments were provided, we can't call a
11995 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011996 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011997 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011998
John McCalla0296f72010-03-19 07:35:19 +000011999 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012000 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012001 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012002 } else {
John McCall10eae182009-11-30 22:42:35 +000012003 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012004 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012005 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012006 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012007 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012008 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012009 }
Mike Stump11289f42009-09-09 15:08:12 +000012010
John McCall10eae182009-11-30 22:42:35 +000012011 DeclarationName DeclName = UnresExpr->getMemberName();
12012
John McCall4124c492011-10-17 18:40:02 +000012013 UnbridgedCasts.restore();
12014
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012015 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012016 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012017 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012018 case OR_Success:
12019 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012020 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012021 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012022 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12023 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012024 // If FoundDecl is different from Method (such as if one is a template
12025 // and the other a specialization), make sure DiagnoseUseOfDecl is
12026 // called on both.
12027 // FIXME: This would be more comprehensively addressed by modifying
12028 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12029 // being used.
12030 if (Method != FoundDecl.getDecl() &&
12031 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12032 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012033 break;
12034
12035 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012036 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012037 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012038 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012039 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012040 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012041 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012042
12043 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012044 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012045 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012046 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012047 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012048 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012049
12050 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012051 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012052 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012053 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012054 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012055 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012056 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012057 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012058 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012059 }
12060
John McCall16df1e52010-03-30 21:47:33 +000012061 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012062
John McCall2d74de92009-12-01 22:10:20 +000012063 // If overload resolution picked a static member, build a
12064 // non-member call based on that function.
12065 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012066 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12067 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012068 }
12069
John McCall10eae182009-11-30 22:42:35 +000012070 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012071 }
12072
Alp Toker314cc812014-01-25 16:55:45 +000012073 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012074 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12075 ResultType = ResultType.getNonLValueExprType(Context);
12076
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012077 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012078 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012079 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012080 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012081
Eli Bendersky291a57e2014-09-25 23:59:08 +000012082 // (CUDA B.1): Check for invalid calls between targets.
12083 if (getLangOpts().CUDA) {
12084 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12085 if (CheckCUDATarget(Caller, Method)) {
12086 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12087 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12088 << IdentifyCUDATarget(Caller);
12089 return ExprError();
12090 }
12091 }
12092 }
12093
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012094 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012095 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012096 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012097 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012098
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012099 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012100 // We only need to do this if there was actually an overload; otherwise
12101 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012102 if (!Method->isStatic()) {
12103 ExprResult ObjectArg =
12104 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12105 FoundDecl, Method);
12106 if (ObjectArg.isInvalid())
12107 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012108 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012109 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012110
12111 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012112 const FunctionProtoType *Proto =
12113 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012114 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012115 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012116 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012117
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012118 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012119
Richard Smith55ce3522012-06-25 20:30:08 +000012120 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012121 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012122
George Burgess IVaea6ade2015-09-25 17:53:16 +000012123 // In the case the method to call was not selected by the overloading
12124 // resolution process, we still need to handle the enable_if attribute. Do
12125 // that here, so it will not hide previous -- and more relevant -- errors
12126 if (isa<MemberExpr>(NakedMemExpr)) {
12127 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12128 Diag(MemExprE->getLocStart(),
12129 diag::err_ovl_no_viable_member_function_in_call)
12130 << Method << Method->getSourceRange();
12131 Diag(Method->getLocation(),
12132 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12133 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12134 return ExprError();
12135 }
12136 }
12137
Anders Carlsson47061ee2011-05-06 14:25:31 +000012138 if ((isa<CXXConstructorDecl>(CurContext) ||
12139 isa<CXXDestructorDecl>(CurContext)) &&
12140 TheCall->getMethodDecl()->isPure()) {
12141 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12142
Davide Italianoccb37382015-07-14 23:36:10 +000012143 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12144 MemExpr->performsVirtualDispatch(getLangOpts())) {
12145 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012146 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12147 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12148 << MD->getParent()->getDeclName();
12149
12150 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012151 if (getLangOpts().AppleKext)
12152 Diag(MemExpr->getLocStart(),
12153 diag::note_pure_qualified_call_kext)
12154 << MD->getParent()->getDeclName()
12155 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012156 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012157 }
John McCallb268a282010-08-23 23:25:46 +000012158 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012159}
12160
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012161/// BuildCallToObjectOfClassType - Build a call to an object of class
12162/// type (C++ [over.call.object]), which can end up invoking an
12163/// overloaded function call operator (@c operator()) or performing a
12164/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012165ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012166Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012167 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012168 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012169 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012170 if (checkPlaceholderForOverload(*this, Obj))
12171 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012172 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012173
12174 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012175 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012176 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012177
Nico Weberb58e51c2014-11-19 05:21:39 +000012178 assert(Object.get()->getType()->isRecordType() &&
12179 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012180 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012181
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012182 // C++ [over.call.object]p1:
12183 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012184 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012185 // candidate functions includes at least the function call
12186 // operators of T. The function call operators of T are obtained by
12187 // ordinary lookup of the name operator() in the context of
12188 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012189 OverloadCandidateSet CandidateSet(LParenLoc,
12190 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012191 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012192
John Wiegley01296292011-04-08 18:41:53 +000012193 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012194 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012195 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012196
John McCall27b18f82009-11-17 02:14:36 +000012197 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12198 LookupQualifiedName(R, Record->getDecl());
12199 R.suppressDiagnostics();
12200
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012201 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012202 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012203 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012204 Object.get()->Classify(Context),
12205 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012206 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012208
Douglas Gregorab7897a2008-11-19 22:57:39 +000012209 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012210 // In addition, for each (non-explicit in C++0x) conversion function
12211 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012212 //
12213 // operator conversion-type-id () cv-qualifier;
12214 //
12215 // where cv-qualifier is the same cv-qualification as, or a
12216 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012217 // denotes the type "pointer to function of (P1,...,Pn) returning
12218 // R", or the type "reference to pointer to function of
12219 // (P1,...,Pn) returning R", or the type "reference to function
12220 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012221 // is also considered as a candidate function. Similarly,
12222 // surrogate call functions are added to the set of candidate
12223 // functions for each conversion function declared in an
12224 // accessible base class provided the function is not hidden
12225 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012226 const auto &Conversions =
12227 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12228 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012229 NamedDecl *D = *I;
12230 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12231 if (isa<UsingShadowDecl>(D))
12232 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012233
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012234 // Skip over templated conversion functions; they aren't
12235 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012236 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012237 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012238
John McCall6e9f8f62009-12-03 04:06:58 +000012239 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012240 if (!Conv->isExplicit()) {
12241 // Strip the reference type (if any) and then the pointer type (if
12242 // any) to get down to what might be a function type.
12243 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12244 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12245 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012246
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012247 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12248 {
12249 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012250 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012251 }
12252 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012253 }
Mike Stump11289f42009-09-09 15:08:12 +000012254
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012255 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12256
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012257 // Perform overload resolution.
12258 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012259 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012260 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012261 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012262 // Overload resolution succeeded; we'll build the appropriate call
12263 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012264 break;
12265
12266 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012267 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012268 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012269 << Object.get()->getType() << /*call*/ 1
12270 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012271 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012272 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012273 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012274 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012276 break;
12277
12278 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012279 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012280 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012281 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012282 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012283 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012284
12285 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012286 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012287 diag::err_ovl_deleted_object_call)
12288 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012289 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012290 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012291 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012293 break;
Mike Stump11289f42009-09-09 15:08:12 +000012294 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012295
Douglas Gregorb412e172010-07-25 18:17:45 +000012296 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012297 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012298
John McCall4124c492011-10-17 18:40:02 +000012299 UnbridgedCasts.restore();
12300
Craig Topperc3ec1492014-05-26 06:22:03 +000012301 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012302 // Since there is no function declaration, this is one of the
12303 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012304 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012305 = cast<CXXConversionDecl>(
12306 Best->Conversions[0].UserDefined.ConversionFunction);
12307
Craig Topperc3ec1492014-05-26 06:22:03 +000012308 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12309 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012310 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12311 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012312 assert(Conv == Best->FoundDecl.getDecl() &&
12313 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012314 // We selected one of the surrogate functions that converts the
12315 // object parameter to a function pointer. Perform the conversion
12316 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012317
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012318 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012319 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012320 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12321 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012322 if (Call.isInvalid())
12323 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012324 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012325 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12326 CK_UserDefinedConversion, Call.get(),
12327 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012328
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012329 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012330 }
12331
Craig Topperc3ec1492014-05-26 06:22:03 +000012332 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012333
Douglas Gregorab7897a2008-11-19 22:57:39 +000012334 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12335 // that calls this method, using Object for the implicit object
12336 // parameter and passing along the remaining arguments.
12337 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012338
12339 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012340 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012341 return ExprError();
12342
Chandler Carruth8e543b32010-12-12 08:17:55 +000012343 const FunctionProtoType *Proto =
12344 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012345
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012346 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012347
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012348 DeclarationNameInfo OpLocInfo(
12349 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12350 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012351 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012352 HadMultipleCandidates,
12353 OpLocInfo.getLoc(),
12354 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012355 if (NewFn.isInvalid())
12356 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012357
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012358 // Build the full argument list for the method call (the implicit object
12359 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012360 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012361 MethodArgs[0] = Object.get();
12362 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12363
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012364 // Once we've built TheCall, all of the expressions are properly
12365 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012366 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012367 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12368 ResultTy = ResultTy.getNonLValueExprType(Context);
12369
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012370 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012371 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012372 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12373 ResultTy, VK, RParenLoc, false);
12374 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012375
Alp Toker314cc812014-01-25 16:55:45 +000012376 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012377 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012378
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012379 // We may have default arguments. If so, we need to allocate more
12380 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012381 if (Args.size() < NumParams)
12382 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012383
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012384 bool IsError = false;
12385
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012386 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012387 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012388 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012389 Best->FoundDecl, Method);
12390 if (ObjRes.isInvalid())
12391 IsError = true;
12392 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012393 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012394 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012395
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012396 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012397 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012398 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012399 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012400 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012401
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012402 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012403
John McCalldadc5752010-08-24 06:29:42 +000012404 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012405 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012406 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012407 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012408 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012409
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012410 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012411 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012412 } else {
John McCalldadc5752010-08-24 06:29:42 +000012413 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012414 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12415 if (DefArg.isInvalid()) {
12416 IsError = true;
12417 break;
12418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012419
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012420 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012421 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012422
12423 TheCall->setArg(i + 1, Arg);
12424 }
12425
12426 // If this is a variadic call, handle args passed through "...".
12427 if (Proto->isVariadic()) {
12428 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012429 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012430 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12431 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012432 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012433 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012434 }
12435 }
12436
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012437 if (IsError) return true;
12438
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012439 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012440
Richard Smith55ce3522012-06-25 20:30:08 +000012441 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012442 return true;
12443
John McCalle172be52010-08-24 06:09:16 +000012444 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012445}
12446
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012447/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012448/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012449/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012450ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012451Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12452 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012453 assert(Base->getType()->isRecordType() &&
12454 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012455
John McCall4124c492011-10-17 18:40:02 +000012456 if (checkPlaceholderForOverload(*this, Base))
12457 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012458
John McCallbc077cf2010-02-08 23:07:23 +000012459 SourceLocation Loc = Base->getExprLoc();
12460
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012461 // C++ [over.ref]p1:
12462 //
12463 // [...] An expression x->m is interpreted as (x.operator->())->m
12464 // for a class object x of type T if T::operator->() exists and if
12465 // the operator is selected as the best match function by the
12466 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012467 DeclarationName OpName =
12468 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012469 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012470 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012471
John McCallbc077cf2010-02-08 23:07:23 +000012472 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012473 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012474 return ExprError();
12475
John McCall27b18f82009-11-17 02:14:36 +000012476 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12477 LookupQualifiedName(R, BaseRecord->getDecl());
12478 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012479
12480 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012481 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012482 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012483 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012484 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012485
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012486 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12487
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012488 // Perform overload resolution.
12489 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012490 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012491 case OR_Success:
12492 // Overload resolution succeeded; we'll build the call below.
12493 break;
12494
12495 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012496 if (CandidateSet.empty()) {
12497 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012498 if (NoArrowOperatorFound) {
12499 // Report this specific error to the caller instead of emitting a
12500 // diagnostic, as requested.
12501 *NoArrowOperatorFound = true;
12502 return ExprError();
12503 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012504 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12505 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012506 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012507 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012508 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012509 }
12510 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012511 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012512 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012513 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012514 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012515
12516 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012517 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12518 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012519 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012520 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012521
12522 case OR_Deleted:
12523 Diag(OpLoc, diag::err_ovl_deleted_oper)
12524 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012525 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012526 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012527 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012529 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012530 }
12531
Craig Topperc3ec1492014-05-26 06:22:03 +000012532 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012533
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012534 // Convert the object parameter.
12535 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012536 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012537 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012538 Best->FoundDecl, Method);
12539 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012540 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012541 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012542
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012543 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012544 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012545 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012546 if (FnExpr.isInvalid())
12547 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012548
Alp Toker314cc812014-01-25 16:55:45 +000012549 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012550 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12551 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012552 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012553 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012554 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012555
Alp Toker314cc812014-01-25 16:55:45 +000012556 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012557 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012558
12559 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012560}
12561
Richard Smithbcc22fc2012-03-09 08:00:36 +000012562/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12563/// a literal operator described by the provided lookup results.
12564ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12565 DeclarationNameInfo &SuffixInfo,
12566 ArrayRef<Expr*> Args,
12567 SourceLocation LitEndLoc,
12568 TemplateArgumentListInfo *TemplateArgs) {
12569 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012570
Richard Smith100b24a2014-04-17 01:52:14 +000012571 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12572 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012573 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12574 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012575
Richard Smithbcc22fc2012-03-09 08:00:36 +000012576 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12577
Richard Smithbcc22fc2012-03-09 08:00:36 +000012578 // Perform overload resolution. This will usually be trivial, but might need
12579 // to perform substitutions for a literal operator template.
12580 OverloadCandidateSet::iterator Best;
12581 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12582 case OR_Success:
12583 case OR_Deleted:
12584 break;
12585
12586 case OR_No_Viable_Function:
12587 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12588 << R.getLookupName();
12589 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12590 return ExprError();
12591
12592 case OR_Ambiguous:
12593 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12594 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12595 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012596 }
12597
Richard Smithbcc22fc2012-03-09 08:00:36 +000012598 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012599 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12600 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012601 SuffixInfo.getLoc(),
12602 SuffixInfo.getInfo());
12603 if (Fn.isInvalid())
12604 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012605
12606 // Check the argument types. This should almost always be a no-op, except
12607 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012608 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012609 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012610 ExprResult InputInit = PerformCopyInitialization(
12611 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12612 SourceLocation(), Args[ArgIdx]);
12613 if (InputInit.isInvalid())
12614 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012615 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012616 }
12617
Alp Toker314cc812014-01-25 16:55:45 +000012618 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012619 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12620 ResultTy = ResultTy.getNonLValueExprType(Context);
12621
Richard Smithc67fdd42012-03-07 08:35:16 +000012622 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012623 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012624 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012625 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12626
Alp Toker314cc812014-01-25 16:55:45 +000012627 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012628 return ExprError();
12629
Craig Topperc3ec1492014-05-26 06:22:03 +000012630 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012631 return ExprError();
12632
12633 return MaybeBindToTemporary(UDL);
12634}
12635
Sam Panzer0f384432012-08-21 00:52:01 +000012636/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12637/// given LookupResult is non-empty, it is assumed to describe a member which
12638/// will be invoked. Otherwise, the function will be found via argument
12639/// dependent lookup.
12640/// CallExpr is set to a valid expression and FRS_Success returned on success,
12641/// otherwise CallExpr is set to ExprError() and some non-success value
12642/// is returned.
12643Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012644Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12645 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012646 const DeclarationNameInfo &NameInfo,
12647 LookupResult &MemberLookup,
12648 OverloadCandidateSet *CandidateSet,
12649 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012650 Scope *S = nullptr;
12651
Sam Panzer0f384432012-08-21 00:52:01 +000012652 CandidateSet->clear();
12653 if (!MemberLookup.empty()) {
12654 ExprResult MemberRef =
12655 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12656 /*IsPtr=*/false, CXXScopeSpec(),
12657 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012658 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012659 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012660 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012661 if (MemberRef.isInvalid()) {
12662 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012663 return FRS_DiagnosticIssued;
12664 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012665 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012666 if (CallExpr->isInvalid()) {
12667 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012668 return FRS_DiagnosticIssued;
12669 }
12670 } else {
12671 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012672 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012673 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012674 NestedNameSpecifierLoc(), NameInfo,
12675 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012676 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012677
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012678 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012679 CandidateSet, CallExpr);
12680 if (CandidateSet->empty() || CandidateSetError) {
12681 *CallExpr = ExprError();
12682 return FRS_NoViableFunction;
12683 }
12684 OverloadCandidateSet::iterator Best;
12685 OverloadingResult OverloadResult =
12686 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12687
12688 if (OverloadResult == OR_No_Viable_Function) {
12689 *CallExpr = ExprError();
12690 return FRS_NoViableFunction;
12691 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012692 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012693 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012694 OverloadResult,
12695 /*AllowTypoCorrection=*/false);
12696 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12697 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012698 return FRS_DiagnosticIssued;
12699 }
12700 }
12701 return FRS_Success;
12702}
12703
12704
Douglas Gregorcd695e52008-11-10 20:40:00 +000012705/// FixOverloadedFunctionReference - E is an expression that refers to
12706/// a C++ overloaded function (possibly with some parentheses and
12707/// perhaps a '&' around it). We have resolved the overloaded function
12708/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012709/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012710Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012711 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012712 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012713 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12714 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012715 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012716 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012717
Douglas Gregor51c538b2009-11-20 19:42:02 +000012718 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012719 }
12720
Douglas Gregor51c538b2009-11-20 19:42:02 +000012721 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012722 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12723 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012724 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012725 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012726 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012727 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012728 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012729 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012730
12731 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012732 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012733 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012734 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012735 }
12736
Douglas Gregor51c538b2009-11-20 19:42:02 +000012737 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012738 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012739 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12741 if (Method->isStatic()) {
12742 // Do nothing: static member functions aren't any different
12743 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012744 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012745 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012746 // UnresolvedLookupExpr holding an overloaded member function
12747 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012748 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12749 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012750 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012751 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012752
John McCalld14a8642009-11-21 08:51:07 +000012753 assert(isa<DeclRefExpr>(SubExpr)
12754 && "fixed to something other than a decl ref");
12755 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12756 && "fixed to a member ref with no nested name qualifier");
12757
12758 // We have taken the address of a pointer to member
12759 // function. Perform the computation here so that we get the
12760 // appropriate pointer to member type.
12761 QualType ClassType
12762 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12763 QualType MemPtrType
12764 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12765
John McCall7decc9e2010-11-18 06:31:45 +000012766 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12767 VK_RValue, OK_Ordinary,
12768 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012769 }
12770 }
John McCall16df1e52010-03-30 21:47:33 +000012771 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12772 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012773 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012774 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012775
John McCalle3027922010-08-25 11:45:40 +000012776 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012777 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012778 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012779 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012780 }
John McCalld14a8642009-11-21 08:51:07 +000012781
12782 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012783 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012784 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012785 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012786 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12787 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012788 }
12789
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012790 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12791 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012792 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012793 Fn,
John McCall113bee02012-03-10 09:33:50 +000012794 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012795 ULE->getNameLoc(),
12796 Fn->getType(),
12797 VK_LValue,
12798 Found.getDecl(),
12799 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012800 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012801 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12802 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012803 }
12804
John McCall10eae182009-11-30 22:42:35 +000012805 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012806 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012807 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012808 if (MemExpr->hasExplicitTemplateArgs()) {
12809 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12810 TemplateArgs = &TemplateArgsBuffer;
12811 }
John McCall6b51f282009-11-23 01:53:49 +000012812
John McCall2d74de92009-12-01 22:10:20 +000012813 Expr *Base;
12814
John McCall7decc9e2010-11-18 06:31:45 +000012815 // If we're filling in a static method where we used to have an
12816 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012817 if (MemExpr->isImplicitAccess()) {
12818 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012819 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12820 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012821 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012822 Fn,
John McCall113bee02012-03-10 09:33:50 +000012823 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012824 MemExpr->getMemberLoc(),
12825 Fn->getType(),
12826 VK_LValue,
12827 Found.getDecl(),
12828 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012829 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012830 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12831 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012832 } else {
12833 SourceLocation Loc = MemExpr->getMemberLoc();
12834 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012835 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012836 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012837 Base = new (Context) CXXThisExpr(Loc,
12838 MemExpr->getBaseType(),
12839 /*isImplicit=*/true);
12840 }
John McCall2d74de92009-12-01 22:10:20 +000012841 } else
John McCallc3007a22010-10-26 07:05:15 +000012842 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012843
John McCall4adb38c2011-04-27 00:36:17 +000012844 ExprValueKind valueKind;
12845 QualType type;
12846 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12847 valueKind = VK_LValue;
12848 type = Fn->getType();
12849 } else {
12850 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012851 type = Context.BoundMemberTy;
12852 }
12853
12854 MemberExpr *ME = MemberExpr::Create(
12855 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12856 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12857 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12858 OK_Ordinary);
12859 ME->setHadMultipleCandidates(true);
12860 MarkMemberReferenced(ME);
12861 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012863
John McCallc3007a22010-10-26 07:05:15 +000012864 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012865}
12866
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012867ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012868 DeclAccessPair Found,
12869 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012870 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012871}