blob: 62f4f18bd3a146d5f753d9ef18ab93495a64e857 [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() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001825 isCompleteType(From->getLocStart(), FromType))
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 Smithdb0ac552015-12-18 22:40:25 +00003088 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
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)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003162 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
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.
Richard Smithdb0ac552015-12-18 22:40:25 +00004050 } else if (isCompleteType(Loc, OrigT2) &&
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() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004317 S.isCompleteType(DeclLoc, T2) &&
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 &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004380 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
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.
Richard Smithdb0ac552015-12-18 22:40:25 +00004518 if (!S.isCompleteType(From->getLocStart(), ToType))
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)
Richard Smithdb0ac552015-12-18 22:40:25 +00005452 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005453
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
Richard Smithdb0ac552015-12-18 22:40:25 +00005459 if (Converter.Suppress ? !isCompleteType(Loc, T)
5460 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005461 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005463 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005464 UnresolvedSet<4>
5465 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005466 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005467 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005468 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
Larisse Voufo236bec22013-06-10 06:50:24 +00005470 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005471 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005472
Larisse Voufo236bec22013-06-10 06:50:24 +00005473 // To check that there is only one target type, in C++1y:
5474 QualType ToType;
5475 bool HasUniqueTargetType = true;
5476
5477 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005478 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005479 NamedDecl *D = (*I)->getUnderlyingDecl();
5480 CXXConversionDecl *Conversion;
5481 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5482 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005483 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005484 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5485 else
5486 continue; // C++11 does not consider conversion operator templates(?).
5487 } else
5488 Conversion = cast<CXXConversionDecl>(D);
5489
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005490 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005491 "Conversion operator templates are considered potentially "
5492 "viable in C++1y");
5493
5494 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5495 if (Converter.match(CurToType) || ConvTemplate) {
5496
5497 if (Conversion->isExplicit()) {
5498 // FIXME: For C++1y, do we need this restriction?
5499 // cf. diagnoseNoViableConversion()
5500 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005501 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005502 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005503 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005504 if (ToType.isNull())
5505 ToType = CurToType.getUnqualifiedType();
5506 else if (HasUniqueTargetType &&
5507 (CurToType.getUnqualifiedType() != ToType))
5508 HasUniqueTargetType = false;
5509 }
5510 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005511 }
Richard Smith8dd34252012-02-04 07:07:42 +00005512 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005515 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005516 // C++1y [conv]p6:
5517 // ... An expression e of class type E appearing in such a context
5518 // is said to be contextually implicitly converted to a specified
5519 // type T and is well-formed if and only if e can be implicitly
5520 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005521 // for conversion functions whose return type is cv T or reference to
5522 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005523 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Larisse Voufo236bec22013-06-10 06:50:24 +00005525 // If no unique T is found:
5526 if (ToType.isNull()) {
5527 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5528 HadMultipleCandidates,
5529 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005530 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005531 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Larisse Voufo236bec22013-06-10 06:50:24 +00005534 // If more than one unique Ts are found:
5535 if (!HasUniqueTargetType)
5536 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5537 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
Larisse Voufo236bec22013-06-10 06:50:24 +00005539 // If one unique T is found:
5540 // First, build a candidate set from the previously recorded
5541 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005542 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005543 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5544 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
Larisse Voufo236bec22013-06-10 06:50:24 +00005546 // Then, perform overload resolution over the candidate set.
5547 OverloadCandidateSet::iterator Best;
5548 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5549 case OR_Success: {
5550 // Apply this conversion.
5551 DeclAccessPair Found =
5552 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5553 if (recordConversion(*this, Loc, From, Converter, T,
5554 HadMultipleCandidates, Found))
5555 return ExprError();
5556 break;
5557 }
5558 case OR_Ambiguous:
5559 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5560 ViableConversions);
5561 case OR_No_Viable_Function:
5562 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5563 HadMultipleCandidates,
5564 ExplicitConversions))
5565 return ExprError();
5566 // fall through 'OR_Deleted' case.
5567 case OR_Deleted:
5568 // We'll complain below about a non-integral condition type.
5569 break;
5570 }
5571 } else {
5572 switch (ViableConversions.size()) {
5573 case 0: {
5574 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5575 HadMultipleCandidates,
5576 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005577 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578
Larisse Voufo236bec22013-06-10 06:50:24 +00005579 // We'll complain below about a non-integral condition type.
5580 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005581 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005582 case 1: {
5583 // Apply this conversion.
5584 DeclAccessPair Found = ViableConversions[0];
5585 if (recordConversion(*this, Loc, From, Converter, T,
5586 HadMultipleCandidates, Found))
5587 return ExprError();
5588 break;
5589 }
5590 default:
5591 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5592 ViableConversions);
5593 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595
Larisse Voufo236bec22013-06-10 06:50:24 +00005596 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005597}
5598
Richard Smith100b24a2014-04-17 01:52:14 +00005599/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5600/// an acceptable non-member overloaded operator for a call whose
5601/// arguments have types T1 (and, if non-empty, T2). This routine
5602/// implements the check in C++ [over.match.oper]p3b2 concerning
5603/// enumeration types.
5604static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5605 FunctionDecl *Fn,
5606 ArrayRef<Expr *> Args) {
5607 QualType T1 = Args[0]->getType();
5608 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5609
5610 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5611 return true;
5612
5613 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5614 return true;
5615
5616 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5617 if (Proto->getNumParams() < 1)
5618 return false;
5619
5620 if (T1->isEnumeralType()) {
5621 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5622 if (Context.hasSameUnqualifiedType(T1, ArgType))
5623 return true;
5624 }
5625
5626 if (Proto->getNumParams() < 2)
5627 return false;
5628
5629 if (!T2.isNull() && T2->isEnumeralType()) {
5630 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5631 if (Context.hasSameUnqualifiedType(T2, ArgType))
5632 return true;
5633 }
5634
5635 return false;
5636}
5637
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005638/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005639/// candidate functions, using the given function call arguments. If
5640/// @p SuppressUserConversions, then don't allow user-defined
5641/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005642///
James Dennett2a4d13c2012-06-15 07:13:21 +00005643/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005644/// based on an incomplete set of function arguments. This feature is used by
5645/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005646void
5647Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005648 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005649 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005650 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005651 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005652 bool PartialOverloading,
5653 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005654 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005655 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005656 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005657 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005658 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005659
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005661 if (!isa<CXXConstructorDecl>(Method)) {
5662 // If we get here, it's because we're calling a member function
5663 // that is named without a member access expression (e.g.,
5664 // "this->f") that was either written explicitly or created
5665 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005666 // function, e.g., X::f(). We use an empty type for the implied
5667 // object argument (C++ [over.call.func]p3), and the acting context
5668 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005669 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005671 Args, CandidateSet, SuppressUserConversions,
5672 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005673 return;
5674 }
5675 // We treat a constructor like a non-member function, since its object
5676 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005677 }
5678
Douglas Gregorff7028a2009-11-13 23:59:09 +00005679 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005680 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005681
Richard Smith100b24a2014-04-17 01:52:14 +00005682 // C++ [over.match.oper]p3:
5683 // if no operand has a class type, only those non-member functions in the
5684 // lookup set that have a first parameter of type T1 or "reference to
5685 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5686 // is a right operand) a second parameter of type T2 or "reference to
5687 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5688 // candidate functions.
5689 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5690 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5691 return;
5692
Richard Smith8b86f2d2013-11-04 01:48:18 +00005693 // C++11 [class.copy]p11: [DR1402]
5694 // A defaulted move constructor that is defined as deleted is ignored by
5695 // overload resolution.
5696 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5697 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5698 Constructor->isMoveConstructor())
5699 return;
5700
Douglas Gregor27381f32009-11-23 12:27:39 +00005701 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005702 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005703
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005704 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005705 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005706 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005707 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005708 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005709 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005710 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005711 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
John McCall578a1f82014-12-14 01:46:53 +00005713 if (Constructor) {
5714 // C++ [class.copy]p3:
5715 // A member function template is never instantiated to perform the copy
5716 // of a class object to an object of its class type.
5717 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005718 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005719 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005720 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5721 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005722 Candidate.Viable = false;
5723 Candidate.FailureKind = ovl_fail_illegal_constructor;
5724 return;
5725 }
5726 }
5727
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005728 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005729
5730 // (C++ 13.3.2p2): A candidate function having fewer than m
5731 // parameters is viable only if it has an ellipsis in its parameter
5732 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005733 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005734 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005735 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005736 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005737 return;
5738 }
5739
5740 // (C++ 13.3.2p2): A candidate function having more than m parameters
5741 // is viable only if the (m+1)st parameter has a default argument
5742 // (8.3.6). For the purposes of overload resolution, the
5743 // parameter list is truncated on the right, so that there are
5744 // exactly m parameters.
5745 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005746 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005747 // Not enough arguments.
5748 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005749 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005750 return;
5751 }
5752
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005753 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005754 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005755 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005756 // Skip the check for callers that are implicit members, because in this
5757 // case we may not yet know what the member's target is; the target is
5758 // inferred for the member automatically, based on the bases and fields of
5759 // the class.
5760 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005761 Candidate.Viable = false;
5762 Candidate.FailureKind = ovl_fail_bad_target;
5763 return;
5764 }
5765
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005766 // Determine the implicit conversion sequences for each of the
5767 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005768 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005769 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005770 // (C++ 13.3.2p3): for F to be a viable function, there shall
5771 // exist for each argument an implicit conversion sequence
5772 // (13.3.3.1) that converts that argument to the corresponding
5773 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005774 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005775 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005776 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005778 /*InOverloadResolution=*/true,
5779 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005780 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005781 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005782 if (Candidate.Conversions[ArgIdx].isBad()) {
5783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005784 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005785 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005786 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005787 } else {
5788 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5789 // argument for which there is no corresponding parameter is
5790 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005791 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005792 }
5793 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005794
5795 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5796 Candidate.Viable = false;
5797 Candidate.FailureKind = ovl_fail_enable_if;
5798 Candidate.DeductionFailure.Data = FailedAttr;
5799 return;
5800 }
5801}
5802
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005803ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005804 bool IsInstance) {
5805 SmallVector<ObjCMethodDecl*, 4> Methods;
5806 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5807 return nullptr;
5808
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005809 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5810 bool Match = true;
5811 ObjCMethodDecl *Method = Methods[b];
5812 unsigned NumNamedArgs = Sel.getNumArgs();
5813 // Method might have more arguments than selector indicates. This is due
5814 // to addition of c-style arguments in method.
5815 if (Method->param_size() > NumNamedArgs)
5816 NumNamedArgs = Method->param_size();
5817 if (Args.size() < NumNamedArgs)
5818 continue;
5819
5820 for (unsigned i = 0; i < NumNamedArgs; i++) {
5821 // We can't do any type-checking on a type-dependent argument.
5822 if (Args[i]->isTypeDependent()) {
5823 Match = false;
5824 break;
5825 }
5826
5827 ParmVarDecl *param = Method->parameters()[i];
5828 Expr *argExpr = Args[i];
5829 assert(argExpr && "SelectBestMethod(): missing expression");
5830
5831 // Strip the unbridged-cast placeholder expression off unless it's
5832 // a consumed argument.
5833 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5834 !param->hasAttr<CFConsumedAttr>())
5835 argExpr = stripARCUnbridgedCast(argExpr);
5836
5837 // If the parameter is __unknown_anytype, move on to the next method.
5838 if (param->getType() == Context.UnknownAnyTy) {
5839 Match = false;
5840 break;
5841 }
George Burgess IV45461812015-10-11 20:13:20 +00005842
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005843 ImplicitConversionSequence ConversionState
5844 = TryCopyInitialization(*this, argExpr, param->getType(),
5845 /*SuppressUserConversions*/false,
5846 /*InOverloadResolution=*/true,
5847 /*AllowObjCWritebackConversion=*/
5848 getLangOpts().ObjCAutoRefCount,
5849 /*AllowExplicit*/false);
5850 if (ConversionState.isBad()) {
5851 Match = false;
5852 break;
5853 }
5854 }
5855 // Promote additional arguments to variadic methods.
5856 if (Match && Method->isVariadic()) {
5857 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5858 if (Args[i]->isTypeDependent()) {
5859 Match = false;
5860 break;
5861 }
5862 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5863 nullptr);
5864 if (Arg.isInvalid()) {
5865 Match = false;
5866 break;
5867 }
5868 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005869 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005870 // Check for extra arguments to non-variadic methods.
5871 if (Args.size() != NumNamedArgs)
5872 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005873 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5874 // Special case when selectors have no argument. In this case, select
5875 // one with the most general result type of 'id'.
5876 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5877 QualType ReturnT = Methods[b]->getReturnType();
5878 if (ReturnT->isObjCIdType())
5879 return Methods[b];
5880 }
5881 }
5882 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005883
5884 if (Match)
5885 return Method;
5886 }
5887 return nullptr;
5888}
5889
George Burgess IV2a6150d2015-10-16 01:17:38 +00005890// specific_attr_iterator iterates over enable_if attributes in reverse, and
5891// enable_if is order-sensitive. As a result, we need to reverse things
5892// sometimes. Size of 4 elements is arbitrary.
5893static SmallVector<EnableIfAttr *, 4>
5894getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5895 SmallVector<EnableIfAttr *, 4> Result;
5896 if (!Function->hasAttrs())
5897 return Result;
5898
5899 const auto &FuncAttrs = Function->getAttrs();
5900 for (Attr *Attr : FuncAttrs)
5901 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5902 Result.push_back(EnableIf);
5903
5904 std::reverse(Result.begin(), Result.end());
5905 return Result;
5906}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005907
5908EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5909 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005910 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5911 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005912 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005913
5914 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005915 SmallVector<Expr *, 16> ConvertedArgs;
5916 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005917 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005918
5919 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005920 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5921 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005922 !cast<CXXMethodDecl>(Function)->isStatic() &&
5923 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005924 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5925 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005926 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005927 Method, Method);
5928 if (R.isInvalid()) {
5929 InitializationFailed = true;
5930 break;
5931 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005932 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005933 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005934 } else {
5935 ExprResult R =
5936 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5937 Context,
5938 Function->getParamDecl(i)),
5939 SourceLocation(),
5940 Args[i]);
5941 if (R.isInvalid()) {
5942 InitializationFailed = true;
5943 break;
5944 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005945 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005946 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005947 }
5948 }
5949
5950 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005951 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005952
Nick Lewyckye283c552015-08-25 22:33:16 +00005953 // Push default arguments if needed.
5954 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5955 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5956 ParmVarDecl *P = Function->getParamDecl(i);
5957 ExprResult R = PerformCopyInitialization(
5958 InitializedEntity::InitializeParameter(Context,
5959 Function->getParamDecl(i)),
5960 SourceLocation(),
5961 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5962 : P->getDefaultArg());
5963 if (R.isInvalid()) {
5964 InitializationFailed = true;
5965 break;
5966 }
5967 ContainsValueDependentExpr |= R.get()->isValueDependent();
5968 ConvertedArgs.push_back(R.get());
5969 }
5970
5971 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005972 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00005973 }
5974
George Burgess IV2a6150d2015-10-16 01:17:38 +00005975 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005976 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005977 if (EIA->getCond()->isValueDependent()) {
5978 // Don't even try now, we'll examine it after instantiation.
5979 continue;
5980 }
5981
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005982 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005983 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5984 if (!ContainsValueDependentExpr)
5985 return EIA;
5986 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005987 return EIA;
5988 }
5989 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005990 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005991}
5992
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005993/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005994/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005995void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005996 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005997 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005998 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005999 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006000 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006001 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006002 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6003 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006004 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006005 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006006 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006007 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006008 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006009 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006010 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006011 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006012 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006013 } else {
John McCalla0296f72010-03-19 07:35:19 +00006014 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006015 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6016 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006017 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006018 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006019 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006020 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006021 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006022 CandidateSet, SuppressUserConversions,
6023 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006024 else
John McCalla0296f72010-03-19 07:35:19 +00006025 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006026 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006027 CandidateSet, SuppressUserConversions,
6028 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006029 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006030 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006031}
6032
John McCallf0f1cf02009-11-17 07:50:12 +00006033/// AddMethodCandidate - Adds a named decl (which is some kind of
6034/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006035void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006036 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006037 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006038 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006039 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006040 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006041 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006043
6044 if (isa<UsingShadowDecl>(Decl))
6045 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006046
John McCallf0f1cf02009-11-17 07:50:12 +00006047 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6048 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6049 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006050 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006051 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006052 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006053 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006054 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006055 } else {
John McCalla0296f72010-03-19 07:35:19 +00006056 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006057 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006058 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006059 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006060 }
6061}
6062
Douglas Gregor436424c2008-11-18 23:14:02 +00006063/// AddMethodCandidate - Adds the given C++ member function to the set
6064/// of candidate functions, using the given function call arguments
6065/// and the object argument (@c Object). For example, in a call
6066/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6067/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6068/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006069/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006070void
John McCalla0296f72010-03-19 07:35:19 +00006071Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006072 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006073 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006074 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006075 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006076 bool SuppressUserConversions,
6077 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006078 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006079 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006080 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006081 assert(!isa<CXXConstructorDecl>(Method) &&
6082 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006083
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006084 if (!CandidateSet.isNewCandidate(Method))
6085 return;
6086
Richard Smith8b86f2d2013-11-04 01:48:18 +00006087 // C++11 [class.copy]p23: [DR1402]
6088 // A defaulted move assignment operator that is defined as deleted is
6089 // ignored by overload resolution.
6090 if (Method->isDefaulted() && Method->isDeleted() &&
6091 Method->isMoveAssignmentOperator())
6092 return;
6093
Douglas Gregor27381f32009-11-23 12:27:39 +00006094 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006095 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006096
Douglas Gregor436424c2008-11-18 23:14:02 +00006097 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006098 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006099 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006100 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006101 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006102 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006103 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006104
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006105 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006106
6107 // (C++ 13.3.2p2): A candidate function having fewer than m
6108 // parameters is viable only if it has an ellipsis in its parameter
6109 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006110 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6111 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006112 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006113 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006114 return;
6115 }
6116
6117 // (C++ 13.3.2p2): A candidate function having more than m parameters
6118 // is viable only if the (m+1)st parameter has a default argument
6119 // (8.3.6). For the purposes of overload resolution, the
6120 // parameter list is truncated on the right, so that there are
6121 // exactly m parameters.
6122 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006123 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006124 // Not enough arguments.
6125 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006126 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006127 return;
6128 }
6129
6130 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006131
John McCall6e9f8f62009-12-03 04:06:58 +00006132 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006133 // The implicit object argument is ignored.
6134 Candidate.IgnoreObjectArgument = true;
6135 else {
6136 // Determine the implicit conversion sequence for the object
6137 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006138 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6139 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6140 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006141 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006142 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006143 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006144 return;
6145 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006146 }
6147
Eli Bendersky291a57e2014-09-25 23:59:08 +00006148 // (CUDA B.1): Check for invalid calls between targets.
6149 if (getLangOpts().CUDA)
6150 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6151 if (CheckCUDATarget(Caller, Method)) {
6152 Candidate.Viable = false;
6153 Candidate.FailureKind = ovl_fail_bad_target;
6154 return;
6155 }
6156
Douglas Gregor436424c2008-11-18 23:14:02 +00006157 // Determine the implicit conversion sequences for each of the
6158 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006159 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006160 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006161 // (C++ 13.3.2p3): for F to be a viable function, there shall
6162 // exist for each argument an implicit conversion sequence
6163 // (13.3.3.1) that converts that argument to the corresponding
6164 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006165 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006166 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006167 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006169 /*InOverloadResolution=*/true,
6170 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006171 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006172 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006173 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006174 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006175 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006176 }
6177 } else {
6178 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6179 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006180 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006181 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006182 }
6183 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006184
6185 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6186 Candidate.Viable = false;
6187 Candidate.FailureKind = ovl_fail_enable_if;
6188 Candidate.DeductionFailure.Data = FailedAttr;
6189 return;
6190 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006191}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006192
Douglas Gregor97628d62009-08-21 00:16:32 +00006193/// \brief Add a C++ member function template as a candidate to the candidate
6194/// set, using template argument deduction to produce an appropriate member
6195/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006196void
Douglas Gregor97628d62009-08-21 00:16:32 +00006197Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006198 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006199 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006200 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006201 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006202 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006203 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006204 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006205 bool SuppressUserConversions,
6206 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006207 if (!CandidateSet.isNewCandidate(MethodTmpl))
6208 return;
6209
Douglas Gregor97628d62009-08-21 00:16:32 +00006210 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006211 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006212 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006213 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006214 // candidate functions in the usual way.113) A given name can refer to one
6215 // or more function templates and also to a set of overloaded non-template
6216 // functions. In such a case, the candidate functions generated from each
6217 // function template are combined with the set of non-template candidate
6218 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006219 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006220 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006221 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006222 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006223 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006224 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006225 Candidate.FoundDecl = FoundDecl;
6226 Candidate.Function = MethodTmpl->getTemplatedDecl();
6227 Candidate.Viable = false;
6228 Candidate.FailureKind = ovl_fail_bad_deduction;
6229 Candidate.IsSurrogate = false;
6230 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006231 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006232 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006233 Info);
6234 return;
6235 }
Mike Stump11289f42009-09-09 15:08:12 +00006236
Douglas Gregor97628d62009-08-21 00:16:32 +00006237 // Add the function template specialization produced by template argument
6238 // deduction as a candidate.
6239 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006240 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006241 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006242 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006243 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006244 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006245}
6246
Douglas Gregor05155d82009-08-21 23:19:43 +00006247/// \brief Add a C++ function template specialization as a candidate
6248/// in the candidate set, using template argument deduction to produce
6249/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006250void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006251Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006252 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006253 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006254 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006255 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006256 bool SuppressUserConversions,
6257 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006258 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6259 return;
6260
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006261 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006262 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006263 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006264 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006265 // candidate functions in the usual way.113) A given name can refer to one
6266 // or more function templates and also to a set of overloaded non-template
6267 // functions. In such a case, the candidate functions generated from each
6268 // function template are combined with the set of non-template candidate
6269 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006270 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006271 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006272 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006273 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006274 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006275 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006276 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006277 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6278 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006279 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006280 Candidate.IsSurrogate = false;
6281 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006282 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006283 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006284 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006285 return;
6286 }
Mike Stump11289f42009-09-09 15:08:12 +00006287
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006288 // Add the function template specialization produced by template argument
6289 // deduction as a candidate.
6290 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006291 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006292 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006293}
Mike Stump11289f42009-09-09 15:08:12 +00006294
Douglas Gregor4b60a152013-11-07 22:34:54 +00006295/// Determine whether this is an allowable conversion from the result
6296/// of an explicit conversion operator to the expected type, per C++
6297/// [over.match.conv]p1 and [over.match.ref]p1.
6298///
6299/// \param ConvType The return type of the conversion function.
6300///
6301/// \param ToType The type we are converting to.
6302///
6303/// \param AllowObjCPointerConversion Allow a conversion from one
6304/// Objective-C pointer to another.
6305///
6306/// \returns true if the conversion is allowable, false otherwise.
6307static bool isAllowableExplicitConversion(Sema &S,
6308 QualType ConvType, QualType ToType,
6309 bool AllowObjCPointerConversion) {
6310 QualType ToNonRefType = ToType.getNonReferenceType();
6311
6312 // Easy case: the types are the same.
6313 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6314 return true;
6315
6316 // Allow qualification conversions.
6317 bool ObjCLifetimeConversion;
6318 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6319 ObjCLifetimeConversion))
6320 return true;
6321
6322 // If we're not allowed to consider Objective-C pointer conversions,
6323 // we're done.
6324 if (!AllowObjCPointerConversion)
6325 return false;
6326
6327 // Is this an Objective-C pointer conversion?
6328 bool IncompatibleObjC = false;
6329 QualType ConvertedType;
6330 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6331 IncompatibleObjC);
6332}
6333
Douglas Gregora1f013e2008-11-07 22:36:19 +00006334/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006335/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006336/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006337/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006338/// (which may or may not be the same type as the type that the
6339/// conversion function produces).
6340void
6341Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006342 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006343 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006344 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006345 OverloadCandidateSet& CandidateSet,
6346 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006347 assert(!Conversion->getDescribedFunctionTemplate() &&
6348 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006349 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006350 if (!CandidateSet.isNewCandidate(Conversion))
6351 return;
6352
Richard Smith2a7d4812013-05-04 07:00:32 +00006353 // If the conversion function has an undeduced return type, trigger its
6354 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006355 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006356 if (DeduceReturnType(Conversion, From->getExprLoc()))
6357 return;
6358 ConvType = Conversion->getConversionType().getNonReferenceType();
6359 }
6360
Richard Smith089c3162013-09-21 21:55:46 +00006361 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6362 // operator is only a candidate if its return type is the target type or
6363 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006364 if (Conversion->isExplicit() &&
6365 !isAllowableExplicitConversion(*this, ConvType, ToType,
6366 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006367 return;
6368
Douglas Gregor27381f32009-11-23 12:27:39 +00006369 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006370 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006371
Douglas Gregora1f013e2008-11-07 22:36:19 +00006372 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006373 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006374 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006375 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006376 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006377 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006378 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006379 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006380 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006381 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006382 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006383
Douglas Gregor6affc782010-08-19 15:37:02 +00006384 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385 // For conversion functions, the function is considered to be a member of
6386 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006387 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006388 //
6389 // Determine the implicit conversion sequence for the implicit
6390 // object parameter.
6391 QualType ImplicitParamType = From->getType();
6392 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6393 ImplicitParamType = FromPtrType->getPointeeType();
6394 CXXRecordDecl *ConversionContext
6395 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006396
Richard Smith0f59cb32015-12-18 21:45:41 +00006397 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6398 *this, CandidateSet.getLocation(), From->getType(),
6399 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006400
John McCall0d1da222010-01-12 00:44:57 +00006401 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006402 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006403 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006404 return;
6405 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006406
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006407 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006408 // derived to base as such conversions are given Conversion Rank. They only
6409 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6410 QualType FromCanon
6411 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6412 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006413 if (FromCanon == ToCanon ||
6414 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006415 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006416 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006417 return;
6418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419
Douglas Gregora1f013e2008-11-07 22:36:19 +00006420 // To determine what the conversion from the result of calling the
6421 // conversion function to the type we're eventually trying to
6422 // convert to (ToType), we need to synthesize a call to the
6423 // conversion function and attempt copy initialization from it. This
6424 // makes sure that we get the right semantics with respect to
6425 // lvalues/rvalues and the type. Fortunately, we can allocate this
6426 // call on the stack and we don't need its arguments to be
6427 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006428 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006429 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006430 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6431 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006432 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006433 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006434
Richard Smith48d24642011-07-13 22:53:21 +00006435 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006436 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006437 Candidate.Viable = false;
6438 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6439 return;
6440 }
6441
Richard Smith48d24642011-07-13 22:53:21 +00006442 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006443
Mike Stump11289f42009-09-09 15:08:12 +00006444 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006445 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6446 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006447 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006448 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006449 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006450 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006451 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006452 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006453 /*InOverloadResolution=*/false,
6454 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006455
John McCall0d1da222010-01-12 00:44:57 +00006456 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006457 case ImplicitConversionSequence::StandardConversion:
6458 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006459
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006460 // C++ [over.ics.user]p3:
6461 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006462 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006463 // shall have exact match rank.
6464 if (Conversion->getPrimaryTemplate() &&
6465 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6466 Candidate.Viable = false;
6467 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006468 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006470
Douglas Gregorcba72b12011-01-21 05:18:22 +00006471 // C++0x [dcl.init.ref]p5:
6472 // In the second case, if the reference is an rvalue reference and
6473 // the second standard conversion sequence of the user-defined
6474 // conversion sequence includes an lvalue-to-rvalue conversion, the
6475 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006477 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6478 Candidate.Viable = false;
6479 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006480 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006481 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006482 break;
6483
6484 case ImplicitConversionSequence::BadConversion:
6485 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006486 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006487 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006488
6489 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006490 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006491 "Can only end up with a standard conversion sequence or failure");
6492 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006493
Craig Topper5fc8fc22014-08-27 06:28:36 +00006494 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006495 Candidate.Viable = false;
6496 Candidate.FailureKind = ovl_fail_enable_if;
6497 Candidate.DeductionFailure.Data = FailedAttr;
6498 return;
6499 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006500}
6501
Douglas Gregor05155d82009-08-21 23:19:43 +00006502/// \brief Adds a conversion function template specialization
6503/// candidate to the overload set, using template argument deduction
6504/// to deduce the template arguments of the conversion function
6505/// template from the type that we are converting to (C++
6506/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006507void
Douglas Gregor05155d82009-08-21 23:19:43 +00006508Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006509 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006510 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006511 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006512 OverloadCandidateSet &CandidateSet,
6513 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006514 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6515 "Only conversion function templates permitted here");
6516
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006517 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6518 return;
6519
Craig Toppere6706e42012-09-19 02:26:47 +00006520 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006521 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006522 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006523 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006524 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006525 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006526 Candidate.FoundDecl = FoundDecl;
6527 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6528 Candidate.Viable = false;
6529 Candidate.FailureKind = ovl_fail_bad_deduction;
6530 Candidate.IsSurrogate = false;
6531 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006532 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006534 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006535 return;
6536 }
Mike Stump11289f42009-09-09 15:08:12 +00006537
Douglas Gregor05155d82009-08-21 23:19:43 +00006538 // Add the conversion function template specialization produced by
6539 // template argument deduction as a candidate.
6540 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006541 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006542 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006543}
6544
Douglas Gregorab7897a2008-11-19 22:57:39 +00006545/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6546/// converts the given @c Object to a function pointer via the
6547/// conversion function @c Conversion, and then attempts to call it
6548/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6549/// the type of function that we'll eventually be calling.
6550void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006551 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006552 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006553 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006554 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006555 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006556 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006557 if (!CandidateSet.isNewCandidate(Conversion))
6558 return;
6559
Douglas Gregor27381f32009-11-23 12:27:39 +00006560 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006561 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006562
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006563 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006564 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006565 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006566 Candidate.Surrogate = Conversion;
6567 Candidate.Viable = true;
6568 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006569 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006570 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006571
6572 // Determine the implicit conversion sequence for the implicit
6573 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006574 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6575 *this, CandidateSet.getLocation(), Object->getType(),
6576 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006577 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006578 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006579 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006580 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006581 return;
6582 }
6583
6584 // The first conversion is actually a user-defined conversion whose
6585 // first conversion is ObjectInit's standard conversion (which is
6586 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006587 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006588 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006589 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006590 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006591 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006592 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006593 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006594 = Candidate.Conversions[0].UserDefined.Before;
6595 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6596
Mike Stump11289f42009-09-09 15:08:12 +00006597 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006598 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006599
6600 // (C++ 13.3.2p2): A candidate function having fewer than m
6601 // parameters is viable only if it has an ellipsis in its parameter
6602 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006603 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006604 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006605 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006606 return;
6607 }
6608
6609 // Function types don't have any default arguments, so just check if
6610 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006611 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006612 // Not enough arguments.
6613 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006614 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006615 return;
6616 }
6617
6618 // Determine the implicit conversion sequences for each of the
6619 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006620 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006621 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006622 // (C++ 13.3.2p3): for F to be a viable function, there shall
6623 // exist for each argument an implicit conversion sequence
6624 // (13.3.3.1) that converts that argument to the corresponding
6625 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006626 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006627 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006628 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006629 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006630 /*InOverloadResolution=*/false,
6631 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006632 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006633 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006634 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006635 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006636 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006637 }
6638 } else {
6639 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6640 // argument for which there is no corresponding parameter is
6641 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006642 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006643 }
6644 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006645
Craig Topper5fc8fc22014-08-27 06:28:36 +00006646 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006647 Candidate.Viable = false;
6648 Candidate.FailureKind = ovl_fail_enable_if;
6649 Candidate.DeductionFailure.Data = FailedAttr;
6650 return;
6651 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006652}
6653
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006654/// \brief Add overload candidates for overloaded operators that are
6655/// member functions.
6656///
6657/// Add the overloaded operator candidates that are member functions
6658/// for the operator Op that was used in an operator expression such
6659/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6660/// CandidateSet will store the added overload candidates. (C++
6661/// [over.match.oper]).
6662void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6663 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006664 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006665 OverloadCandidateSet& CandidateSet,
6666 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006667 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6668
6669 // C++ [over.match.oper]p3:
6670 // For a unary operator @ with an operand of a type whose
6671 // cv-unqualified version is T1, and for a binary operator @ with
6672 // a left operand of a type whose cv-unqualified version is T1 and
6673 // a right operand of a type whose cv-unqualified version is T2,
6674 // three sets of candidate functions, designated member
6675 // candidates, non-member candidates and built-in candidates, are
6676 // constructed as follows:
6677 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006678
Richard Smith0feaf0c2013-04-20 12:41:22 +00006679 // -- If T1 is a complete class type or a class currently being
6680 // defined, the set of member candidates is the result of the
6681 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6682 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006683 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006684 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006685 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006686 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006687 // If the type is neither complete nor being defined, bail out now.
6688 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006689 return;
Mike Stump11289f42009-09-09 15:08:12 +00006690
John McCall27b18f82009-11-17 02:14:36 +00006691 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6692 LookupQualifiedName(Operators, T1Rec->getDecl());
6693 Operators.suppressDiagnostics();
6694
Mike Stump11289f42009-09-09 15:08:12 +00006695 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006696 OperEnd = Operators.end();
6697 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006698 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006699 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006700 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006701 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006702 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006703 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006704 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006705}
6706
Douglas Gregora11693b2008-11-12 17:17:38 +00006707/// AddBuiltinCandidate - Add a candidate for a built-in
6708/// operator. ResultTy and ParamTys are the result and parameter types
6709/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006710/// arguments being passed to the candidate. IsAssignmentOperator
6711/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006712/// operator. NumContextualBoolArguments is the number of arguments
6713/// (at the beginning of the argument list) that will be contextually
6714/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006715void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006716 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006717 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006718 bool IsAssignmentOperator,
6719 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006720 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006721 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006722
Douglas Gregora11693b2008-11-12 17:17:38 +00006723 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006724 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006725 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6726 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006727 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006728 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006729 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006730 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006731 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6732
6733 // Determine the implicit conversion sequences for each of the
6734 // arguments.
6735 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006736 Candidate.ExplicitCallArguments = Args.size();
6737 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006738 // C++ [over.match.oper]p4:
6739 // For the built-in assignment operators, conversions of the
6740 // left operand are restricted as follows:
6741 // -- no temporaries are introduced to hold the left operand, and
6742 // -- no user-defined conversions are applied to the left
6743 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006744 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006745 //
6746 // We block these conversions by turning off user-defined
6747 // conversions, since that is the only way that initialization of
6748 // a reference to a non-class type can occur from something that
6749 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006750 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006751 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006752 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006753 Candidate.Conversions[ArgIdx]
6754 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006755 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006756 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006757 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006758 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006759 /*InOverloadResolution=*/false,
6760 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006761 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006762 }
John McCall0d1da222010-01-12 00:44:57 +00006763 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006764 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006765 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006766 break;
6767 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006768 }
6769}
6770
Craig Toppercd7b0332013-07-01 06:29:40 +00006771namespace {
6772
Douglas Gregora11693b2008-11-12 17:17:38 +00006773/// BuiltinCandidateTypeSet - A set of types that will be used for the
6774/// candidate operator functions for built-in operators (C++
6775/// [over.built]). The types are separated into pointer types and
6776/// enumeration types.
6777class BuiltinCandidateTypeSet {
6778 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006779 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006780
6781 /// PointerTypes - The set of pointer types that will be used in the
6782 /// built-in candidates.
6783 TypeSet PointerTypes;
6784
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006785 /// MemberPointerTypes - The set of member pointer types that will be
6786 /// used in the built-in candidates.
6787 TypeSet MemberPointerTypes;
6788
Douglas Gregora11693b2008-11-12 17:17:38 +00006789 /// EnumerationTypes - The set of enumeration types that will be
6790 /// used in the built-in candidates.
6791 TypeSet EnumerationTypes;
6792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006794 /// candidates.
6795 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006796
6797 /// \brief A flag indicating non-record types are viable candidates
6798 bool HasNonRecordTypes;
6799
6800 /// \brief A flag indicating whether either arithmetic or enumeration types
6801 /// were present in the candidate set.
6802 bool HasArithmeticOrEnumeralTypes;
6803
Douglas Gregor80af3132011-05-21 23:15:46 +00006804 /// \brief A flag indicating whether the nullptr type was present in the
6805 /// candidate set.
6806 bool HasNullPtrType;
6807
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006808 /// Sema - The semantic analysis instance where we are building the
6809 /// candidate type set.
6810 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006811
Douglas Gregora11693b2008-11-12 17:17:38 +00006812 /// Context - The AST context in which we will build the type sets.
6813 ASTContext &Context;
6814
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006815 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6816 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006817 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006818
6819public:
6820 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006821 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006822
Mike Stump11289f42009-09-09 15:08:12 +00006823 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006824 : HasNonRecordTypes(false),
6825 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006826 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006827 SemaRef(SemaRef),
6828 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006831 SourceLocation Loc,
6832 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006833 bool AllowExplicitConversions,
6834 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006835
6836 /// pointer_begin - First pointer type found;
6837 iterator pointer_begin() { return PointerTypes.begin(); }
6838
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006839 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006840 iterator pointer_end() { return PointerTypes.end(); }
6841
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006842 /// member_pointer_begin - First member pointer type found;
6843 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6844
6845 /// member_pointer_end - Past the last member pointer type found;
6846 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6847
Douglas Gregora11693b2008-11-12 17:17:38 +00006848 /// enumeration_begin - First enumeration type found;
6849 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6850
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006851 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006852 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006853
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006854 iterator vector_begin() { return VectorTypes.begin(); }
6855 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006856
6857 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6858 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006859 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006860};
6861
Craig Toppercd7b0332013-07-01 06:29:40 +00006862} // end anonymous namespace
6863
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006864/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006865/// the set of pointer types along with any more-qualified variants of
6866/// that type. For example, if @p Ty is "int const *", this routine
6867/// will add "int const *", "int const volatile *", "int const
6868/// restrict *", and "int const volatile restrict *" to the set of
6869/// pointer types. Returns true if the add of @p Ty itself succeeded,
6870/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006871///
6872/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006873bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006874BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6875 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006876
Douglas Gregora11693b2008-11-12 17:17:38 +00006877 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006878 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006879 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006881 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006882 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006883 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006884 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006885 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6886 PointeeTy = PTy->getPointeeType();
6887 buildObjCPtr = true;
6888 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006889 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006890 }
6891
Sebastian Redl4990a632009-11-18 20:39:26 +00006892 // Don't add qualified variants of arrays. For one, they're not allowed
6893 // (the qualifier would sink to the element type), and for another, the
6894 // only overload situation where it matters is subscript or pointer +- int,
6895 // and those shouldn't have qualifier variants anyway.
6896 if (PointeeTy->isArrayType())
6897 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006898
John McCall8ccfcb52009-09-24 19:53:00 +00006899 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006900 bool hasVolatile = VisibleQuals.hasVolatile();
6901 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902
John McCall8ccfcb52009-09-24 19:53:00 +00006903 // Iterate through all strict supersets of BaseCVR.
6904 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6905 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006906 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006907 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006908
6909 // Skip over restrict if no restrict found anywhere in the types, or if
6910 // the type cannot be restrict-qualified.
6911 if ((CVR & Qualifiers::Restrict) &&
6912 (!hasRestrict ||
6913 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6914 continue;
6915
6916 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006917 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006918
6919 // Build qualified pointer type.
6920 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006921 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006922 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006923 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006924 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6925
6926 // Insert qualified pointer type.
6927 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 }
6929
6930 return true;
6931}
6932
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006933/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6934/// to the set of pointer types along with any more-qualified variants of
6935/// that type. For example, if @p Ty is "int const *", this routine
6936/// will add "int const *", "int const volatile *", "int const
6937/// restrict *", and "int const volatile restrict *" to the set of
6938/// pointer types. Returns true if the add of @p Ty itself succeeded,
6939/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006940///
6941/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006942bool
6943BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6944 QualType Ty) {
6945 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006946 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006947 return false;
6948
John McCall8ccfcb52009-09-24 19:53:00 +00006949 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6950 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006951
John McCall8ccfcb52009-09-24 19:53:00 +00006952 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006953 // Don't add qualified variants of arrays. For one, they're not allowed
6954 // (the qualifier would sink to the element type), and for another, the
6955 // only overload situation where it matters is subscript or pointer +- int,
6956 // and those shouldn't have qualifier variants anyway.
6957 if (PointeeTy->isArrayType())
6958 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006959 const Type *ClassTy = PointerTy->getClass();
6960
6961 // Iterate through all strict supersets of the pointee type's CVR
6962 // qualifiers.
6963 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6964 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6965 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966
John McCall8ccfcb52009-09-24 19:53:00 +00006967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006968 MemberPointerTypes.insert(
6969 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006970 }
6971
6972 return true;
6973}
6974
Douglas Gregora11693b2008-11-12 17:17:38 +00006975/// AddTypesConvertedFrom - Add each of the types to which the type @p
6976/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006977/// primarily interested in pointer types and enumeration types. We also
6978/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006979/// AllowUserConversions is true if we should look at the conversion
6980/// functions of a class type, and AllowExplicitConversions if we
6981/// should also include the explicit conversion functions of a class
6982/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006983void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006984BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006985 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006986 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006987 bool AllowExplicitConversions,
6988 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006989 // Only deal with canonical types.
6990 Ty = Context.getCanonicalType(Ty);
6991
6992 // Look through reference types; they aren't part of the type of an
6993 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006994 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006995 Ty = RefTy->getPointeeType();
6996
John McCall33ddac02011-01-19 10:06:00 +00006997 // If we're dealing with an array type, decay to the pointer.
6998 if (Ty->isArrayType())
6999 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7000
7001 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007002 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007003
Chandler Carruth00a38332010-12-13 01:44:01 +00007004 // Flag if we ever add a non-record type.
7005 const RecordType *TyRec = Ty->getAs<RecordType>();
7006 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7007
Chandler Carruth00a38332010-12-13 01:44:01 +00007008 // Flag if we encounter an arithmetic type.
7009 HasArithmeticOrEnumeralTypes =
7010 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7011
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007012 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7013 PointerTypes.insert(Ty);
7014 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007015 // Insert our type, and its more-qualified variants, into the set
7016 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007017 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007018 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007019 } else if (Ty->isMemberPointerType()) {
7020 // Member pointers are far easier, since the pointee can't be converted.
7021 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7022 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007023 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007024 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007025 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007026 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007027 // We treat vector types as arithmetic types in many contexts as an
7028 // extension.
7029 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007030 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007031 } else if (Ty->isNullPtrType()) {
7032 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007033 } else if (AllowUserConversions && TyRec) {
7034 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007035 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007036 return;
Mike Stump11289f42009-09-09 15:08:12 +00007037
Chandler Carruth00a38332010-12-13 01:44:01 +00007038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007039 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007040 if (isa<UsingShadowDecl>(D))
7041 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007042
Chandler Carruth00a38332010-12-13 01:44:01 +00007043 // Skip conversion function templates; they don't tell us anything
7044 // about which builtin types we can convert to.
7045 if (isa<FunctionTemplateDecl>(D))
7046 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007047
Chandler Carruth00a38332010-12-13 01:44:01 +00007048 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7049 if (AllowExplicitConversions || !Conv->isExplicit()) {
7050 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7051 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007052 }
7053 }
7054 }
7055}
7056
Douglas Gregor84605ae2009-08-24 13:43:27 +00007057/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7058/// the volatile- and non-volatile-qualified assignment operators for the
7059/// given type to the candidate set.
7060static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7061 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007062 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007063 OverloadCandidateSet &CandidateSet) {
7064 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007065
Douglas Gregor84605ae2009-08-24 13:43:27 +00007066 // T& operator=(T&, T)
7067 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7068 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007070 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007071
Douglas Gregor84605ae2009-08-24 13:43:27 +00007072 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7073 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007074 ParamTypes[0]
7075 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007076 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007078 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007079 }
7080}
Mike Stump11289f42009-09-09 15:08:12 +00007081
Sebastian Redl1054fae2009-10-25 17:03:50 +00007082/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7083/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007084static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7085 Qualifiers VRQuals;
7086 const RecordType *TyRec;
7087 if (const MemberPointerType *RHSMPType =
7088 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007089 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007090 else
7091 TyRec = ArgExpr->getType()->getAs<RecordType>();
7092 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007093 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007094 VRQuals.addVolatile();
7095 VRQuals.addRestrict();
7096 return VRQuals;
7097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007100 if (!ClassDecl->hasDefinition())
7101 return VRQuals;
7102
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007103 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007104 if (isa<UsingShadowDecl>(D))
7105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7106 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007107 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7108 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7109 CanTy = ResTypeRef->getPointeeType();
7110 // Need to go down the pointer/mempointer chain and add qualifiers
7111 // as see them.
7112 bool done = false;
7113 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007114 if (CanTy.isRestrictQualified())
7115 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007116 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7117 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007119 CanTy->getAs<MemberPointerType>())
7120 CanTy = ResTypeMPtr->getPointeeType();
7121 else
7122 done = true;
7123 if (CanTy.isVolatileQualified())
7124 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007125 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7126 return VRQuals;
7127 }
7128 }
7129 }
7130 return VRQuals;
7131}
John McCall52872982010-11-13 05:51:15 +00007132
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007133namespace {
John McCall52872982010-11-13 05:51:15 +00007134
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007135/// \brief Helper class to manage the addition of builtin operator overload
7136/// candidates. It provides shared state and utility methods used throughout
7137/// the process, as well as a helper method to add each group of builtin
7138/// operator overloads from the standard to a candidate set.
7139class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007140 // Common instance state available to all overload candidate addition methods.
7141 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007142 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007143 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007144 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007145 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007146 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007147
Chandler Carruthc6586e52010-12-12 10:35:00 +00007148 // Define some constants used to index and iterate over the arithemetic types
7149 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007150 // The "promoted arithmetic types" are the arithmetic
7151 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007152 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007153 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007154 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007155 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007156 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007157 LastPromotedArithmeticType = 11;
7158 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007159
Chandler Carruthc6586e52010-12-12 10:35:00 +00007160 /// \brief Get the canonical type for a given arithmetic type index.
7161 CanQualType getArithmeticType(unsigned index) {
7162 assert(index < NumArithmeticTypes);
7163 static CanQualType ASTContext::* const
7164 ArithmeticTypes[NumArithmeticTypes] = {
7165 // Start of promoted types.
7166 &ASTContext::FloatTy,
7167 &ASTContext::DoubleTy,
7168 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007169
Chandler Carruthc6586e52010-12-12 10:35:00 +00007170 // Start of integral types.
7171 &ASTContext::IntTy,
7172 &ASTContext::LongTy,
7173 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007174 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007175 &ASTContext::UnsignedIntTy,
7176 &ASTContext::UnsignedLongTy,
7177 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007178 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007179 // End of promoted types.
7180
7181 &ASTContext::BoolTy,
7182 &ASTContext::CharTy,
7183 &ASTContext::WCharTy,
7184 &ASTContext::Char16Ty,
7185 &ASTContext::Char32Ty,
7186 &ASTContext::SignedCharTy,
7187 &ASTContext::ShortTy,
7188 &ASTContext::UnsignedCharTy,
7189 &ASTContext::UnsignedShortTy,
7190 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007191 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007192 };
7193 return S.Context.*ArithmeticTypes[index];
7194 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007196 /// \brief Gets the canonical type resulting from the usual arithemetic
7197 /// converions for the given arithmetic types.
7198 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7199 // Accelerator table for performing the usual arithmetic conversions.
7200 // The rules are basically:
7201 // - if either is floating-point, use the wider floating-point
7202 // - if same signedness, use the higher rank
7203 // - if same size, use unsigned of the higher rank
7204 // - use the larger type
7205 // These rules, together with the axiom that higher ranks are
7206 // never smaller, are sufficient to precompute all of these results
7207 // *except* when dealing with signed types of higher rank.
7208 // (we could precompute SLL x UI for all known platforms, but it's
7209 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007210 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007211 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007212 Dep=-1,
7213 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007214 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007215 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007216 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007217/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7218/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7219/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7220/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7221/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7222/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7223/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7224/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7225/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7226/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7227/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007228 };
7229
7230 assert(L < LastPromotedArithmeticType);
7231 assert(R < LastPromotedArithmeticType);
7232 int Idx = ConversionsTable[L][R];
7233
7234 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007235 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007236
7237 // Slow path: we need to compare widths.
7238 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007239 CanQualType LT = getArithmeticType(L),
7240 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007241 unsigned LW = S.Context.getIntWidth(LT),
7242 RW = S.Context.getIntWidth(RT);
7243
7244 // If they're different widths, use the signed type.
7245 if (LW > RW) return LT;
7246 else if (LW < RW) return RT;
7247
7248 // Otherwise, use the unsigned type of the signed type's rank.
7249 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7250 assert(L == SLL || R == SLL);
7251 return S.Context.UnsignedLongLongTy;
7252 }
7253
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007254 /// \brief Helper method to factor out the common pattern of adding overloads
7255 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007256 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007257 bool HasVolatile,
7258 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007259 QualType ParamTypes[2] = {
7260 S.Context.getLValueReferenceType(CandidateTy),
7261 S.Context.IntTy
7262 };
7263
7264 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007265 if (Args.size() == 1)
7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007267 else
Richard Smithe54c3072013-05-05 15:51:06 +00007268 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007269
7270 // Use a heuristic to reduce number of builtin candidates in the set:
7271 // add volatile version only if there are conversions to a volatile type.
7272 if (HasVolatile) {
7273 ParamTypes[0] =
7274 S.Context.getLValueReferenceType(
7275 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007276 if (Args.size() == 1)
7277 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007278 else
Richard Smithe54c3072013-05-05 15:51:06 +00007279 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007280 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007281
7282 // Add restrict version only if there are conversions to a restrict type
7283 // and our candidate type is a non-restrict-qualified pointer.
7284 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7285 !CandidateTy.isRestrictQualified()) {
7286 ParamTypes[0]
7287 = S.Context.getLValueReferenceType(
7288 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007289 if (Args.size() == 1)
7290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007291 else
Richard Smithe54c3072013-05-05 15:51:06 +00007292 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007293
7294 if (HasVolatile) {
7295 ParamTypes[0]
7296 = S.Context.getLValueReferenceType(
7297 S.Context.getCVRQualifiedType(CandidateTy,
7298 (Qualifiers::Volatile |
7299 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007300 if (Args.size() == 1)
7301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007302 else
Richard Smithe54c3072013-05-05 15:51:06 +00007303 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007304 }
7305 }
7306
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007307 }
7308
7309public:
7310 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007311 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007312 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007313 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007314 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007315 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007316 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007317 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007318 HasArithmeticOrEnumeralCandidateType(
7319 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007320 CandidateTypes(CandidateTypes),
7321 CandidateSet(CandidateSet) {
7322 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007323 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007324 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007325 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007326 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007327 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007328 assert(getArithmeticType(FirstPromotedArithmeticType)
7329 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007330 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007331 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007332 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007333 "Invalid last promoted arithmetic type");
7334 }
7335
7336 // C++ [over.built]p3:
7337 //
7338 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7339 // is either volatile or empty, there exist candidate operator
7340 // functions of the form
7341 //
7342 // VQ T& operator++(VQ T&);
7343 // T operator++(VQ T&, int);
7344 //
7345 // C++ [over.built]p4:
7346 //
7347 // For every pair (T, VQ), where T is an arithmetic type other
7348 // than bool, and VQ is either volatile or empty, there exist
7349 // candidate operator functions of the form
7350 //
7351 // VQ T& operator--(VQ T&);
7352 // T operator--(VQ T&, int);
7353 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007354 if (!HasArithmeticOrEnumeralCandidateType)
7355 return;
7356
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7358 Arith < NumArithmeticTypes; ++Arith) {
7359 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007360 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007361 VisibleTypeConversionsQuals.hasVolatile(),
7362 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007363 }
7364 }
7365
7366 // C++ [over.built]p5:
7367 //
7368 // For every pair (T, VQ), where T is a cv-qualified or
7369 // cv-unqualified object type, and VQ is either volatile or
7370 // empty, there exist candidate operator functions of the form
7371 //
7372 // T*VQ& operator++(T*VQ&);
7373 // T*VQ& operator--(T*VQ&);
7374 // T* operator++(T*VQ&, int);
7375 // T* operator--(T*VQ&, int);
7376 void addPlusPlusMinusMinusPointerOverloads() {
7377 for (BuiltinCandidateTypeSet::iterator
7378 Ptr = CandidateTypes[0].pointer_begin(),
7379 PtrEnd = CandidateTypes[0].pointer_end();
7380 Ptr != PtrEnd; ++Ptr) {
7381 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007382 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007383 continue;
7384
7385 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007386 (!(*Ptr).isVolatileQualified() &&
7387 VisibleTypeConversionsQuals.hasVolatile()),
7388 (!(*Ptr).isRestrictQualified() &&
7389 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007390 }
7391 }
7392
7393 // C++ [over.built]p6:
7394 // For every cv-qualified or cv-unqualified object type T, there
7395 // exist candidate operator functions of the form
7396 //
7397 // T& operator*(T*);
7398 //
7399 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007401 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007402 // T& operator*(T*);
7403 void addUnaryStarPointerOverloads() {
7404 for (BuiltinCandidateTypeSet::iterator
7405 Ptr = CandidateTypes[0].pointer_begin(),
7406 PtrEnd = CandidateTypes[0].pointer_end();
7407 Ptr != PtrEnd; ++Ptr) {
7408 QualType ParamTy = *Ptr;
7409 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007410 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7411 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007412
Douglas Gregor02824322011-01-26 19:30:28 +00007413 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7414 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7415 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007416
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007417 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007418 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007419 }
7420 }
7421
7422 // C++ [over.built]p9:
7423 // For every promoted arithmetic type T, there exist candidate
7424 // operator functions of the form
7425 //
7426 // T operator+(T);
7427 // T operator-(T);
7428 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007429 if (!HasArithmeticOrEnumeralCandidateType)
7430 return;
7431
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007432 for (unsigned Arith = FirstPromotedArithmeticType;
7433 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007434 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007435 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007436 }
7437
7438 // Extension: We also add these operators for vector types.
7439 for (BuiltinCandidateTypeSet::iterator
7440 Vec = CandidateTypes[0].vector_begin(),
7441 VecEnd = CandidateTypes[0].vector_end();
7442 Vec != VecEnd; ++Vec) {
7443 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007444 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007445 }
7446 }
7447
7448 // C++ [over.built]p8:
7449 // For every type T, there exist candidate operator functions of
7450 // the form
7451 //
7452 // T* operator+(T*);
7453 void addUnaryPlusPointerOverloads() {
7454 for (BuiltinCandidateTypeSet::iterator
7455 Ptr = CandidateTypes[0].pointer_begin(),
7456 PtrEnd = CandidateTypes[0].pointer_end();
7457 Ptr != PtrEnd; ++Ptr) {
7458 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007459 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007460 }
7461 }
7462
7463 // C++ [over.built]p10:
7464 // For every promoted integral type T, there exist candidate
7465 // operator functions of the form
7466 //
7467 // T operator~(T);
7468 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007469 if (!HasArithmeticOrEnumeralCandidateType)
7470 return;
7471
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007472 for (unsigned Int = FirstPromotedIntegralType;
7473 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007474 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007475 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 }
7477
7478 // Extension: We also add this operator for vector types.
7479 for (BuiltinCandidateTypeSet::iterator
7480 Vec = CandidateTypes[0].vector_begin(),
7481 VecEnd = CandidateTypes[0].vector_end();
7482 Vec != VecEnd; ++Vec) {
7483 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007484 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007485 }
7486 }
7487
7488 // C++ [over.match.oper]p16:
7489 // For every pointer to member type T, there exist candidate operator
7490 // functions of the form
7491 //
7492 // bool operator==(T,T);
7493 // bool operator!=(T,T);
7494 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7495 /// Set of (canonical) types that we've already handled.
7496 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7497
Richard Smithe54c3072013-05-05 15:51:06 +00007498 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007499 for (BuiltinCandidateTypeSet::iterator
7500 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7501 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7502 MemPtr != MemPtrEnd;
7503 ++MemPtr) {
7504 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007505 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007506 continue;
7507
7508 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007509 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 }
7511 }
7512 }
7513
7514 // C++ [over.built]p15:
7515 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007516 // For every T, where T is an enumeration type, a pointer type, or
7517 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007518 //
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);
7524 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007525 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007526 // C++ [over.match.oper]p3:
7527 // [...]the built-in candidates include all of the candidate operator
7528 // functions defined in 13.6 that, compared to the given operator, [...]
7529 // do not have the same parameter-type-list as any non-template non-member
7530 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007531 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007532 // Note that in practice, this only affects enumeration types because there
7533 // aren't any built-in candidates of record type, and a user-defined operator
7534 // must have an operand of record or enumeration type. Also, the only other
7535 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007536 // cannot be overloaded for enumeration types, so this is the only place
7537 // where we must suppress candidates like this.
7538 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7539 UserDefinedBinaryOperators;
7540
Richard Smithe54c3072013-05-05 15:51:06 +00007541 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007542 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7543 CandidateTypes[ArgIdx].enumeration_end()) {
7544 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7545 CEnd = CandidateSet.end();
7546 C != CEnd; ++C) {
7547 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7548 continue;
7549
Eli Friedman14f082b2012-09-18 21:52:24 +00007550 if (C->Function->isFunctionTemplateSpecialization())
7551 continue;
7552
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007553 QualType FirstParamType =
7554 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7555 QualType SecondParamType =
7556 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7557
7558 // Skip if either parameter isn't of enumeral type.
7559 if (!FirstParamType->isEnumeralType() ||
7560 !SecondParamType->isEnumeralType())
7561 continue;
7562
7563 // Add this operator to the set of known user-defined operators.
7564 UserDefinedBinaryOperators.insert(
7565 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7566 S.Context.getCanonicalType(SecondParamType)));
7567 }
7568 }
7569 }
7570
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571 /// Set of (canonical) types that we've already handled.
7572 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7573
Richard Smithe54c3072013-05-05 15:51:06 +00007574 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007575 for (BuiltinCandidateTypeSet::iterator
7576 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7577 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7578 Ptr != PtrEnd; ++Ptr) {
7579 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007580 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007581 continue;
7582
7583 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007584 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007585 }
7586 for (BuiltinCandidateTypeSet::iterator
7587 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7588 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7589 Enum != EnumEnd; ++Enum) {
7590 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7591
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007592 // Don't add the same builtin candidate twice, or if a user defined
7593 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007594 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007595 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7596 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007597 continue;
7598
7599 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007600 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007602
7603 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7604 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007605 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007606 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007607 NullPtrTy))) {
7608 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007609 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007610 CandidateSet);
7611 }
7612 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 }
7614 }
7615
7616 // C++ [over.built]p13:
7617 //
7618 // For every cv-qualified or cv-unqualified object type T
7619 // there exist candidate operator functions of the form
7620 //
7621 // T* operator+(T*, ptrdiff_t);
7622 // T& operator[](T*, ptrdiff_t); [BELOW]
7623 // T* operator-(T*, ptrdiff_t);
7624 // T* operator+(ptrdiff_t, T*);
7625 // T& operator[](ptrdiff_t, T*); [BELOW]
7626 //
7627 // C++ [over.built]p14:
7628 //
7629 // For every T, where T is a pointer to object type, there
7630 // exist candidate operator functions of the form
7631 //
7632 // ptrdiff_t operator-(T, T);
7633 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7634 /// Set of (canonical) types that we've already handled.
7635 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7636
7637 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007638 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639 S.Context.getPointerDiffType(),
7640 S.Context.getPointerDiffType(),
7641 };
7642 for (BuiltinCandidateTypeSet::iterator
7643 Ptr = CandidateTypes[Arg].pointer_begin(),
7644 PtrEnd = CandidateTypes[Arg].pointer_end();
7645 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007646 QualType PointeeTy = (*Ptr)->getPointeeType();
7647 if (!PointeeTy->isObjectType())
7648 continue;
7649
Eric Christopher9207a522015-08-21 16:24:01 +00007650 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 if (Arg == 0 || Op == OO_Plus) {
7652 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7653 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007654 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 }
7656 if (Op == OO_Minus) {
7657 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007658 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 continue;
7660
7661 QualType ParamTypes[2] = { *Ptr, *Ptr };
7662 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007663 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007664 }
7665 }
7666 }
7667 }
7668
7669 // C++ [over.built]p12:
7670 //
7671 // For every pair of promoted arithmetic types L and R, there
7672 // exist candidate operator functions of the form
7673 //
7674 // LR operator*(L, R);
7675 // LR operator/(L, R);
7676 // LR operator+(L, R);
7677 // LR 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 // bool operator!=(L, R);
7684 //
7685 // where LR is the result of the usual arithmetic conversions
7686 // between types L and R.
7687 //
7688 // C++ [over.built]p24:
7689 //
7690 // For every pair of promoted arithmetic types L and R, there exist
7691 // candidate operator functions of the form
7692 //
7693 // LR operator?(bool, L, R);
7694 //
7695 // where LR is the result of the usual arithmetic conversions
7696 // between types L and R.
7697 // Our candidates ignore the first parameter.
7698 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007699 if (!HasArithmeticOrEnumeralCandidateType)
7700 return;
7701
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 for (unsigned Left = FirstPromotedArithmeticType;
7703 Left < LastPromotedArithmeticType; ++Left) {
7704 for (unsigned Right = FirstPromotedArithmeticType;
7705 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007706 QualType LandR[2] = { getArithmeticType(Left),
7707 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 QualType Result =
7709 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007710 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007711 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007712 }
7713 }
7714
7715 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7716 // conditional operator for vector types.
7717 for (BuiltinCandidateTypeSet::iterator
7718 Vec1 = CandidateTypes[0].vector_begin(),
7719 Vec1End = CandidateTypes[0].vector_end();
7720 Vec1 != Vec1End; ++Vec1) {
7721 for (BuiltinCandidateTypeSet::iterator
7722 Vec2 = CandidateTypes[1].vector_begin(),
7723 Vec2End = CandidateTypes[1].vector_end();
7724 Vec2 != Vec2End; ++Vec2) {
7725 QualType LandR[2] = { *Vec1, *Vec2 };
7726 QualType Result = S.Context.BoolTy;
7727 if (!isComparison) {
7728 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7729 Result = *Vec1;
7730 else
7731 Result = *Vec2;
7732 }
7733
Richard Smithe54c3072013-05-05 15:51:06 +00007734 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007735 }
7736 }
7737 }
7738
7739 // C++ [over.built]p17:
7740 //
7741 // For every pair of promoted integral types L and R, there
7742 // exist candidate operator functions of the form
7743 //
7744 // LR operator%(L, R);
7745 // LR operator&(L, R);
7746 // LR operator^(L, R);
7747 // LR operator|(L, R);
7748 // L operator<<(L, R);
7749 // L operator>>(L, R);
7750 //
7751 // where LR is the result of the usual arithmetic conversions
7752 // between types L and R.
7753 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007754 if (!HasArithmeticOrEnumeralCandidateType)
7755 return;
7756
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007757 for (unsigned Left = FirstPromotedIntegralType;
7758 Left < LastPromotedIntegralType; ++Left) {
7759 for (unsigned Right = FirstPromotedIntegralType;
7760 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007761 QualType LandR[2] = { getArithmeticType(Left),
7762 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007763 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7764 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007765 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007766 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007767 }
7768 }
7769 }
7770
7771 // C++ [over.built]p20:
7772 //
7773 // For every pair (T, VQ), where T is an enumeration or
7774 // pointer to member type and VQ is either volatile or
7775 // empty, there exist candidate operator functions of the form
7776 //
7777 // VQ T& operator=(VQ T&, T);
7778 void addAssignmentMemberPointerOrEnumeralOverloads() {
7779 /// Set of (canonical) types that we've already handled.
7780 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7781
7782 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7783 for (BuiltinCandidateTypeSet::iterator
7784 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7785 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7786 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007787 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007788 continue;
7789
Richard Smithe54c3072013-05-05 15:51:06 +00007790 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007791 }
7792
7793 for (BuiltinCandidateTypeSet::iterator
7794 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7795 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7796 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007797 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 continue;
7799
Richard Smithe54c3072013-05-05 15:51:06 +00007800 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007801 }
7802 }
7803 }
7804
7805 // C++ [over.built]p19:
7806 //
7807 // For every pair (T, VQ), where T is any type and VQ is either
7808 // volatile or empty, there exist candidate operator functions
7809 // of the form
7810 //
7811 // T*VQ& operator=(T*VQ&, T*);
7812 //
7813 // C++ [over.built]p21:
7814 //
7815 // For every pair (T, VQ), where T is a cv-qualified or
7816 // cv-unqualified object type and VQ is either volatile or
7817 // empty, there exist candidate operator functions of the form
7818 //
7819 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7820 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7821 void addAssignmentPointerOverloads(bool isEqualOp) {
7822 /// Set of (canonical) types that we've already handled.
7823 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7824
7825 for (BuiltinCandidateTypeSet::iterator
7826 Ptr = CandidateTypes[0].pointer_begin(),
7827 PtrEnd = CandidateTypes[0].pointer_end();
7828 Ptr != PtrEnd; ++Ptr) {
7829 // If this is operator=, keep track of the builtin candidates we added.
7830 if (isEqualOp)
7831 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007832 else if (!(*Ptr)->getPointeeType()->isObjectType())
7833 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007834
7835 // non-volatile version
7836 QualType ParamTypes[2] = {
7837 S.Context.getLValueReferenceType(*Ptr),
7838 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7839 };
Richard Smithe54c3072013-05-05 15:51:06 +00007840 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007841 /*IsAssigmentOperator=*/ isEqualOp);
7842
Douglas Gregor5bee2582012-06-04 00:15:09 +00007843 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7844 VisibleTypeConversionsQuals.hasVolatile();
7845 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 // volatile version
7847 ParamTypes[0] =
7848 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007849 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007850 /*IsAssigmentOperator=*/isEqualOp);
7851 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007852
7853 if (!(*Ptr).isRestrictQualified() &&
7854 VisibleTypeConversionsQuals.hasRestrict()) {
7855 // restrict version
7856 ParamTypes[0]
7857 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007858 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007859 /*IsAssigmentOperator=*/isEqualOp);
7860
7861 if (NeedVolatile) {
7862 // volatile restrict version
7863 ParamTypes[0]
7864 = S.Context.getLValueReferenceType(
7865 S.Context.getCVRQualifiedType(*Ptr,
7866 (Qualifiers::Volatile |
7867 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007868 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007869 /*IsAssigmentOperator=*/isEqualOp);
7870 }
7871 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 }
7873
7874 if (isEqualOp) {
7875 for (BuiltinCandidateTypeSet::iterator
7876 Ptr = CandidateTypes[1].pointer_begin(),
7877 PtrEnd = CandidateTypes[1].pointer_end();
7878 Ptr != PtrEnd; ++Ptr) {
7879 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007880 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007881 continue;
7882
Chandler Carruth8e543b32010-12-12 08:17:55 +00007883 QualType ParamTypes[2] = {
7884 S.Context.getLValueReferenceType(*Ptr),
7885 *Ptr,
7886 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887
7888 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 /*IsAssigmentOperator=*/true);
7891
Douglas Gregor5bee2582012-06-04 00:15:09 +00007892 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7893 VisibleTypeConversionsQuals.hasVolatile();
7894 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007895 // volatile version
7896 ParamTypes[0] =
7897 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007898 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7899 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007901
7902 if (!(*Ptr).isRestrictQualified() &&
7903 VisibleTypeConversionsQuals.hasRestrict()) {
7904 // restrict version
7905 ParamTypes[0]
7906 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007907 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7908 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007909
7910 if (NeedVolatile) {
7911 // volatile restrict version
7912 ParamTypes[0]
7913 = S.Context.getLValueReferenceType(
7914 S.Context.getCVRQualifiedType(*Ptr,
7915 (Qualifiers::Volatile |
7916 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007917 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7918 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007919 }
7920 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007921 }
7922 }
7923 }
7924
7925 // C++ [over.built]p18:
7926 //
7927 // For every triple (L, VQ, R), where L is an arithmetic type,
7928 // VQ is either volatile or empty, and R is a promoted
7929 // arithmetic type, there exist candidate operator functions of
7930 // the form
7931 //
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 // VQ L& operator-=(VQ L&, R);
7937 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007938 if (!HasArithmeticOrEnumeralCandidateType)
7939 return;
7940
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007941 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7942 for (unsigned Right = FirstPromotedArithmeticType;
7943 Right < LastPromotedArithmeticType; ++Right) {
7944 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007945 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946
7947 // Add this built-in operator as a candidate (VQ is empty).
7948 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007949 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007950 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 /*IsAssigmentOperator=*/isEqualOp);
7952
7953 // Add this built-in operator as a candidate (VQ is 'volatile').
7954 if (VisibleTypeConversionsQuals.hasVolatile()) {
7955 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007956 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007957 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007959 /*IsAssigmentOperator=*/isEqualOp);
7960 }
7961 }
7962 }
7963
7964 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7965 for (BuiltinCandidateTypeSet::iterator
7966 Vec1 = CandidateTypes[0].vector_begin(),
7967 Vec1End = CandidateTypes[0].vector_end();
7968 Vec1 != Vec1End; ++Vec1) {
7969 for (BuiltinCandidateTypeSet::iterator
7970 Vec2 = CandidateTypes[1].vector_begin(),
7971 Vec2End = CandidateTypes[1].vector_end();
7972 Vec2 != Vec2End; ++Vec2) {
7973 QualType ParamTypes[2];
7974 ParamTypes[1] = *Vec2;
7975 // Add this built-in operator as a candidate (VQ is empty).
7976 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007978 /*IsAssigmentOperator=*/isEqualOp);
7979
7980 // Add this built-in operator as a candidate (VQ is 'volatile').
7981 if (VisibleTypeConversionsQuals.hasVolatile()) {
7982 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7983 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007985 /*IsAssigmentOperator=*/isEqualOp);
7986 }
7987 }
7988 }
7989 }
7990
7991 // C++ [over.built]p22:
7992 //
7993 // For every triple (L, VQ, R), where L is an integral type, VQ
7994 // is either volatile or empty, and R is a promoted integral
7995 // type, there exist candidate operator functions of the form
7996 //
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 // VQ L& operator|=(VQ L&, R);
8003 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008004 if (!HasArithmeticOrEnumeralCandidateType)
8005 return;
8006
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8008 for (unsigned Right = FirstPromotedIntegralType;
8009 Right < LastPromotedIntegralType; ++Right) {
8010 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008011 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008012
8013 // Add this built-in operator as a candidate (VQ is empty).
8014 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008015 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008016 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008017 if (VisibleTypeConversionsQuals.hasVolatile()) {
8018 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008019 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008020 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8021 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008023 }
8024 }
8025 }
8026 }
8027
8028 // C++ [over.operator]p23:
8029 //
8030 // There also exist candidate operator functions of the form
8031 //
8032 // bool operator!(bool);
8033 // bool operator&&(bool, bool);
8034 // bool operator||(bool, bool);
8035 void addExclaimOverload() {
8036 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008037 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008038 /*IsAssignmentOperator=*/false,
8039 /*NumContextualBoolArguments=*/1);
8040 }
8041 void addAmpAmpOrPipePipeOverload() {
8042 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008043 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008044 /*IsAssignmentOperator=*/false,
8045 /*NumContextualBoolArguments=*/2);
8046 }
8047
8048 // C++ [over.built]p13:
8049 //
8050 // For every cv-qualified or cv-unqualified object type T there
8051 // exist candidate operator functions of the form
8052 //
8053 // T* operator+(T*, ptrdiff_t); [ABOVE]
8054 // T& operator[](T*, ptrdiff_t);
8055 // T* operator-(T*, ptrdiff_t); [ABOVE]
8056 // T* operator+(ptrdiff_t, T*); [ABOVE]
8057 // T& operator[](ptrdiff_t, T*);
8058 void addSubscriptOverloads() {
8059 for (BuiltinCandidateTypeSet::iterator
8060 Ptr = CandidateTypes[0].pointer_begin(),
8061 PtrEnd = CandidateTypes[0].pointer_end();
8062 Ptr != PtrEnd; ++Ptr) {
8063 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8064 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008065 if (!PointeeType->isObjectType())
8066 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008068 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8069
8070 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008071 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 }
8073
8074 for (BuiltinCandidateTypeSet::iterator
8075 Ptr = CandidateTypes[1].pointer_begin(),
8076 PtrEnd = CandidateTypes[1].pointer_end();
8077 Ptr != PtrEnd; ++Ptr) {
8078 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8079 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008080 if (!PointeeType->isObjectType())
8081 continue;
8082
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008083 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8084
8085 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008086 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008087 }
8088 }
8089
8090 // C++ [over.built]p11:
8091 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8092 // C1 is the same type as C2 or is a derived class of C2, T is an object
8093 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8094 // there exist candidate operator functions of the form
8095 //
8096 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8097 //
8098 // where CV12 is the union of CV1 and CV2.
8099 void addArrowStarOverloads() {
8100 for (BuiltinCandidateTypeSet::iterator
8101 Ptr = CandidateTypes[0].pointer_begin(),
8102 PtrEnd = CandidateTypes[0].pointer_end();
8103 Ptr != PtrEnd; ++Ptr) {
8104 QualType C1Ty = (*Ptr);
8105 QualType C1;
8106 QualifierCollector Q1;
8107 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8108 if (!isa<RecordType>(C1))
8109 continue;
8110 // heuristic to reduce number of builtin candidates in the set.
8111 // Add volatile/restrict version only if there are conversions to a
8112 // volatile/restrict type.
8113 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8114 continue;
8115 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8116 continue;
8117 for (BuiltinCandidateTypeSet::iterator
8118 MemPtr = CandidateTypes[1].member_pointer_begin(),
8119 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8120 MemPtr != MemPtrEnd; ++MemPtr) {
8121 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8122 QualType C2 = QualType(mptr->getClass(), 0);
8123 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008124 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008125 break;
8126 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8127 // build CV12 T&
8128 QualType T = mptr->getPointeeType();
8129 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8130 T.isVolatileQualified())
8131 continue;
8132 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8133 T.isRestrictQualified())
8134 continue;
8135 T = Q1.apply(S.Context, T);
8136 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008137 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008138 }
8139 }
8140 }
8141
8142 // Note that we don't consider the first argument, since it has been
8143 // contextually converted to bool long ago. The candidates below are
8144 // therefore added as binary.
8145 //
8146 // C++ [over.built]p25:
8147 // For every type T, where T is a pointer, pointer-to-member, or scoped
8148 // enumeration type, there exist candidate operator functions of the form
8149 //
8150 // T operator?(bool, T, T);
8151 //
8152 void addConditionalOperatorOverloads() {
8153 /// Set of (canonical) types that we've already handled.
8154 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8155
8156 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8157 for (BuiltinCandidateTypeSet::iterator
8158 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8159 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8160 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008161 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008162 continue;
8163
8164 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008165 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008166 }
8167
8168 for (BuiltinCandidateTypeSet::iterator
8169 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8170 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8171 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008172 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008173 continue;
8174
8175 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008176 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008177 }
8178
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008179 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008180 for (BuiltinCandidateTypeSet::iterator
8181 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8182 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8183 Enum != EnumEnd; ++Enum) {
8184 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8185 continue;
8186
David Blaikie82e95a32014-11-19 07:49:47 +00008187 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008188 continue;
8189
8190 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008191 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 }
8193 }
8194 }
8195 }
8196};
8197
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008198} // end anonymous namespace
8199
8200/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8201/// operator overloads to the candidate set (C++ [over.built]), based
8202/// on the operator @p Op and the arguments given. For example, if the
8203/// operator is a binary '+', this routine might add "int
8204/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008205void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8206 SourceLocation OpLoc,
8207 ArrayRef<Expr *> Args,
8208 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008209 // Find all of the types that the arguments can convert to, but only
8210 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008211 // that make use of these types. Also record whether we encounter non-record
8212 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008213 Qualifiers VisibleTypeConversionsQuals;
8214 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008215 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008216 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008217
8218 bool HasNonRecordCandidateType = false;
8219 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008220 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008221 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008222 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008223 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8224 OpLoc,
8225 true,
8226 (Op == OO_Exclaim ||
8227 Op == OO_AmpAmp ||
8228 Op == OO_PipePipe),
8229 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008230 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8231 CandidateTypes[ArgIdx].hasNonRecordTypes();
8232 HasArithmeticOrEnumeralCandidateType =
8233 HasArithmeticOrEnumeralCandidateType ||
8234 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008235 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008236
Chandler Carruth00a38332010-12-13 01:44:01 +00008237 // Exit early when no non-record types have been added to the candidate set
8238 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008239 //
8240 // We can't exit early for !, ||, or &&, since there we have always have
8241 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008242 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008243 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008244 return;
8245
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008246 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008247 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008248 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008249 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008250 CandidateTypes, CandidateSet);
8251
8252 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008253 switch (Op) {
8254 case OO_None:
8255 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008256 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008257
Chandler Carruth5184de02010-12-12 08:51:33 +00008258 case OO_New:
8259 case OO_Delete:
8260 case OO_Array_New:
8261 case OO_Array_Delete:
8262 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008263 llvm_unreachable(
8264 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008265
8266 case OO_Comma:
8267 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008268 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008269 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008270 // -- For the operator ',', the unary operator '&', the
8271 // operator '->', or the operator 'co_await', the
8272 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008273 break;
8274
8275 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008276 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008278 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008279
8280 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008281 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008282 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008283 } else {
8284 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8285 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8286 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008287 break;
8288
Chandler Carruth5184de02010-12-12 08:51:33 +00008289 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008290 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008291 OpBuilder.addUnaryStarPointerOverloads();
8292 else
8293 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8294 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008295
Chandler Carruth5184de02010-12-12 08:51:33 +00008296 case OO_Slash:
8297 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008298 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008299
8300 case OO_PlusPlus:
8301 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008302 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8303 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008304 break;
8305
Douglas Gregor84605ae2009-08-24 13:43:27 +00008306 case OO_EqualEqual:
8307 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008308 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008309 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008310
Douglas Gregora11693b2008-11-12 17:17:38 +00008311 case OO_Less:
8312 case OO_Greater:
8313 case OO_LessEqual:
8314 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008315 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008316 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8317 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008318
Douglas Gregora11693b2008-11-12 17:17:38 +00008319 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008320 case OO_Caret:
8321 case OO_Pipe:
8322 case OO_LessLess:
8323 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008324 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008325 break;
8326
Chandler Carruth5184de02010-12-12 08:51:33 +00008327 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008328 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008329 // C++ [over.match.oper]p3:
8330 // -- For the operator ',', the unary operator '&', or the
8331 // operator '->', the built-in candidates set is empty.
8332 break;
8333
8334 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8335 break;
8336
8337 case OO_Tilde:
8338 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8339 break;
8340
Douglas Gregora11693b2008-11-12 17:17:38 +00008341 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008343 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008344
8345 case OO_PlusEqual:
8346 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008347 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008348 // Fall through.
8349
8350 case OO_StarEqual:
8351 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008352 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008353 break;
8354
8355 case OO_PercentEqual:
8356 case OO_LessLessEqual:
8357 case OO_GreaterGreaterEqual:
8358 case OO_AmpEqual:
8359 case OO_CaretEqual:
8360 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008361 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008362 break;
8363
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008364 case OO_Exclaim:
8365 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008366 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008367
Douglas Gregora11693b2008-11-12 17:17:38 +00008368 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008369 case OO_PipePipe:
8370 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008371 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008372
8373 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008374 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008375 break;
8376
8377 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008378 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008379 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008380
8381 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008383 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8384 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008385 }
8386}
8387
Douglas Gregore254f902009-02-04 00:32:51 +00008388/// \brief Add function candidates found via argument-dependent lookup
8389/// to the set of overloading candidates.
8390///
8391/// This routine performs argument-dependent name lookup based on the
8392/// given function name (which may also be an operator name) and adds
8393/// all of the overload candidates found by ADL to the overload
8394/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008395void
Douglas Gregore254f902009-02-04 00:32:51 +00008396Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008397 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008398 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008399 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008400 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008401 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008402 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008403
John McCall91f61fc2010-01-26 06:04:06 +00008404 // FIXME: This approach for uniquing ADL results (and removing
8405 // redundant candidates from the set) relies on pointer-equality,
8406 // which means we need to key off the canonical decl. However,
8407 // always going back to the canonical decl might not get us the
8408 // right set of default arguments. What default arguments are
8409 // we supposed to consider on ADL candidates, anyway?
8410
Douglas Gregorcabea402009-09-22 15:41:20 +00008411 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008412 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008413
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008414 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008415 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8416 CandEnd = CandidateSet.end();
8417 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008418 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008419 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008420 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008421 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008422 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008423
8424 // For each of the ADL candidates we found, add it to the overload
8425 // set.
John McCall8fe68082010-01-26 07:16:45 +00008426 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008427 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008428 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008429 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008430 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008431
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008432 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8433 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008434 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008435 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008436 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008437 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008438 }
Douglas Gregore254f902009-02-04 00:32:51 +00008439}
8440
George Burgess IV2a6150d2015-10-16 01:17:38 +00008441// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8442// Cand2 for overloading. This function assumes that all of the enable_if attrs
8443// on Cand1 and Cand2 have conditions that evaluate to true.
8444//
8445// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8446// Cand1's first N enable_if attributes have precisely the same conditions as
8447// Cand2's first N enable_if attributes (where N = the number of enable_if
8448// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8449static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8450 const FunctionDecl *Cand2) {
8451
8452 // FIXME: The next several lines are just
8453 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8454 // instead of reverse order which is how they're stored in the AST.
8455 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8456 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8457
8458 // Candidate 1 is better if it has strictly more attributes and
8459 // the common sequence is identical.
8460 if (Cand1Attrs.size() <= Cand2Attrs.size())
8461 return false;
8462
8463 auto Cand1I = Cand1Attrs.begin();
8464 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8465 for (auto &Cand2A : Cand2Attrs) {
8466 Cand1ID.clear();
8467 Cand2ID.clear();
8468
8469 auto &Cand1A = *Cand1I++;
8470 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8471 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8472 if (Cand1ID != Cand2ID)
8473 return false;
8474 }
8475
8476 return true;
8477}
8478
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008479/// isBetterOverloadCandidate - Determines whether the first overload
8480/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008481bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8482 const OverloadCandidate &Cand2,
8483 SourceLocation Loc,
8484 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008485 // Define viable functions to be better candidates than non-viable
8486 // functions.
8487 if (!Cand2.Viable)
8488 return Cand1.Viable;
8489 else if (!Cand1.Viable)
8490 return false;
8491
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008492 // C++ [over.match.best]p1:
8493 //
8494 // -- if F is a static member function, ICS1(F) is defined such
8495 // that ICS1(F) is neither better nor worse than ICS1(G) for
8496 // any function G, and, symmetrically, ICS1(G) is neither
8497 // better nor worse than ICS1(F).
8498 unsigned StartArg = 0;
8499 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8500 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008501
Douglas Gregord3cb3562009-07-07 23:38:56 +00008502 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008503 // A viable function F1 is defined to be a better function than another
8504 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008505 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008506 unsigned NumArgs = Cand1.NumConversions;
8507 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008508 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008509 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008510 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008511 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008512 Cand2.Conversions[ArgIdx])) {
8513 case ImplicitConversionSequence::Better:
8514 // Cand1 has a better conversion sequence.
8515 HasBetterConversion = true;
8516 break;
8517
8518 case ImplicitConversionSequence::Worse:
8519 // Cand1 can't be better than Cand2.
8520 return false;
8521
8522 case ImplicitConversionSequence::Indistinguishable:
8523 // Do nothing.
8524 break;
8525 }
8526 }
8527
Mike Stump11289f42009-09-09 15:08:12 +00008528 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008529 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008530 if (HasBetterConversion)
8531 return true;
8532
Douglas Gregora1f013e2008-11-07 22:36:19 +00008533 // -- the context is an initialization by user-defined conversion
8534 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8535 // from the return type of F1 to the destination type (i.e.,
8536 // the type of the entity being initialized) is a better
8537 // conversion sequence than the standard conversion sequence
8538 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008539 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008540 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008541 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008542 // First check whether we prefer one of the conversion functions over the
8543 // other. This only distinguishes the results in non-standard, extension
8544 // cases such as the conversion from a lambda closure type to a function
8545 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008546 ImplicitConversionSequence::CompareKind Result =
8547 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8548 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008549 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008550 Cand1.FinalConversion,
8551 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008552
Richard Smithec2748a2014-05-17 04:36:39 +00008553 if (Result != ImplicitConversionSequence::Indistinguishable)
8554 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008555
8556 // FIXME: Compare kind of reference binding if conversion functions
8557 // convert to a reference type used in direct reference binding, per
8558 // C++14 [over.match.best]p1 section 2 bullet 3.
8559 }
8560
8561 // -- F1 is a non-template function and F2 is a function template
8562 // specialization, or, if not that,
8563 bool Cand1IsSpecialization = Cand1.Function &&
8564 Cand1.Function->getPrimaryTemplate();
8565 bool Cand2IsSpecialization = Cand2.Function &&
8566 Cand2.Function->getPrimaryTemplate();
8567 if (Cand1IsSpecialization != Cand2IsSpecialization)
8568 return Cand2IsSpecialization;
8569
8570 // -- F1 and F2 are function template specializations, and the function
8571 // template for F1 is more specialized than the template for F2
8572 // according to the partial ordering rules described in 14.5.5.2, or,
8573 // if not that,
8574 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8575 if (FunctionTemplateDecl *BetterTemplate
8576 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8577 Cand2.Function->getPrimaryTemplate(),
8578 Loc,
8579 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8580 : TPOC_Call,
8581 Cand1.ExplicitCallArguments,
8582 Cand2.ExplicitCallArguments))
8583 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008584 }
8585
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008586 // Check for enable_if value-based overload resolution.
8587 if (Cand1.Function && Cand2.Function &&
8588 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008589 Cand2.Function->hasAttr<EnableIfAttr>()))
8590 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008591
Artem Belevich94a55e82015-09-22 17:22:59 +00008592 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8593 Cand1.Function && Cand2.Function) {
8594 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8595 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8596 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8597 }
8598
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008599 bool HasPS1 = Cand1.Function != nullptr &&
8600 functionHasPassObjectSizeParams(Cand1.Function);
8601 bool HasPS2 = Cand2.Function != nullptr &&
8602 functionHasPassObjectSizeParams(Cand2.Function);
8603 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008604}
8605
Richard Smith2dbe4042015-11-04 19:26:32 +00008606/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008607/// name lookup and overload resolution. This applies when the same internal/no
8608/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008609/// the same header). In such a case, we don't consider the declarations to
8610/// declare the same entity, but we also don't want lookups with both
8611/// declarations visible to be ambiguous in some cases (this happens when using
8612/// a modularized libstdc++).
8613bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8614 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008615 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8616 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8617 if (!VA || !VB)
8618 return false;
8619
8620 // The declarations must be declaring the same name as an internal linkage
8621 // entity in different modules.
8622 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8623 VB->getDeclContext()->getRedeclContext()) ||
8624 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8625 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8626 VA->isExternallyVisible() || VB->isExternallyVisible())
8627 return false;
8628
8629 // Check that the declarations appear to be equivalent.
8630 //
8631 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8632 // For constants and functions, we should check the initializer or body is
8633 // the same. For non-constant variables, we shouldn't allow it at all.
8634 if (Context.hasSameType(VA->getType(), VB->getType()))
8635 return true;
8636
8637 // Enum constants within unnamed enumerations will have different types, but
8638 // may still be similar enough to be interchangeable for our purposes.
8639 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8640 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8641 // Only handle anonymous enums. If the enumerations were named and
8642 // equivalent, they would have been merged to the same type.
8643 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8644 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8645 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8646 !Context.hasSameType(EnumA->getIntegerType(),
8647 EnumB->getIntegerType()))
8648 return false;
8649 // Allow this only if the value is the same for both enumerators.
8650 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8651 }
8652 }
8653
8654 // Nothing else is sufficiently similar.
8655 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008656}
8657
8658void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8659 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8660 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8661
8662 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8663 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8664 << !M << (M ? M->getFullModuleName() : "");
8665
8666 for (auto *E : Equiv) {
8667 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8668 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8669 << !M << (M ? M->getFullModuleName() : "");
8670 }
Richard Smith896c66e2015-10-21 07:13:52 +00008671}
8672
Mike Stump11289f42009-09-09 15:08:12 +00008673/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008674/// within an overload candidate set.
8675///
James Dennettffad8b72012-06-22 08:10:18 +00008676/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008677/// which overload resolution occurs.
8678///
James Dennettffad8b72012-06-22 08:10:18 +00008679/// \param Best If overload resolution was successful or found a deleted
8680/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008681///
8682/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008683OverloadingResult
8684OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008685 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008686 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008687 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008688 Best = end();
8689 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8690 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008691 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008692 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008693 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008694 }
8695
8696 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008697 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008698 return OR_No_Viable_Function;
8699
Richard Smith2dbe4042015-11-04 19:26:32 +00008700 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008701
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008702 // Make sure that this function is better than every other viable
8703 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008704 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008705 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008706 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008707 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008708 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008709 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8710 Cand->Function)) {
8711 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008712 continue;
8713 }
8714
John McCall5c32be02010-08-24 20:38:10 +00008715 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008716 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008717 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008718 }
Mike Stump11289f42009-09-09 15:08:12 +00008719
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008720 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008721 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008722 (Best->Function->isDeleted() ||
8723 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008724 return OR_Deleted;
8725
Richard Smith2dbe4042015-11-04 19:26:32 +00008726 if (!EquivalentCands.empty())
8727 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8728 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008729
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008730 return OR_Success;
8731}
8732
John McCall53262c92010-01-12 02:15:36 +00008733namespace {
8734
8735enum OverloadCandidateKind {
8736 oc_function,
8737 oc_method,
8738 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008739 oc_function_template,
8740 oc_method_template,
8741 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008742 oc_implicit_default_constructor,
8743 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008744 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008745 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008746 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008747 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008748};
8749
John McCalle1ac8d12010-01-13 00:25:19 +00008750OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8751 FunctionDecl *Fn,
8752 std::string &Description) {
8753 bool isTemplate = false;
8754
8755 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8756 isTemplate = true;
8757 Description = S.getTemplateArgumentBindingsText(
8758 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8759 }
John McCallfd0b2f82010-01-06 09:43:14 +00008760
8761 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008762 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008763 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008764
Sebastian Redl08905022011-02-05 19:23:19 +00008765 if (Ctor->getInheritedConstructor())
8766 return oc_implicit_inherited_constructor;
8767
Alexis Hunt119c10e2011-05-25 23:16:36 +00008768 if (Ctor->isDefaultConstructor())
8769 return oc_implicit_default_constructor;
8770
8771 if (Ctor->isMoveConstructor())
8772 return oc_implicit_move_constructor;
8773
8774 assert(Ctor->isCopyConstructor() &&
8775 "unexpected sort of implicit constructor");
8776 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008777 }
8778
8779 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8780 // This actually gets spelled 'candidate function' for now, but
8781 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008782 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008783 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008784
Alexis Hunt119c10e2011-05-25 23:16:36 +00008785 if (Meth->isMoveAssignmentOperator())
8786 return oc_implicit_move_assignment;
8787
Douglas Gregor12695102012-02-10 08:36:38 +00008788 if (Meth->isCopyAssignmentOperator())
8789 return oc_implicit_copy_assignment;
8790
8791 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8792 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008793 }
8794
John McCalle1ac8d12010-01-13 00:25:19 +00008795 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008796}
8797
Larisse Voufo98b20f12013-07-19 23:00:19 +00008798void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008799 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8800 if (!Ctor) return;
8801
8802 Ctor = Ctor->getInheritedConstructor();
8803 if (!Ctor) return;
8804
8805 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8806}
8807
John McCall53262c92010-01-12 02:15:36 +00008808} // end anonymous namespace
8809
George Burgess IV5f21c712015-10-12 19:57:04 +00008810static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8811 const FunctionDecl *FD) {
8812 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8813 bool AlwaysTrue;
8814 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8815 return false;
8816 if (!AlwaysTrue)
8817 return false;
8818 }
8819 return true;
8820}
8821
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008822/// \brief Returns true if we can take the address of the function.
8823///
8824/// \param Complain - If true, we'll emit a diagnostic
8825/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8826/// we in overload resolution?
8827/// \param Loc - The location of the statement we're complaining about. Ignored
8828/// if we're not complaining, or if we're in overload resolution.
8829static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8830 bool Complain,
8831 bool InOverloadResolution,
8832 SourceLocation Loc) {
8833 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8834 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008835 if (InOverloadResolution)
8836 S.Diag(FD->getLocStart(),
8837 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8838 else
8839 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8840 }
8841 return false;
8842 }
8843
8844 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8845 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8846 if (I == FD->param_end())
8847 return true;
8848
8849 if (Complain) {
8850 // Add one to ParamNo because it's user-facing
8851 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8852 if (InOverloadResolution)
8853 S.Diag(FD->getLocation(),
8854 diag::note_ovl_candidate_has_pass_object_size_params)
8855 << ParamNo;
8856 else
8857 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8858 << FD << ParamNo;
8859 }
8860 return false;
8861}
8862
8863static bool checkAddressOfCandidateIsAvailable(Sema &S,
8864 const FunctionDecl *FD) {
8865 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8866 /*InOverloadResolution=*/true,
8867 /*Loc=*/SourceLocation());
8868}
8869
8870bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8871 bool Complain,
8872 SourceLocation Loc) {
8873 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8874 /*InOverloadResolution=*/false,
8875 Loc);
8876}
8877
John McCall53262c92010-01-12 02:15:36 +00008878// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008879void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8880 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008881 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8882 return;
8883
John McCalle1ac8d12010-01-13 00:25:19 +00008884 std::string FnDesc;
8885 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008886 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8887 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008888
8889 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008890 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008891 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008892}
8893
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008894// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008895// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008896void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8897 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008898 assert(OverloadedExpr->getType() == Context.OverloadTy);
8899
8900 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8901 OverloadExpr *OvlExpr = Ovl.Expression;
8902
8903 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8904 IEnd = OvlExpr->decls_end();
8905 I != IEnd; ++I) {
8906 if (FunctionTemplateDecl *FunTmpl =
8907 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008908 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8909 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008910 } else if (FunctionDecl *Fun
8911 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008912 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008913 }
8914 }
8915}
8916
John McCall0d1da222010-01-12 00:44:57 +00008917/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8918/// "lead" diagnostic; it will be given two arguments, the source and
8919/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008920void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8921 Sema &S,
8922 SourceLocation CaretLoc,
8923 const PartialDiagnostic &PDiag) const {
8924 S.Diag(CaretLoc, PDiag)
8925 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008926 // FIXME: The note limiting machinery is borrowed from
8927 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8928 // refactoring here.
8929 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8930 unsigned CandsShown = 0;
8931 AmbiguousConversionSequence::const_iterator I, E;
8932 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8933 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8934 break;
8935 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008936 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008937 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008938 if (I != E)
8939 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008940}
8941
Richard Smith17c00b42014-11-12 01:24:00 +00008942static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008943 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00008944 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8945 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008946 assert(Cand->Function && "for now, candidate must be a function");
8947 FunctionDecl *Fn = Cand->Function;
8948
8949 // There's a conversion slot for the object argument if this is a
8950 // non-constructor method. Note that 'I' corresponds the
8951 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008952 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008953 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008954 if (I == 0)
8955 isObjectArgument = true;
8956 else
8957 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008958 }
8959
John McCalle1ac8d12010-01-13 00:25:19 +00008960 std::string FnDesc;
8961 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8962
John McCall6a61b522010-01-13 09:16:55 +00008963 Expr *FromExpr = Conv.Bad.FromExpr;
8964 QualType FromTy = Conv.Bad.getFromType();
8965 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008966
John McCallfb7ad0f2010-02-02 02:42:52 +00008967 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008968 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008969 Expr *E = FromExpr->IgnoreParens();
8970 if (isa<UnaryOperator>(E))
8971 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008972 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008973
8974 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8975 << (unsigned) FnKind << FnDesc
8976 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8977 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008978 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008979 return;
8980 }
8981
John McCall6d174642010-01-23 08:10:49 +00008982 // Do some hand-waving analysis to see if the non-viability is due
8983 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008984 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8985 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8986 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8987 CToTy = RT->getPointeeType();
8988 else {
8989 // TODO: detect and diagnose the full richness of const mismatches.
8990 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8991 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8992 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8993 }
8994
8995 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8996 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008997 Qualifiers FromQs = CFromTy.getQualifiers();
8998 Qualifiers ToQs = CToTy.getQualifiers();
8999
9000 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9002 << (unsigned) FnKind << FnDesc
9003 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9004 << FromTy
9005 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9006 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009007 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009008 return;
9009 }
9010
John McCall31168b02011-06-15 23:02:42 +00009011 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009013 << (unsigned) FnKind << FnDesc
9014 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9015 << FromTy
9016 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9017 << (unsigned) isObjectArgument << I+1;
9018 MaybeEmitInheritedConstructorNote(S, Fn);
9019 return;
9020 }
9021
Douglas Gregoraec25842011-04-26 23:16:46 +00009022 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9023 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9024 << (unsigned) FnKind << FnDesc
9025 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9026 << FromTy
9027 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9028 << (unsigned) isObjectArgument << I+1;
9029 MaybeEmitInheritedConstructorNote(S, Fn);
9030 return;
9031 }
9032
John McCall47000992010-01-14 03:28:57 +00009033 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9034 assert(CVR && "unexpected qualifiers mismatch");
9035
9036 if (isObjectArgument) {
9037 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9038 << (unsigned) FnKind << FnDesc
9039 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9040 << FromTy << (CVR - 1);
9041 } else {
9042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9043 << (unsigned) FnKind << FnDesc
9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9045 << FromTy << (CVR - 1) << I+1;
9046 }
Sebastian Redl08905022011-02-05 19:23:19 +00009047 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009048 return;
9049 }
9050
Sebastian Redla72462c2011-09-24 17:48:32 +00009051 // Special diagnostic for failure to convert an initializer list, since
9052 // telling the user that it has type void is not useful.
9053 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9055 << (unsigned) FnKind << FnDesc
9056 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9057 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9058 MaybeEmitInheritedConstructorNote(S, Fn);
9059 return;
9060 }
9061
John McCall6d174642010-01-23 08:10:49 +00009062 // Diagnose references or pointers to incomplete types differently,
9063 // since it's far from impossible that the incompleteness triggered
9064 // the failure.
9065 QualType TempFromTy = FromTy.getNonReferenceType();
9066 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9067 TempFromTy = PTy->getPointeeType();
9068 if (TempFromTy->isIncompleteType()) {
9069 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9070 << (unsigned) FnKind << FnDesc
9071 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9072 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009073 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009074 return;
9075 }
9076
Douglas Gregor56f2e342010-06-30 23:01:39 +00009077 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009078 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009079 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9080 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9081 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9082 FromPtrTy->getPointeeType()) &&
9083 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9084 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009085 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009086 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009087 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009088 }
9089 } else if (const ObjCObjectPointerType *FromPtrTy
9090 = FromTy->getAs<ObjCObjectPointerType>()) {
9091 if (const ObjCObjectPointerType *ToPtrTy
9092 = ToTy->getAs<ObjCObjectPointerType>())
9093 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9094 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9095 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9096 FromPtrTy->getPointeeType()) &&
9097 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009098 BaseToDerivedConversion = 2;
9099 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009100 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9101 !FromTy->isIncompleteType() &&
9102 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009103 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009104 BaseToDerivedConversion = 3;
9105 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9106 ToTy.getNonReferenceType().getCanonicalType() ==
9107 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9109 << (unsigned) FnKind << FnDesc
9110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9111 << (unsigned) isObjectArgument << I + 1;
9112 MaybeEmitInheritedConstructorNote(S, Fn);
9113 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009114 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009117 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009118 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009119 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009120 << (unsigned) FnKind << FnDesc
9121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009122 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009123 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009124 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009125 return;
9126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009127
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009128 if (isa<ObjCObjectPointerType>(CFromTy) &&
9129 isa<PointerType>(CToTy)) {
9130 Qualifiers FromQs = CFromTy.getQualifiers();
9131 Qualifiers ToQs = CToTy.getQualifiers();
9132 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9134 << (unsigned) FnKind << FnDesc
9135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9136 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9137 MaybeEmitInheritedConstructorNote(S, Fn);
9138 return;
9139 }
9140 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009141
9142 if (TakingCandidateAddress &&
9143 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9144 return;
9145
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009146 // Emit the generic diagnostic and, optionally, add the hints to it.
9147 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9148 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009149 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009150 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9151 << (unsigned) (Cand->Fix.Kind);
9152
9153 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009154 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9155 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009156 FDiag << *HI;
9157 S.Diag(Fn->getLocation(), FDiag);
9158
Sebastian Redl08905022011-02-05 19:23:19 +00009159 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009160}
9161
Larisse Voufo98b20f12013-07-19 23:00:19 +00009162/// Additional arity mismatch diagnosis specific to a function overload
9163/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9164/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009165static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9166 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009167 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009168 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009169
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009170 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009171 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009172 // right number of arguments, because only overloaded operators have
9173 // the weird behavior of overloading member and non-member functions.
9174 // Just don't report anything.
9175 if (Fn->isInvalidDecl() &&
9176 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009177 return true;
9178
9179 if (NumArgs < MinParams) {
9180 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9181 (Cand->FailureKind == ovl_fail_bad_deduction &&
9182 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9183 } else {
9184 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9185 (Cand->FailureKind == ovl_fail_bad_deduction &&
9186 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9187 }
9188
9189 return false;
9190}
9191
9192/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009193static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009194 assert(isa<FunctionDecl>(D) &&
9195 "The templated declaration should at least be a function"
9196 " when diagnosing bad template argument deduction due to too many"
9197 " or too few arguments");
9198
9199 FunctionDecl *Fn = cast<FunctionDecl>(D);
9200
9201 // TODO: treat calls to a missing default constructor as a special case
9202 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9203 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009204
John McCall6a61b522010-01-13 09:16:55 +00009205 // at least / at most / exactly
9206 unsigned mode, modeCount;
9207 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009208 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9209 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009210 mode = 0; // "at least"
9211 else
9212 mode = 2; // "exactly"
9213 modeCount = MinParams;
9214 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009215 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009216 mode = 1; // "at most"
9217 else
9218 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009219 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009220 }
9221
9222 std::string Description;
9223 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9224
Richard Smith10ff50d2012-05-11 05:16:41 +00009225 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009227 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9228 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009229 else
9230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009231 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9232 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009233 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009234}
9235
Larisse Voufo98b20f12013-07-19 23:00:19 +00009236/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009237static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9238 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009239 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9240 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9241}
Larisse Voufo47c08452013-07-19 22:53:23 +00009242
Richard Smith17c00b42014-11-12 01:24:00 +00009243static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9245 return FD->getDescribedFunctionTemplate();
9246 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9247 return RD->getDescribedClassTemplate();
9248
9249 llvm_unreachable("Unsupported: Getting the described template declaration"
9250 " for bad deduction diagnosis");
9251}
9252
9253/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009254static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9255 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009256 unsigned NumArgs,
9257 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009258 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009259 NamedDecl *ParamD;
9260 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9261 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9262 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009263 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009264 case Sema::TDK_Success:
9265 llvm_unreachable("TDK_success while diagnosing bad deduction");
9266
9267 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009268 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009269 S.Diag(Templated->getLocation(),
9270 diag::note_ovl_candidate_incomplete_deduction)
9271 << ParamD->getDeclName();
9272 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009273 return;
9274 }
9275
John McCall42d7d192010-08-05 09:05:08 +00009276 case Sema::TDK_Underqualified: {
9277 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9278 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9279
Larisse Voufo98b20f12013-07-19 23:00:19 +00009280 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009281
9282 // Param will have been canonicalized, but it should just be a
9283 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009284 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009285 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009286 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009287 assert(S.Context.hasSameType(Param, NonCanonParam));
9288
9289 // Arg has also been canonicalized, but there's nothing we can do
9290 // about that. It also doesn't matter as much, because it won't
9291 // have any template parameters in it (because deduction isn't
9292 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009293 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009294
Larisse Voufo98b20f12013-07-19 23:00:19 +00009295 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9296 << ParamD->getDeclName() << Arg << NonCanonParam;
9297 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009298 return;
9299 }
9300
9301 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009302 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009303 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009304 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009305 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009306 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009307 which = 1;
9308 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009309 which = 2;
9310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009311
Larisse Voufo98b20f12013-07-19 23:00:19 +00009312 S.Diag(Templated->getLocation(),
9313 diag::note_ovl_candidate_inconsistent_deduction)
9314 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9315 << *DeductionFailure.getSecondArg();
9316 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009317 return;
9318 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009319
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009320 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009321 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009322 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009323 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009324 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009325 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009326 else {
9327 int index = 0;
9328 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9329 index = TTP->getIndex();
9330 else if (NonTypeTemplateParmDecl *NTTP
9331 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9332 index = NTTP->getIndex();
9333 else
9334 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009335 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009336 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009337 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009338 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009339 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009340 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009341
Douglas Gregor02eb4832010-05-08 18:13:28 +00009342 case Sema::TDK_TooManyArguments:
9343 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009344 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009345 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009346
9347 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009348 S.Diag(Templated->getLocation(),
9349 diag::note_ovl_candidate_instantiation_depth);
9350 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009351 return;
9352
9353 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009354 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009355 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009356 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009357 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009358 TemplateArgString = " ";
9359 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009360 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009361 }
9362
Richard Smith6f8d2c62012-05-09 05:17:00 +00009363 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009364 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009365 if (PDiag && PDiag->second.getDiagID() ==
9366 diag::err_typename_nested_not_found_enable_if) {
9367 // FIXME: Use the source range of the condition, and the fully-qualified
9368 // name of the enable_if template. These are both present in PDiag.
9369 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9370 << "'enable_if'" << TemplateArgString;
9371 return;
9372 }
9373
Richard Smith9ca64612012-05-07 09:03:25 +00009374 // Format the SFINAE diagnostic into the argument string.
9375 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9376 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009377 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009378 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009379 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009380 SFINAEArgString = ": ";
9381 R = SourceRange(PDiag->first, PDiag->first);
9382 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9383 }
9384
Larisse Voufo98b20f12013-07-19 23:00:19 +00009385 S.Diag(Templated->getLocation(),
9386 diag::note_ovl_candidate_substitution_failure)
9387 << TemplateArgString << SFINAEArgString << R;
9388 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009389 return;
9390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009391
Richard Smith8c6eeb92013-01-31 04:03:12 +00009392 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009393 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9394 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009395 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009396 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009397 return;
9398 }
9399
Richard Trieue3732352013-04-08 21:11:40 +00009400 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009401 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009402 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9403 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009404 if (FirstTA.getKind() == TemplateArgument::Template &&
9405 SecondTA.getKind() == TemplateArgument::Template) {
9406 TemplateName FirstTN = FirstTA.getAsTemplate();
9407 TemplateName SecondTN = SecondTA.getAsTemplate();
9408 if (FirstTN.getKind() == TemplateName::Template &&
9409 SecondTN.getKind() == TemplateName::Template) {
9410 if (FirstTN.getAsTemplateDecl()->getName() ==
9411 SecondTN.getAsTemplateDecl()->getName()) {
9412 // FIXME: This fixes a bad diagnostic where both templates are named
9413 // the same. This particular case is a bit difficult since:
9414 // 1) It is passed as a string to the diagnostic printer.
9415 // 2) The diagnostic printer only attempts to find a better
9416 // name for types, not decls.
9417 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009418 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009419 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9420 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9421 return;
9422 }
9423 }
9424 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009425
9426 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9427 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9428 return;
9429
Faisal Vali2b391ab2013-09-26 19:54:12 +00009430 // FIXME: For generic lambda parameters, check if the function is a lambda
9431 // call operator, and if so, emit a prettier and more informative
9432 // diagnostic that mentions 'auto' and lambda in addition to
9433 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009434 S.Diag(Templated->getLocation(),
9435 diag::note_ovl_candidate_non_deduced_mismatch)
9436 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009437 return;
Richard Trieue3732352013-04-08 21:11:40 +00009438 }
John McCall8b9ed552010-02-01 18:53:26 +00009439 // TODO: diagnose these individually, then kill off
9440 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009441 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009442 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9443 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009444 return;
9445 }
9446}
9447
Larisse Voufo98b20f12013-07-19 23:00:19 +00009448/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009449static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009450 unsigned NumArgs,
9451 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009452 unsigned TDK = Cand->DeductionFailure.Result;
9453 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9454 if (CheckArityMismatch(S, Cand, NumArgs))
9455 return;
9456 }
9457 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009458 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009459}
9460
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009461/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009462static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009463 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9464 FunctionDecl *Callee = Cand->Function;
9465
9466 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9467 CalleeTarget = S.IdentifyCUDATarget(Callee);
9468
9469 std::string FnDesc;
9470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9471
9472 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009473 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9474
9475 // This could be an implicit constructor for which we could not infer the
9476 // target due to a collsion. Diagnose that case.
9477 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9478 if (Meth != nullptr && Meth->isImplicit()) {
9479 CXXRecordDecl *ParentClass = Meth->getParent();
9480 Sema::CXXSpecialMember CSM;
9481
9482 switch (FnKind) {
9483 default:
9484 return;
9485 case oc_implicit_default_constructor:
9486 CSM = Sema::CXXDefaultConstructor;
9487 break;
9488 case oc_implicit_copy_constructor:
9489 CSM = Sema::CXXCopyConstructor;
9490 break;
9491 case oc_implicit_move_constructor:
9492 CSM = Sema::CXXMoveConstructor;
9493 break;
9494 case oc_implicit_copy_assignment:
9495 CSM = Sema::CXXCopyAssignment;
9496 break;
9497 case oc_implicit_move_assignment:
9498 CSM = Sema::CXXMoveAssignment;
9499 break;
9500 };
9501
9502 bool ConstRHS = false;
9503 if (Meth->getNumParams()) {
9504 if (const ReferenceType *RT =
9505 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9506 ConstRHS = RT->getPointeeType().isConstQualified();
9507 }
9508 }
9509
9510 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9511 /* ConstRHS */ ConstRHS,
9512 /* Diagnose */ true);
9513 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009514}
9515
Richard Smith17c00b42014-11-12 01:24:00 +00009516static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009517 FunctionDecl *Callee = Cand->Function;
9518 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9519
9520 S.Diag(Callee->getLocation(),
9521 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9522 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9523}
9524
John McCall8b9ed552010-02-01 18:53:26 +00009525/// Generates a 'note' diagnostic for an overload candidate. We've
9526/// already generated a primary error at the call site.
9527///
9528/// It really does need to be a single diagnostic with its caret
9529/// pointed at the candidate declaration. Yes, this creates some
9530/// major challenges of technical writing. Yes, this makes pointing
9531/// out problems with specific arguments quite awkward. It's still
9532/// better than generating twenty screens of text for every failed
9533/// overload.
9534///
9535/// It would be great to be able to express per-candidate problems
9536/// more richly for those diagnostic clients that cared, but we'd
9537/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009538static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009539 unsigned NumArgs,
9540 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009541 FunctionDecl *Fn = Cand->Function;
9542
John McCall12f97bc2010-01-08 04:41:39 +00009543 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009544 if (Cand->Viable && (Fn->isDeleted() ||
9545 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009546 std::string FnDesc;
9547 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009548
9549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009550 << FnKind << FnDesc
9551 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009552 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009553 return;
John McCall12f97bc2010-01-08 04:41:39 +00009554 }
9555
John McCalle1ac8d12010-01-13 00:25:19 +00009556 // We don't really have anything else to say about viable candidates.
9557 if (Cand->Viable) {
9558 S.NoteOverloadCandidate(Fn);
9559 return;
9560 }
John McCall0d1da222010-01-12 00:44:57 +00009561
John McCall6a61b522010-01-13 09:16:55 +00009562 switch (Cand->FailureKind) {
9563 case ovl_fail_too_many_arguments:
9564 case ovl_fail_too_few_arguments:
9565 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009566
John McCall6a61b522010-01-13 09:16:55 +00009567 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009568 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009569
John McCall578a1f82014-12-14 01:46:53 +00009570 case ovl_fail_illegal_constructor: {
9571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9572 << (Fn->getPrimaryTemplate() ? 1 : 0);
9573 MaybeEmitInheritedConstructorNote(S, Fn);
9574 return;
9575 }
9576
John McCallfe796dd2010-01-23 05:17:32 +00009577 case ovl_fail_trivial_conversion:
9578 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009579 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009580 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009581
John McCall65eb8792010-02-25 01:37:24 +00009582 case ovl_fail_bad_conversion: {
9583 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009584 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009585 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009586 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009587
John McCall6a61b522010-01-13 09:16:55 +00009588 // FIXME: this currently happens when we're called from SemaInit
9589 // when user-conversion overload fails. Figure out how to handle
9590 // those conditions and diagnose them well.
9591 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009592 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009593
9594 case ovl_fail_bad_target:
9595 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009596
9597 case ovl_fail_enable_if:
9598 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009599 }
John McCalld3224162010-01-08 00:58:21 +00009600}
9601
Richard Smith17c00b42014-11-12 01:24:00 +00009602static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009603 // Desugar the type of the surrogate down to a function type,
9604 // retaining as many typedefs as possible while still showing
9605 // the function type (and, therefore, its parameter types).
9606 QualType FnType = Cand->Surrogate->getConversionType();
9607 bool isLValueReference = false;
9608 bool isRValueReference = false;
9609 bool isPointer = false;
9610 if (const LValueReferenceType *FnTypeRef =
9611 FnType->getAs<LValueReferenceType>()) {
9612 FnType = FnTypeRef->getPointeeType();
9613 isLValueReference = true;
9614 } else if (const RValueReferenceType *FnTypeRef =
9615 FnType->getAs<RValueReferenceType>()) {
9616 FnType = FnTypeRef->getPointeeType();
9617 isRValueReference = true;
9618 }
9619 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9620 FnType = FnTypePtr->getPointeeType();
9621 isPointer = true;
9622 }
9623 // Desugar down to a function type.
9624 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9625 // Reconstruct the pointer/reference as appropriate.
9626 if (isPointer) FnType = S.Context.getPointerType(FnType);
9627 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9628 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9629
9630 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9631 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009632 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009633}
9634
Richard Smith17c00b42014-11-12 01:24:00 +00009635static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9636 SourceLocation OpLoc,
9637 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009638 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009639 std::string TypeStr("operator");
9640 TypeStr += Opc;
9641 TypeStr += "(";
9642 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009643 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009644 TypeStr += ")";
9645 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9646 } else {
9647 TypeStr += ", ";
9648 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9649 TypeStr += ")";
9650 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9651 }
9652}
9653
Richard Smith17c00b42014-11-12 01:24:00 +00009654static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9655 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009656 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009657 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9658 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009659 if (ICS.isBad()) break; // all meaningless after first invalid
9660 if (!ICS.isAmbiguous()) continue;
9661
John McCall5c32be02010-08-24 20:38:10 +00009662 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009663 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009664 }
9665}
9666
Larisse Voufo98b20f12013-07-19 23:00:19 +00009667static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009668 if (Cand->Function)
9669 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009670 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009671 return Cand->Surrogate->getLocation();
9672 return SourceLocation();
9673}
9674
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009676 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009677 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009678 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009679
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009680 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009681 case Sema::TDK_Incomplete:
9682 return 1;
9683
9684 case Sema::TDK_Underqualified:
9685 case Sema::TDK_Inconsistent:
9686 return 2;
9687
9688 case Sema::TDK_SubstitutionFailure:
9689 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009690 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009691 return 3;
9692
9693 case Sema::TDK_InstantiationDepth:
9694 case Sema::TDK_FailedOverloadResolution:
9695 return 4;
9696
9697 case Sema::TDK_InvalidExplicitArguments:
9698 return 5;
9699
9700 case Sema::TDK_TooManyArguments:
9701 case Sema::TDK_TooFewArguments:
9702 return 6;
9703 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009704 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009705}
9706
Richard Smith17c00b42014-11-12 01:24:00 +00009707namespace {
John McCallad2587a2010-01-12 00:48:53 +00009708struct CompareOverloadCandidatesForDisplay {
9709 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009710 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009711 size_t NumArgs;
9712
Richard Smith0f59cb32015-12-18 21:45:41 +00009713 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009714 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009715
9716 bool operator()(const OverloadCandidate *L,
9717 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009718 // Fast-path this check.
9719 if (L == R) return false;
9720
John McCall12f97bc2010-01-08 04:41:39 +00009721 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009722 if (L->Viable) {
9723 if (!R->Viable) return true;
9724
9725 // TODO: introduce a tri-valued comparison for overload
9726 // candidates. Would be more worthwhile if we had a sort
9727 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009728 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9729 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009730 } else if (R->Viable)
9731 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009732
John McCall3712d9e2010-01-15 23:32:50 +00009733 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009734
John McCall3712d9e2010-01-15 23:32:50 +00009735 // Criteria by which we can sort non-viable candidates:
9736 if (!L->Viable) {
9737 // 1. Arity mismatches come after other candidates.
9738 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009739 L->FailureKind == ovl_fail_too_few_arguments) {
9740 if (R->FailureKind == ovl_fail_too_many_arguments ||
9741 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009742 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9743 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9744 if (LDist == RDist) {
9745 if (L->FailureKind == R->FailureKind)
9746 // Sort non-surrogates before surrogates.
9747 return !L->IsSurrogate && R->IsSurrogate;
9748 // Sort candidates requiring fewer parameters than there were
9749 // arguments given after candidates requiring more parameters
9750 // than there were arguments given.
9751 return L->FailureKind == ovl_fail_too_many_arguments;
9752 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009753 return LDist < RDist;
9754 }
John McCall3712d9e2010-01-15 23:32:50 +00009755 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009756 }
John McCall3712d9e2010-01-15 23:32:50 +00009757 if (R->FailureKind == ovl_fail_too_many_arguments ||
9758 R->FailureKind == ovl_fail_too_few_arguments)
9759 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009760
John McCallfe796dd2010-01-23 05:17:32 +00009761 // 2. Bad conversions come first and are ordered by the number
9762 // of bad conversions and quality of good conversions.
9763 if (L->FailureKind == ovl_fail_bad_conversion) {
9764 if (R->FailureKind != ovl_fail_bad_conversion)
9765 return true;
9766
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009767 // The conversion that can be fixed with a smaller number of changes,
9768 // comes first.
9769 unsigned numLFixes = L->Fix.NumConversionsFixed;
9770 unsigned numRFixes = R->Fix.NumConversionsFixed;
9771 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9772 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009773 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009774 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009775 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009776
John McCallfe796dd2010-01-23 05:17:32 +00009777 // If there's any ordering between the defined conversions...
9778 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009779 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009780
9781 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009782 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009783 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009784 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009785 L->Conversions[I],
9786 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009787 case ImplicitConversionSequence::Better:
9788 leftBetter++;
9789 break;
9790
9791 case ImplicitConversionSequence::Worse:
9792 leftBetter--;
9793 break;
9794
9795 case ImplicitConversionSequence::Indistinguishable:
9796 break;
9797 }
9798 }
9799 if (leftBetter > 0) return true;
9800 if (leftBetter < 0) return false;
9801
9802 } else if (R->FailureKind == ovl_fail_bad_conversion)
9803 return false;
9804
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009805 if (L->FailureKind == ovl_fail_bad_deduction) {
9806 if (R->FailureKind != ovl_fail_bad_deduction)
9807 return true;
9808
9809 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9810 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009811 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009812 } else if (R->FailureKind == ovl_fail_bad_deduction)
9813 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009814
John McCall3712d9e2010-01-15 23:32:50 +00009815 // TODO: others?
9816 }
9817
9818 // Sort everything else by location.
9819 SourceLocation LLoc = GetLocationForCandidate(L);
9820 SourceLocation RLoc = GetLocationForCandidate(R);
9821
9822 // Put candidates without locations (e.g. builtins) at the end.
9823 if (LLoc.isInvalid()) return false;
9824 if (RLoc.isInvalid()) return true;
9825
9826 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009827 }
9828};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009829}
John McCall12f97bc2010-01-08 04:41:39 +00009830
John McCallfe796dd2010-01-23 05:17:32 +00009831/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009832/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009833static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9834 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009835 assert(!Cand->Viable);
9836
9837 // Don't do anything on failures other than bad conversion.
9838 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9839
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009840 // We only want the FixIts if all the arguments can be corrected.
9841 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009842 // Use a implicit copy initialization to check conversion fixes.
9843 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009844
John McCallfe796dd2010-01-23 05:17:32 +00009845 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009846 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009847 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009848 while (true) {
9849 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9850 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009851 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009852 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009853 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009854 }
John McCallfe796dd2010-01-23 05:17:32 +00009855 }
9856
9857 if (ConvIdx == ConvCount)
9858 return;
9859
John McCall65eb8792010-02-25 01:37:24 +00009860 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9861 "remaining conversion is initialized?");
9862
Douglas Gregoradc7a702010-04-16 17:45:54 +00009863 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009864 // operation somehow.
9865 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009866
9867 const FunctionProtoType* Proto;
9868 unsigned ArgIdx = ConvIdx;
9869
9870 if (Cand->IsSurrogate) {
9871 QualType ConvType
9872 = Cand->Surrogate->getConversionType().getNonReferenceType();
9873 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9874 ConvType = ConvPtrType->getPointeeType();
9875 Proto = ConvType->getAs<FunctionProtoType>();
9876 ArgIdx--;
9877 } else if (Cand->Function) {
9878 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9879 if (isa<CXXMethodDecl>(Cand->Function) &&
9880 !isa<CXXConstructorDecl>(Cand->Function))
9881 ArgIdx--;
9882 } else {
9883 // Builtin binary operator with a bad first conversion.
9884 assert(ConvCount <= 3);
9885 for (; ConvIdx != ConvCount; ++ConvIdx)
9886 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009887 = TryCopyInitialization(S, Args[ConvIdx],
9888 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009889 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009890 /*InOverloadResolution*/ true,
9891 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009892 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009893 return;
9894 }
9895
9896 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009897 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009898 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009899 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009900 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9901 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9902 /*InOverloadResolution=*/true,
9903 /*AllowObjCWritebackConversion=*/
9904 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009905 // Store the FixIt in the candidate if it exists.
9906 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009907 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009908 }
John McCallfe796dd2010-01-23 05:17:32 +00009909 else
9910 Cand->Conversions[ConvIdx].setEllipsis();
9911 }
9912}
9913
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009914/// PrintOverloadCandidates - When overload resolution fails, prints
9915/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009916/// set.
John McCall5c32be02010-08-24 20:38:10 +00009917void OverloadCandidateSet::NoteCandidates(Sema &S,
9918 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009919 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009920 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009921 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009922 // Sort the candidates by viability and position. Sorting directly would
9923 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009924 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009925 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9926 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009927 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009928 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009929 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009930 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009931 if (Cand->Function || Cand->IsSurrogate)
9932 Cands.push_back(Cand);
9933 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9934 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009935 }
9936 }
9937
John McCallad2587a2010-01-12 00:48:53 +00009938 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +00009939 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009940
John McCall0d1da222010-01-12 00:44:57 +00009941 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009942
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009943 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009944 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009945 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009946 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9947 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009948
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009949 // Set an arbitrary limit on the number of candidate functions we'll spam
9950 // the user with. FIXME: This limit should depend on details of the
9951 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009952 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009953 break;
9954 }
9955 ++CandsShown;
9956
John McCalld3224162010-01-08 00:58:21 +00009957 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009958 NoteFunctionCandidate(S, Cand, Args.size(),
9959 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +00009960 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009961 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009962 else {
9963 assert(Cand->Viable &&
9964 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009965 // Generally we only see ambiguities including viable builtin
9966 // operators if overload resolution got screwed up by an
9967 // ambiguous user-defined conversion.
9968 //
9969 // FIXME: It's quite possible for different conversions to see
9970 // different ambiguities, though.
9971 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009972 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009973 ReportedAmbiguousConversions = true;
9974 }
John McCalld3224162010-01-08 00:58:21 +00009975
John McCall0d1da222010-01-12 00:44:57 +00009976 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009977 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009978 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009979 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009980
9981 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009982 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009983}
9984
Larisse Voufo98b20f12013-07-19 23:00:19 +00009985static SourceLocation
9986GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9987 return Cand->Specialization ? Cand->Specialization->getLocation()
9988 : SourceLocation();
9989}
9990
Richard Smith17c00b42014-11-12 01:24:00 +00009991namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009992struct CompareTemplateSpecCandidatesForDisplay {
9993 Sema &S;
9994 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9995
9996 bool operator()(const TemplateSpecCandidate *L,
9997 const TemplateSpecCandidate *R) {
9998 // Fast-path this check.
9999 if (L == R)
10000 return false;
10001
10002 // Assuming that both candidates are not matches...
10003
10004 // Sort by the ranking of deduction failures.
10005 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10006 return RankDeductionFailure(L->DeductionFailure) <
10007 RankDeductionFailure(R->DeductionFailure);
10008
10009 // Sort everything else by location.
10010 SourceLocation LLoc = GetLocationForCandidate(L);
10011 SourceLocation RLoc = GetLocationForCandidate(R);
10012
10013 // Put candidates without locations (e.g. builtins) at the end.
10014 if (LLoc.isInvalid())
10015 return false;
10016 if (RLoc.isInvalid())
10017 return true;
10018
10019 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10020 }
10021};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010022}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010023
10024/// Diagnose a template argument deduction failure.
10025/// We are treating these failures as overload failures due to bad
10026/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010027void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10028 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010029 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010030 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010031}
10032
10033void TemplateSpecCandidateSet::destroyCandidates() {
10034 for (iterator i = begin(), e = end(); i != e; ++i) {
10035 i->DeductionFailure.Destroy();
10036 }
10037}
10038
10039void TemplateSpecCandidateSet::clear() {
10040 destroyCandidates();
10041 Candidates.clear();
10042}
10043
10044/// NoteCandidates - When no template specialization match is found, prints
10045/// diagnostic messages containing the non-matching specializations that form
10046/// the candidate set.
10047/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10048/// OCD == OCD_AllCandidates and Cand->Viable == false.
10049void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10050 // Sort the candidates by position (assuming no candidate is a match).
10051 // Sorting directly would be prohibitive, so we make a set of pointers
10052 // and sort those.
10053 SmallVector<TemplateSpecCandidate *, 32> Cands;
10054 Cands.reserve(size());
10055 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10056 if (Cand->Specialization)
10057 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010058 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010059 // in general, want to list every possible builtin candidate.
10060 }
10061
10062 std::sort(Cands.begin(), Cands.end(),
10063 CompareTemplateSpecCandidatesForDisplay(S));
10064
10065 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10066 // for generalization purposes (?).
10067 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10068
10069 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10070 unsigned CandsShown = 0;
10071 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10072 TemplateSpecCandidate *Cand = *I;
10073
10074 // Set an arbitrary limit on the number of candidates we'll spam
10075 // the user with. FIXME: This limit should depend on details of the
10076 // candidate list.
10077 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10078 break;
10079 ++CandsShown;
10080
10081 assert(Cand->Specialization &&
10082 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010083 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010084 }
10085
10086 if (I != E)
10087 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10088}
10089
Douglas Gregorb491ed32011-02-19 21:32:49 +000010090// [PossiblyAFunctionType] --> [Return]
10091// NonFunctionType --> NonFunctionType
10092// R (A) --> R(A)
10093// R (*)(A) --> R (A)
10094// R (&)(A) --> R (A)
10095// R (S::*)(A) --> R (A)
10096QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10097 QualType Ret = PossiblyAFunctionType;
10098 if (const PointerType *ToTypePtr =
10099 PossiblyAFunctionType->getAs<PointerType>())
10100 Ret = ToTypePtr->getPointeeType();
10101 else if (const ReferenceType *ToTypeRef =
10102 PossiblyAFunctionType->getAs<ReferenceType>())
10103 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010104 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010105 PossiblyAFunctionType->getAs<MemberPointerType>())
10106 Ret = MemTypePtr->getPointeeType();
10107 Ret =
10108 Context.getCanonicalType(Ret).getUnqualifiedType();
10109 return Ret;
10110}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010111
Richard Smith17c00b42014-11-12 01:24:00 +000010112namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010113// A helper class to help with address of function resolution
10114// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010115class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010116 Sema& S;
10117 Expr* SourceExpr;
10118 const QualType& TargetType;
10119 QualType TargetFunctionType; // Extracted function type from target type
10120
10121 bool Complain;
10122 //DeclAccessPair& ResultFunctionAccessPair;
10123 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010124
Douglas Gregorb491ed32011-02-19 21:32:49 +000010125 bool TargetTypeIsNonStaticMemberFunction;
10126 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010127 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010128 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010129
Douglas Gregorb491ed32011-02-19 21:32:49 +000010130 OverloadExpr::FindResult OvlExprInfo;
10131 OverloadExpr *OvlExpr;
10132 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010133 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010134 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010135
Douglas Gregorb491ed32011-02-19 21:32:49 +000010136public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010137 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10138 const QualType &TargetType, bool Complain)
10139 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10140 Complain(Complain), Context(S.getASTContext()),
10141 TargetTypeIsNonStaticMemberFunction(
10142 !!TargetType->getAs<MemberPointerType>()),
10143 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010144 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010145 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010146 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10147 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010148 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010149 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010150
David Majnemera4f7c7a2013-08-01 06:13:59 +000010151 if (TargetFunctionType->isFunctionType()) {
10152 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10153 if (!UME->isImplicitAccess() &&
10154 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10155 StaticMemberFunctionFromBoundPointer = true;
10156 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10157 DeclAccessPair dap;
10158 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10159 OvlExpr, false, &dap)) {
10160 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10161 if (!Method->isStatic()) {
10162 // If the target type is a non-function type and the function found
10163 // is a non-static member function, pretend as if that was the
10164 // target, it's the only possible type to end up with.
10165 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010166
David Majnemera4f7c7a2013-08-01 06:13:59 +000010167 // And skip adding the function if its not in the proper form.
10168 // We'll diagnose this due to an empty set of functions.
10169 if (!OvlExprInfo.HasFormOfMemberPointer)
10170 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010171 }
10172
David Majnemera4f7c7a2013-08-01 06:13:59 +000010173 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010174 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010175 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010176 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010177
10178 if (OvlExpr->hasExplicitTemplateArgs())
10179 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010180
Douglas Gregorb491ed32011-02-19 21:32:49 +000010181 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10182 // C++ [over.over]p4:
10183 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010184 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010185 if (FoundNonTemplateFunction)
10186 EliminateAllTemplateMatches();
10187 else
10188 EliminateAllExceptMostSpecializedTemplate();
10189 }
10190 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010191
10192 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10193 Matches.size() > 1)
10194 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010195 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010196
10197 bool hasComplained() const { return HasComplained; }
10198
Douglas Gregorb491ed32011-02-19 21:32:49 +000010199private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010200 // Is A considered a better overload candidate for the desired type than B?
10201 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10202 return hasBetterEnableIfAttrs(S, A, B);
10203 }
10204
10205 // Returns true if we've eliminated any (read: all but one) candidates, false
10206 // otherwise.
10207 bool eliminiateSuboptimalOverloadCandidates() {
10208 // Same algorithm as overload resolution -- one pass to pick the "best",
10209 // another pass to be sure that nothing is better than the best.
10210 auto Best = Matches.begin();
10211 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10212 if (isBetterCandidate(I->second, Best->second))
10213 Best = I;
10214
10215 const FunctionDecl *BestFn = Best->second;
10216 auto IsBestOrInferiorToBest = [this, BestFn](
10217 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10218 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10219 };
10220
10221 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10222 // option, so we can potentially give the user a better error
10223 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10224 return false;
10225 Matches[0] = *Best;
10226 Matches.resize(1);
10227 return true;
10228 }
10229
Douglas Gregorb491ed32011-02-19 21:32:49 +000010230 bool isTargetTypeAFunction() const {
10231 return TargetFunctionType->isFunctionType();
10232 }
10233
10234 // [ToType] [Return]
10235
10236 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10237 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10238 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10239 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10240 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10241 }
10242
10243 // return true if any matching specializations were found
10244 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10245 const DeclAccessPair& CurAccessFunPair) {
10246 if (CXXMethodDecl *Method
10247 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10248 // Skip non-static function templates when converting to pointer, and
10249 // static when converting to member pointer.
10250 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10251 return false;
10252 }
10253 else if (TargetTypeIsNonStaticMemberFunction)
10254 return false;
10255
10256 // C++ [over.over]p2:
10257 // If the name is a function template, template argument deduction is
10258 // done (14.8.2.2), and if the argument deduction succeeds, the
10259 // resulting template argument list is used to generate a single
10260 // function template specialization, which is added to the set of
10261 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010262 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010263 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010264 if (Sema::TemplateDeductionResult Result
10265 = S.DeduceTemplateArguments(FunctionTemplate,
10266 &OvlExplicitTemplateArgs,
10267 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010268 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010269 // Make a note of the failed deduction for diagnostics.
10270 FailedCandidates.addCandidate()
10271 .set(FunctionTemplate->getTemplatedDecl(),
10272 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010273 return false;
10274 }
10275
Douglas Gregor19a41f12013-04-17 08:45:07 +000010276 // Template argument deduction ensures that we have an exact match or
10277 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010278 // This function template specicalization works.
10279 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010280 assert(S.isSameOrCompatibleFunctionType(
10281 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010282 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010283
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010284 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010285 return false;
10286
Douglas Gregorb491ed32011-02-19 21:32:49 +000010287 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10288 return true;
10289 }
10290
10291 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10292 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010294 // Skip non-static functions when converting to pointer, and static
10295 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010296 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10297 return false;
10298 }
10299 else if (TargetTypeIsNonStaticMemberFunction)
10300 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010301
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010302 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010303 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010304 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010305 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010306 return false;
10307
Richard Smith2a7d4812013-05-04 07:00:32 +000010308 // If any candidate has a placeholder return type, trigger its deduction
10309 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010310 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010311 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010312 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10313 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010314 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010315 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010316
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010317 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010318 return false;
10319
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010320 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010321 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10322 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010323 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010324 ResultTy) ||
10325 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10326 Matches.push_back(std::make_pair(
10327 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010328 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010329 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010330 }
Mike Stump11289f42009-09-09 15:08:12 +000010331 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010332
10333 return false;
10334 }
10335
10336 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10337 bool Ret = false;
10338
10339 // If the overload expression doesn't have the form of a pointer to
10340 // member, don't try to convert it to a pointer-to-member type.
10341 if (IsInvalidFormOfPointerToMemberFunction())
10342 return false;
10343
10344 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10345 E = OvlExpr->decls_end();
10346 I != E; ++I) {
10347 // Look through any using declarations to find the underlying function.
10348 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10349
10350 // C++ [over.over]p3:
10351 // Non-member functions and static member functions match
10352 // targets of type "pointer-to-function" or "reference-to-function."
10353 // Nonstatic member functions match targets of
10354 // type "pointer-to-member-function."
10355 // Note that according to DR 247, the containing class does not matter.
10356 if (FunctionTemplateDecl *FunctionTemplate
10357 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10358 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10359 Ret = true;
10360 }
10361 // If we have explicit template arguments supplied, skip non-templates.
10362 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10363 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10364 Ret = true;
10365 }
10366 assert(Ret || Matches.empty());
10367 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010368 }
10369
Douglas Gregorb491ed32011-02-19 21:32:49 +000010370 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010371 // [...] and any given function template specialization F1 is
10372 // eliminated if the set contains a second function template
10373 // specialization whose function template is more specialized
10374 // than the function template of F1 according to the partial
10375 // ordering rules of 14.5.5.2.
10376
10377 // The algorithm specified above is quadratic. We instead use a
10378 // two-pass algorithm (similar to the one used to identify the
10379 // best viable function in an overload set) that identifies the
10380 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010381
10382 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10383 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10384 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010385
Larisse Voufo98b20f12013-07-19 23:00:19 +000010386 // TODO: It looks like FailedCandidates does not serve much purpose
10387 // here, since the no_viable diagnostic has index 0.
10388 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010389 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010390 SourceExpr->getLocStart(), S.PDiag(),
10391 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10392 .second->getDeclName(),
10393 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10394 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010395
Douglas Gregorb491ed32011-02-19 21:32:49 +000010396 if (Result != MatchesCopy.end()) {
10397 // Make it the first and only element
10398 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10399 Matches[0].second = cast<FunctionDecl>(*Result);
10400 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010401 } else
10402 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010404
Douglas Gregorb491ed32011-02-19 21:32:49 +000010405 void EliminateAllTemplateMatches() {
10406 // [...] any function template specializations in the set are
10407 // eliminated if the set also contains a non-template function, [...]
10408 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010409 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010410 ++I;
10411 else {
10412 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010413 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010414 }
10415 }
10416 }
10417
Artem Belevich94a55e82015-09-22 17:22:59 +000010418 void EliminateSuboptimalCudaMatches() {
10419 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10420 }
10421
Douglas Gregorb491ed32011-02-19 21:32:49 +000010422public:
10423 void ComplainNoMatchesFound() const {
10424 assert(Matches.empty());
10425 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10426 << OvlExpr->getName() << TargetFunctionType
10427 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010428 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010429 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10430 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010431 else {
10432 // We have some deduction failure messages. Use them to diagnose
10433 // the function templates, and diagnose the non-template candidates
10434 // normally.
10435 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10436 IEnd = OvlExpr->decls_end();
10437 I != IEnd; ++I)
10438 if (FunctionDecl *Fun =
10439 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010440 if (!functionHasPassObjectSizeParams(Fun))
10441 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10442 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010443 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10444 }
10445 }
10446
Douglas Gregorb491ed32011-02-19 21:32:49 +000010447 bool IsInvalidFormOfPointerToMemberFunction() const {
10448 return TargetTypeIsNonStaticMemberFunction &&
10449 !OvlExprInfo.HasFormOfMemberPointer;
10450 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010451
Douglas Gregorb491ed32011-02-19 21:32:49 +000010452 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10453 // TODO: Should we condition this on whether any functions might
10454 // have matched, or is it more appropriate to do that in callers?
10455 // TODO: a fixit wouldn't hurt.
10456 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10457 << TargetType << OvlExpr->getSourceRange();
10458 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010459
10460 bool IsStaticMemberFunctionFromBoundPointer() const {
10461 return StaticMemberFunctionFromBoundPointer;
10462 }
10463
10464 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10465 S.Diag(OvlExpr->getLocStart(),
10466 diag::err_invalid_form_pointer_member_function)
10467 << OvlExpr->getSourceRange();
10468 }
10469
Douglas Gregorb491ed32011-02-19 21:32:49 +000010470 void ComplainOfInvalidConversion() const {
10471 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10472 << OvlExpr->getName() << TargetType;
10473 }
10474
10475 void ComplainMultipleMatchesFound() const {
10476 assert(Matches.size() > 1);
10477 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10478 << OvlExpr->getName()
10479 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010480 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10481 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010482 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010483
10484 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10485
Douglas Gregorb491ed32011-02-19 21:32:49 +000010486 int getNumMatches() const { return Matches.size(); }
10487
10488 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010489 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010490 return Matches[0].second;
10491 }
10492
10493 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010494 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010495 return &Matches[0].first;
10496 }
10497};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010498}
Richard Smith17c00b42014-11-12 01:24:00 +000010499
Douglas Gregorb491ed32011-02-19 21:32:49 +000010500/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10501/// an overloaded function (C++ [over.over]), where @p From is an
10502/// expression with overloaded function type and @p ToType is the type
10503/// we're trying to resolve to. For example:
10504///
10505/// @code
10506/// int f(double);
10507/// int f(int);
10508///
10509/// int (*pfd)(double) = f; // selects f(double)
10510/// @endcode
10511///
10512/// This routine returns the resulting FunctionDecl if it could be
10513/// resolved, and NULL otherwise. When @p Complain is true, this
10514/// routine will emit diagnostics if there is an error.
10515FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010516Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10517 QualType TargetType,
10518 bool Complain,
10519 DeclAccessPair &FoundResult,
10520 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010521 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010522
10523 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10524 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010525 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010526 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010527 bool ShouldComplain = Complain && !Resolver.hasComplained();
10528 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010529 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10530 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10531 else
10532 Resolver.ComplainNoMatchesFound();
10533 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010534 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010535 Resolver.ComplainMultipleMatchesFound();
10536 else if (NumMatches == 1) {
10537 Fn = Resolver.getMatchingFunctionDecl();
10538 assert(Fn);
10539 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010540 if (Complain) {
10541 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10542 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10543 else
10544 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10545 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010546 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010547
10548 if (pHadMultipleCandidates)
10549 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010550 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010551}
10552
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010553/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010554/// resolve that overloaded function expression down to a single function.
10555///
10556/// This routine can only resolve template-ids that refer to a single function
10557/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010558/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010559/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010560///
10561/// If no template-ids are found, no diagnostics are emitted and NULL is
10562/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010563FunctionDecl *
10564Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10565 bool Complain,
10566 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010567 // C++ [over.over]p1:
10568 // [...] [Note: any redundant set of parentheses surrounding the
10569 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010570 // C++ [over.over]p1:
10571 // [...] The overloaded function name can be preceded by the &
10572 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010573
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010574 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010575 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010576 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010577
10578 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010579 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010580 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010581
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010582 // Look through all of the overloaded functions, searching for one
10583 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010584 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010585 for (UnresolvedSetIterator I = ovl->decls_begin(),
10586 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010587 // C++0x [temp.arg.explicit]p3:
10588 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010589 // where deduction is not done, if a template argument list is
10590 // specified and it, along with any default template arguments,
10591 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010592 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010593 FunctionTemplateDecl *FunctionTemplate
10594 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010595
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010596 // C++ [over.over]p2:
10597 // If the name is a function template, template argument deduction is
10598 // done (14.8.2.2), and if the argument deduction succeeds, the
10599 // resulting template argument list is used to generate a single
10600 // function template specialization, which is added to the set of
10601 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010602 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010603 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010604 if (TemplateDeductionResult Result
10605 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010606 Specialization, Info,
10607 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010608 // Make a note of the failed deduction for diagnostics.
10609 // TODO: Actually use the failed-deduction info?
10610 FailedCandidates.addCandidate()
10611 .set(FunctionTemplate->getTemplatedDecl(),
10612 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010613 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010614 }
10615
John McCall0009fcc2011-04-26 20:42:42 +000010616 assert(Specialization && "no specialization and no error?");
10617
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010618 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010619 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010620 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010621 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10622 << ovl->getName();
10623 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010624 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010625 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010626 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010627
John McCall0009fcc2011-04-26 20:42:42 +000010628 Matched = Specialization;
10629 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010631
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010632 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010633 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010634 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010635 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010636
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010637 return Matched;
10638}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010639
Douglas Gregor1beec452011-03-12 01:48:56 +000010640
10641
10642
John McCall50a2c2c2011-10-11 23:14:30 +000010643// Resolve and fix an overloaded expression that can be resolved
10644// because it identifies a single function template specialization.
10645//
Douglas Gregor1beec452011-03-12 01:48:56 +000010646// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010647//
10648// Return true if it was logically possible to so resolve the
10649// expression, regardless of whether or not it succeeded. Always
10650// returns true if 'complain' is set.
10651bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10652 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010653 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010654 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010655 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010656 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010657
John McCall50a2c2c2011-10-11 23:14:30 +000010658 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010659
John McCall0009fcc2011-04-26 20:42:42 +000010660 DeclAccessPair found;
10661 ExprResult SingleFunctionExpression;
10662 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10663 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010664 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010665 SrcExpr = ExprError();
10666 return true;
10667 }
John McCall0009fcc2011-04-26 20:42:42 +000010668
10669 // It is only correct to resolve to an instance method if we're
10670 // resolving a form that's permitted to be a pointer to member.
10671 // Otherwise we'll end up making a bound member expression, which
10672 // is illegal in all the contexts we resolve like this.
10673 if (!ovl.HasFormOfMemberPointer &&
10674 isa<CXXMethodDecl>(fn) &&
10675 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010676 if (!complain) return false;
10677
10678 Diag(ovl.Expression->getExprLoc(),
10679 diag::err_bound_member_function)
10680 << 0 << ovl.Expression->getSourceRange();
10681
10682 // TODO: I believe we only end up here if there's a mix of
10683 // static and non-static candidates (otherwise the expression
10684 // would have 'bound member' type, not 'overload' type).
10685 // Ideally we would note which candidate was chosen and why
10686 // the static candidates were rejected.
10687 SrcExpr = ExprError();
10688 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010689 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010690
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010691 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010692 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010693 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010694
10695 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010696 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010697 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010698 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010699 if (SingleFunctionExpression.isInvalid()) {
10700 SrcExpr = ExprError();
10701 return true;
10702 }
10703 }
John McCall0009fcc2011-04-26 20:42:42 +000010704 }
10705
10706 if (!SingleFunctionExpression.isUsable()) {
10707 if (complain) {
10708 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10709 << ovl.Expression->getName()
10710 << DestTypeForComplaining
10711 << OpRangeForComplaining
10712 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010713 NoteAllOverloadCandidates(SrcExpr.get());
10714
10715 SrcExpr = ExprError();
10716 return true;
10717 }
10718
10719 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010720 }
10721
John McCall50a2c2c2011-10-11 23:14:30 +000010722 SrcExpr = SingleFunctionExpression;
10723 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010724}
10725
Douglas Gregorcabea402009-09-22 15:41:20 +000010726/// \brief Add a single candidate to the overload set.
10727static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010728 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010729 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010730 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010731 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010732 bool PartialOverloading,
10733 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010734 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010735 if (isa<UsingShadowDecl>(Callee))
10736 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10737
Douglas Gregorcabea402009-09-22 15:41:20 +000010738 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010739 if (ExplicitTemplateArgs) {
10740 assert(!KnownValid && "Explicit template arguments?");
10741 return;
10742 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010743 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10744 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010745 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010746 return;
John McCalld14a8642009-11-21 08:51:07 +000010747 }
10748
10749 if (FunctionTemplateDecl *FuncTemplate
10750 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010751 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010752 ExplicitTemplateArgs, Args, CandidateSet,
10753 /*SuppressUsedConversions=*/false,
10754 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010755 return;
10756 }
10757
Richard Smith95ce4f62011-06-26 22:19:54 +000010758 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010759}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010760
Douglas Gregorcabea402009-09-22 15:41:20 +000010761/// \brief Add the overload candidates named by callee and/or found by argument
10762/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010763void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010764 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010765 OverloadCandidateSet &CandidateSet,
10766 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010767
10768#ifndef NDEBUG
10769 // Verify that ArgumentDependentLookup is consistent with the rules
10770 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010771 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010772 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10773 // and let Y be the lookup set produced by argument dependent
10774 // lookup (defined as follows). If X contains
10775 //
10776 // -- a declaration of a class member, or
10777 //
10778 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010779 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010780 //
10781 // -- a declaration that is neither a function or a function
10782 // template
10783 //
10784 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010785
John McCall57500772009-12-16 12:17:52 +000010786 if (ULE->requiresADL()) {
10787 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10788 E = ULE->decls_end(); I != E; ++I) {
10789 assert(!(*I)->getDeclContext()->isRecord());
10790 assert(isa<UsingShadowDecl>(*I) ||
10791 !(*I)->getDeclContext()->isFunctionOrMethod());
10792 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010793 }
10794 }
10795#endif
10796
John McCall57500772009-12-16 12:17:52 +000010797 // It would be nice to avoid this copy.
10798 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010799 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010800 if (ULE->hasExplicitTemplateArgs()) {
10801 ULE->copyTemplateArgumentsInto(TABuffer);
10802 ExplicitTemplateArgs = &TABuffer;
10803 }
10804
10805 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10806 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010807 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10808 CandidateSet, PartialOverloading,
10809 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010810
John McCall57500772009-12-16 12:17:52 +000010811 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010812 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010813 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010814 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010815}
John McCalld681c392009-12-16 08:11:27 +000010816
Richard Smith0603bbb2013-06-12 22:56:54 +000010817/// Determine whether a declaration with the specified name could be moved into
10818/// a different namespace.
10819static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10820 switch (Name.getCXXOverloadedOperator()) {
10821 case OO_New: case OO_Array_New:
10822 case OO_Delete: case OO_Array_Delete:
10823 return false;
10824
10825 default:
10826 return true;
10827 }
10828}
10829
Richard Smith998a5912011-06-05 22:42:48 +000010830/// Attempt to recover from an ill-formed use of a non-dependent name in a
10831/// template, where the non-dependent name was declared after the template
10832/// was defined. This is common in code written for a compilers which do not
10833/// correctly implement two-stage name lookup.
10834///
10835/// Returns true if a viable candidate was found and a diagnostic was issued.
10836static bool
10837DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10838 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010839 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010840 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010841 ArrayRef<Expr *> Args,
10842 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010843 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10844 return false;
10845
10846 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010847 if (DC->isTransparentContext())
10848 continue;
10849
Richard Smith998a5912011-06-05 22:42:48 +000010850 SemaRef.LookupQualifiedName(R, DC);
10851
10852 if (!R.empty()) {
10853 R.suppressDiagnostics();
10854
10855 if (isa<CXXRecordDecl>(DC)) {
10856 // Don't diagnose names we find in classes; we get much better
10857 // diagnostics for these from DiagnoseEmptyLookup.
10858 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010859 if (DoDiagnoseEmptyLookup)
10860 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010861 return false;
10862 }
10863
Richard Smith100b24a2014-04-17 01:52:14 +000010864 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10866 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010867 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010868 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010869
10870 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010871 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010872 // No viable functions. Don't bother the user with notes for functions
10873 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010874 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010875 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010876 }
Richard Smith998a5912011-06-05 22:42:48 +000010877
10878 // Find the namespaces where ADL would have looked, and suggest
10879 // declaring the function there instead.
10880 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10881 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010882 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010883 AssociatedNamespaces,
10884 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010885 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010886 if (canBeDeclaredInNamespace(R.getLookupName())) {
10887 DeclContext *Std = SemaRef.getStdNamespace();
10888 for (Sema::AssociatedNamespaceSet::iterator
10889 it = AssociatedNamespaces.begin(),
10890 end = AssociatedNamespaces.end(); it != end; ++it) {
10891 // Never suggest declaring a function within namespace 'std'.
10892 if (Std && Std->Encloses(*it))
10893 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010894
Richard Smith0603bbb2013-06-12 22:56:54 +000010895 // Never suggest declaring a function within a namespace with a
10896 // reserved name, like __gnu_cxx.
10897 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10898 if (NS &&
10899 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10900 continue;
10901
10902 SuggestedNamespaces.insert(*it);
10903 }
Richard Smith998a5912011-06-05 22:42:48 +000010904 }
10905
10906 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10907 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010908 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010909 SemaRef.Diag(Best->Function->getLocation(),
10910 diag::note_not_found_by_two_phase_lookup)
10911 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010912 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010913 SemaRef.Diag(Best->Function->getLocation(),
10914 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010915 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010916 } else {
10917 // FIXME: It would be useful to list the associated namespaces here,
10918 // but the diagnostics infrastructure doesn't provide a way to produce
10919 // a localized representation of a list of items.
10920 SemaRef.Diag(Best->Function->getLocation(),
10921 diag::note_not_found_by_two_phase_lookup)
10922 << R.getLookupName() << 2;
10923 }
10924
10925 // Try to recover by calling this function.
10926 return true;
10927 }
10928
10929 R.clear();
10930 }
10931
10932 return false;
10933}
10934
10935/// Attempt to recover from ill-formed use of a non-dependent operator in a
10936/// template, where the non-dependent operator was declared after the template
10937/// was defined.
10938///
10939/// Returns true if a viable candidate was found and a diagnostic was issued.
10940static bool
10941DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10942 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010943 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010944 DeclarationName OpName =
10945 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10946 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10947 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010948 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010949 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010950}
10951
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010952namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010953class BuildRecoveryCallExprRAII {
10954 Sema &SemaRef;
10955public:
10956 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10957 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10958 SemaRef.IsBuildingRecoveryCallExpr = true;
10959 }
10960
10961 ~BuildRecoveryCallExprRAII() {
10962 SemaRef.IsBuildingRecoveryCallExpr = false;
10963 }
10964};
10965
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010966}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010967
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010968static std::unique_ptr<CorrectionCandidateCallback>
10969MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10970 bool HasTemplateArgs, bool AllowTypoCorrection) {
10971 if (!AllowTypoCorrection)
10972 return llvm::make_unique<NoTypoCorrectionCCC>();
10973 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10974 HasTemplateArgs, ME);
10975}
10976
John McCalld681c392009-12-16 08:11:27 +000010977/// Attempts to recover from a call where no functions were found.
10978///
10979/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010980static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010981BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010982 UnresolvedLookupExpr *ULE,
10983 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010984 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010985 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010986 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010987 // Do not try to recover if it is already building a recovery call.
10988 // This stops infinite loops for template instantiations like
10989 //
10990 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10991 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10992 //
10993 if (SemaRef.IsBuildingRecoveryCallExpr)
10994 return ExprError();
10995 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010996
10997 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010998 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010999 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011000
John McCall57500772009-12-16 12:17:52 +000011001 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011002 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011003 if (ULE->hasExplicitTemplateArgs()) {
11004 ULE->copyTemplateArgumentsInto(TABuffer);
11005 ExplicitTemplateArgs = &TABuffer;
11006 }
11007
John McCalld681c392009-12-16 08:11:27 +000011008 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11009 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011010 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011011 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011012 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011013 ExplicitTemplateArgs, Args,
11014 &DoDiagnoseEmptyLookup) &&
11015 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11016 S, SS, R,
11017 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11018 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11019 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011020 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011021
John McCall57500772009-12-16 12:17:52 +000011022 assert(!R.empty() && "lookup results empty despite recovery");
11023
11024 // Build an implicit member call if appropriate. Just drop the
11025 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011026 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011027 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011028 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11029 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011030 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011031 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011032 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011033 else
11034 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11035
11036 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011037 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011038
11039 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011040 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011041 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011042 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011043 MultiExprArg(Args.data(), Args.size()),
11044 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011045}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011046
Sam Panzer0f384432012-08-21 00:52:01 +000011047/// \brief Constructs and populates an OverloadedCandidateSet from
11048/// the given function.
11049/// \returns true when an the ExprResult output parameter has been set.
11050bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11051 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011052 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011053 SourceLocation RParenLoc,
11054 OverloadCandidateSet *CandidateSet,
11055 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011056#ifndef NDEBUG
11057 if (ULE->requiresADL()) {
11058 // To do ADL, we must have found an unqualified name.
11059 assert(!ULE->getQualifier() && "qualified name with ADL");
11060
11061 // We don't perform ADL for implicit declarations of builtins.
11062 // Verify that this was correctly set up.
11063 FunctionDecl *F;
11064 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11065 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11066 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011067 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011068
John McCall57500772009-12-16 12:17:52 +000011069 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011070 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011071 }
John McCall57500772009-12-16 12:17:52 +000011072#endif
11073
John McCall4124c492011-10-17 18:40:02 +000011074 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011075 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011076 *Result = ExprError();
11077 return true;
11078 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011079
John McCall57500772009-12-16 12:17:52 +000011080 // Add the functions denoted by the callee to the set of candidate
11081 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011082 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011083
Hans Wennborgb2747382015-06-12 21:23:23 +000011084 if (getLangOpts().MSVCCompat &&
11085 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011086 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11087
11088 OverloadCandidateSet::iterator Best;
11089 if (CandidateSet->empty() ||
11090 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11091 OR_No_Viable_Function) {
11092 // In Microsoft mode, if we are inside a template class member function then
11093 // create a type dependent CallExpr. The goal is to postpone name lookup
11094 // to instantiation time to be able to search into type dependent base
11095 // classes.
11096 CallExpr *CE = new (Context) CallExpr(
11097 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011098 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011099 CE->setValueDependent(true);
11100 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011101 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011102 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011103 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011104 }
John McCalld681c392009-12-16 08:11:27 +000011105
Hans Wennborg64937c62015-06-11 21:21:57 +000011106 if (CandidateSet->empty())
11107 return false;
11108
John McCall4124c492011-10-17 18:40:02 +000011109 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011110 return false;
11111}
John McCall4124c492011-10-17 18:40:02 +000011112
Sam Panzer0f384432012-08-21 00:52:01 +000011113/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11114/// the completed call expression. If overload resolution fails, emits
11115/// diagnostics and returns ExprError()
11116static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11117 UnresolvedLookupExpr *ULE,
11118 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011119 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011120 SourceLocation RParenLoc,
11121 Expr *ExecConfig,
11122 OverloadCandidateSet *CandidateSet,
11123 OverloadCandidateSet::iterator *Best,
11124 OverloadingResult OverloadResult,
11125 bool AllowTypoCorrection) {
11126 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011127 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011128 RParenLoc, /*EmptyLookup=*/true,
11129 AllowTypoCorrection);
11130
11131 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011132 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011133 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011134 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011135 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11136 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011137 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011138 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11139 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011140 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011141
Richard Smith998a5912011-06-05 22:42:48 +000011142 case OR_No_Viable_Function: {
11143 // Try to recover by looking for viable functions which the user might
11144 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011145 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011146 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011147 /*EmptyLookup=*/false,
11148 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011149 if (!Recovery.isInvalid())
11150 return Recovery;
11151
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011152 // If the user passes in a function that we can't take the address of, we
11153 // generally end up emitting really bad error messages. Here, we attempt to
11154 // emit better ones.
11155 for (const Expr *Arg : Args) {
11156 if (!Arg->getType()->isFunctionType())
11157 continue;
11158 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11159 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11160 if (FD &&
11161 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11162 Arg->getExprLoc()))
11163 return ExprError();
11164 }
11165 }
11166
11167 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11168 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011169 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011170 break;
Richard Smith998a5912011-06-05 22:42:48 +000011171 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011172
11173 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011174 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011175 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011176 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011177 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011178
Sam Panzer0f384432012-08-21 00:52:01 +000011179 case OR_Deleted: {
11180 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11181 << (*Best)->Function->isDeleted()
11182 << ULE->getName()
11183 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11184 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011185 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011186
Sam Panzer0f384432012-08-21 00:52:01 +000011187 // We emitted an error for the unvailable/deleted function call but keep
11188 // the call in the AST.
11189 FunctionDecl *FDecl = (*Best)->Function;
11190 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011191 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11192 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011193 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011194 }
11195
Douglas Gregorb412e172010-07-25 18:17:45 +000011196 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011197 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011198}
11199
Sam Panzer0f384432012-08-21 00:52:01 +000011200/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11201/// (which eventually refers to the declaration Func) and the call
11202/// arguments Args/NumArgs, attempt to resolve the function call down
11203/// to a specific function. If overload resolution succeeds, returns
11204/// the call expression produced by overload resolution.
11205/// Otherwise, emits diagnostics and returns ExprError.
11206ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11207 UnresolvedLookupExpr *ULE,
11208 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011209 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011210 SourceLocation RParenLoc,
11211 Expr *ExecConfig,
11212 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000011213 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11214 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011215 ExprResult result;
11216
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011217 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11218 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011219 return result;
11220
11221 OverloadCandidateSet::iterator Best;
11222 OverloadingResult OverloadResult =
11223 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11224
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011225 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011226 RParenLoc, ExecConfig, &CandidateSet,
11227 &Best, OverloadResult,
11228 AllowTypoCorrection);
11229}
11230
John McCall4c4c1df2010-01-26 03:27:55 +000011231static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011232 return Functions.size() > 1 ||
11233 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11234}
11235
Douglas Gregor084d8552009-03-13 23:49:33 +000011236/// \brief Create a unary operation that may resolve to an overloaded
11237/// operator.
11238///
11239/// \param OpLoc The location of the operator itself (e.g., '*').
11240///
Craig Toppera92ffb02015-12-10 08:51:49 +000011241/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011242///
James Dennett18348b62012-06-22 08:52:37 +000011243/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011244/// considered by overload resolution. The caller needs to build this
11245/// set based on the context using, e.g.,
11246/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11247/// set should not contain any member functions; those will be added
11248/// by CreateOverloadedUnaryOp().
11249///
James Dennett91738ff2012-06-22 10:32:46 +000011250/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011251ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011252Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011253 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011254 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011255 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11256 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11257 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011258 // TODO: provide better source location info.
11259 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011260
John McCall4124c492011-10-17 18:40:02 +000011261 if (checkPlaceholderForOverload(*this, Input))
11262 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011263
Craig Topperc3ec1492014-05-26 06:22:03 +000011264 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011265 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011266
Douglas Gregor084d8552009-03-13 23:49:33 +000011267 // For post-increment and post-decrement, add the implicit '0' as
11268 // the second argument, so that we know this is a post-increment or
11269 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011270 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011271 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011272 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11273 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011274 NumArgs = 2;
11275 }
11276
Richard Smithe54c3072013-05-05 15:51:06 +000011277 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11278
Douglas Gregor084d8552009-03-13 23:49:33 +000011279 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011280 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011281 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11282 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011283
Craig Topperc3ec1492014-05-26 06:22:03 +000011284 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011285 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011286 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011287 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011288 /*ADL*/ true, IsOverloaded(Fns),
11289 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011290 return new (Context)
11291 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11292 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011293 }
11294
11295 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011296 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011297
11298 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011299 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011300
11301 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011302 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011303
John McCall4c4c1df2010-01-26 03:27:55 +000011304 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011305 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011306 /*ExplicitTemplateArgs*/nullptr,
11307 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011308
Douglas Gregor084d8552009-03-13 23:49:33 +000011309 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011310 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011311
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011312 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11313
Douglas Gregor084d8552009-03-13 23:49:33 +000011314 // Perform overload resolution.
11315 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011316 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011317 case OR_Success: {
11318 // We found a built-in operator or an overloaded operator.
11319 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011320
Douglas Gregor084d8552009-03-13 23:49:33 +000011321 if (FnDecl) {
11322 // We matched an overloaded operator. Build a call to that
11323 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011324
Douglas Gregor084d8552009-03-13 23:49:33 +000011325 // Convert the arguments.
11326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011327 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011328
John Wiegley01296292011-04-08 18:41:53 +000011329 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011330 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011331 Best->FoundDecl, Method);
11332 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011333 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011334 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011335 } else {
11336 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011337 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011338 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011339 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011340 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011341 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011342 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011343 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011344 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011345 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011346 }
11347
Douglas Gregor084d8552009-03-13 23:49:33 +000011348 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011349 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011350 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011351 if (FnExpr.isInvalid())
11352 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011353
Richard Smithc1564702013-11-15 02:58:23 +000011354 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011355 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011356 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11357 ResultTy = ResultTy.getNonLValueExprType(Context);
11358
Eli Friedman030eee42009-11-18 03:58:17 +000011359 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011360 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011361 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011362 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011363
Alp Toker314cc812014-01-25 16:55:45 +000011364 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011365 return ExprError();
11366
John McCallb268a282010-08-23 23:25:46 +000011367 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011368 } else {
11369 // We matched a built-in operator. Convert the arguments, then
11370 // break out so that we will build the appropriate built-in
11371 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011372 ExprResult InputRes =
11373 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11374 Best->Conversions[0], AA_Passing);
11375 if (InputRes.isInvalid())
11376 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011377 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011378 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011379 }
John Wiegley01296292011-04-08 18:41:53 +000011380 }
11381
11382 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011383 // This is an erroneous use of an operator which can be overloaded by
11384 // a non-member function. Check for non-member operators which were
11385 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011386 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011387 // FIXME: Recover by calling the found function.
11388 return ExprError();
11389
John Wiegley01296292011-04-08 18:41:53 +000011390 // No viable function; fall through to handling this as a
11391 // built-in operator, which will produce an error message for us.
11392 break;
11393
11394 case OR_Ambiguous:
11395 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11396 << UnaryOperator::getOpcodeStr(Opc)
11397 << Input->getType()
11398 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011399 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011400 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11401 return ExprError();
11402
11403 case OR_Deleted:
11404 Diag(OpLoc, diag::err_ovl_deleted_oper)
11405 << Best->Function->isDeleted()
11406 << UnaryOperator::getOpcodeStr(Opc)
11407 << getDeletedOrUnavailableSuffix(Best->Function)
11408 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011410 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011411 return ExprError();
11412 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011413
11414 // Either we found no viable overloaded operator or we matched a
11415 // built-in operator. In either case, fall through to trying to
11416 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011417 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011418}
11419
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011420/// \brief Create a binary operation that may resolve to an overloaded
11421/// operator.
11422///
11423/// \param OpLoc The location of the operator itself (e.g., '+').
11424///
Craig Toppera92ffb02015-12-10 08:51:49 +000011425/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011426///
James Dennett18348b62012-06-22 08:52:37 +000011427/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011428/// considered by overload resolution. The caller needs to build this
11429/// set based on the context using, e.g.,
11430/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11431/// set should not contain any member functions; those will be added
11432/// by CreateOverloadedBinOp().
11433///
11434/// \param LHS Left-hand argument.
11435/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011436ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011437Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011438 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011439 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011440 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011441 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011442 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011443
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011444 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11445 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11446
11447 // If either side is type-dependent, create an appropriate dependent
11448 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011449 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011450 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011451 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011452 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011453 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011454 return new (Context) BinaryOperator(
11455 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11456 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011457
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011458 return new (Context) CompoundAssignOperator(
11459 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11460 Context.DependentTy, Context.DependentTy, OpLoc,
11461 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011462 }
John McCall4c4c1df2010-01-26 03:27:55 +000011463
11464 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011465 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011466 // TODO: provide better source location info in DNLoc component.
11467 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011468 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011469 = UnresolvedLookupExpr::Create(Context, NamingClass,
11470 NestedNameSpecifierLoc(), OpNameInfo,
11471 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011472 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011473 return new (Context)
11474 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11475 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011476 }
11477
John McCall4124c492011-10-17 18:40:02 +000011478 // Always do placeholder-like conversions on the RHS.
11479 if (checkPlaceholderForOverload(*this, Args[1]))
11480 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011481
John McCall526ab472011-10-25 17:37:35 +000011482 // Do placeholder-like conversion on the LHS; note that we should
11483 // not get here with a PseudoObject LHS.
11484 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011485 if (checkPlaceholderForOverload(*this, Args[0]))
11486 return ExprError();
11487
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011488 // If this is the assignment operator, we only perform overload resolution
11489 // if the left-hand side is a class or enumeration type. This is actually
11490 // a hack. The standard requires that we do overload resolution between the
11491 // various built-in candidates, but as DR507 points out, this can lead to
11492 // problems. So we do it this way, which pretty much follows what GCC does.
11493 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011494 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011495 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011496
John McCalle26a8722010-12-04 08:14:53 +000011497 // If this is the .* operator, which is not overloadable, just
11498 // create a built-in binary operator.
11499 if (Opc == BO_PtrMemD)
11500 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11501
Douglas Gregor084d8552009-03-13 23:49:33 +000011502 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011503 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011504
11505 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011506 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011507
11508 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011509 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011510
Richard Smith0daabd72014-09-23 20:31:39 +000011511 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11512 // performed for an assignment operator (nor for operator[] nor operator->,
11513 // which don't get here).
11514 if (Opc != BO_Assign)
11515 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11516 /*ExplicitTemplateArgs*/ nullptr,
11517 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011518
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011519 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011520 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011521
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011522 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11523
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011524 // Perform overload resolution.
11525 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011526 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011527 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011528 // We found a built-in operator or an overloaded operator.
11529 FunctionDecl *FnDecl = Best->Function;
11530
11531 if (FnDecl) {
11532 // We matched an overloaded operator. Build a call to that
11533 // operator.
11534
11535 // Convert the arguments.
11536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011537 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011538 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011539
Chandler Carruth8e543b32010-12-12 08:17:55 +000011540 ExprResult Arg1 =
11541 PerformCopyInitialization(
11542 InitializedEntity::InitializeParameter(Context,
11543 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011544 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011545 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011546 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011547
John Wiegley01296292011-04-08 18:41:53 +000011548 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011549 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011550 Best->FoundDecl, Method);
11551 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011552 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011553 Args[0] = Arg0.getAs<Expr>();
11554 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011555 } else {
11556 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011557 ExprResult Arg0 = PerformCopyInitialization(
11558 InitializedEntity::InitializeParameter(Context,
11559 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011560 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011561 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011562 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011563
Chandler Carruth8e543b32010-12-12 08:17:55 +000011564 ExprResult Arg1 =
11565 PerformCopyInitialization(
11566 InitializedEntity::InitializeParameter(Context,
11567 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011568 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011569 if (Arg1.isInvalid())
11570 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011571 Args[0] = LHS = Arg0.getAs<Expr>();
11572 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011573 }
11574
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011575 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011576 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011577 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011578 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011579 if (FnExpr.isInvalid())
11580 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011581
Richard Smithc1564702013-11-15 02:58:23 +000011582 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011583 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011584 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11585 ResultTy = ResultTy.getNonLValueExprType(Context);
11586
John McCallb268a282010-08-23 23:25:46 +000011587 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011588 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011589 Args, ResultTy, VK, OpLoc,
11590 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011591
Alp Toker314cc812014-01-25 16:55:45 +000011592 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011593 FnDecl))
11594 return ExprError();
11595
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011596 ArrayRef<const Expr *> ArgsArray(Args, 2);
11597 // Cut off the implicit 'this'.
11598 if (isa<CXXMethodDecl>(FnDecl))
11599 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011600
11601 // Check for a self move.
11602 if (Op == OO_Equal)
11603 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11604
Douglas Gregorb4866e82015-06-19 18:13:19 +000011605 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011606 TheCall->getSourceRange(), VariadicDoesNotApply);
11607
John McCallb268a282010-08-23 23:25:46 +000011608 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011609 } else {
11610 // We matched a built-in operator. Convert the arguments, then
11611 // break out so that we will build the appropriate built-in
11612 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011613 ExprResult ArgsRes0 =
11614 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11615 Best->Conversions[0], AA_Passing);
11616 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011617 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011618 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011619
John Wiegley01296292011-04-08 18:41:53 +000011620 ExprResult ArgsRes1 =
11621 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11622 Best->Conversions[1], AA_Passing);
11623 if (ArgsRes1.isInvalid())
11624 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011625 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011626 break;
11627 }
11628 }
11629
Douglas Gregor66950a32009-09-30 21:46:01 +000011630 case OR_No_Viable_Function: {
11631 // C++ [over.match.oper]p9:
11632 // If the operator is the operator , [...] and there are no
11633 // viable functions, then the operator is assumed to be the
11634 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011635 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011636 break;
11637
Chandler Carruth8e543b32010-12-12 08:17:55 +000011638 // For class as left operand for assignment or compound assigment
11639 // operator do not fall through to handling in built-in, but report that
11640 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011641 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011642 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011643 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011644 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11645 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011646 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011647 if (Args[0]->getType()->isIncompleteType()) {
11648 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11649 << Args[0]->getType()
11650 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11651 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011652 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011653 // This is an erroneous use of an operator which can be overloaded by
11654 // a non-member function. Check for non-member operators which were
11655 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011656 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011657 // FIXME: Recover by calling the found function.
11658 return ExprError();
11659
Douglas Gregor66950a32009-09-30 21:46:01 +000011660 // No viable function; try to create a built-in operation, which will
11661 // produce an error. Then, show the non-viable candidates.
11662 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011664 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011665 "C++ binary operator overloading is missing candidates!");
11666 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011667 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011668 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011669 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011670 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011671
11672 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011673 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011674 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011675 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011676 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011677 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011678 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011679 return ExprError();
11680
11681 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011682 if (isImplicitlyDeleted(Best->Function)) {
11683 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11684 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011685 << Context.getRecordType(Method->getParent())
11686 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011687
Richard Smithde1a4872012-12-28 12:23:24 +000011688 // The user probably meant to call this special member. Just
11689 // explain why it's deleted.
11690 NoteDeletedFunction(Method);
11691 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011692 } else {
11693 Diag(OpLoc, diag::err_ovl_deleted_oper)
11694 << Best->Function->isDeleted()
11695 << BinaryOperator::getOpcodeStr(Opc)
11696 << getDeletedOrUnavailableSuffix(Best->Function)
11697 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11698 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011699 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011700 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011701 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011702 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011703
Douglas Gregor66950a32009-09-30 21:46:01 +000011704 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011705 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011706}
11707
John McCalldadc5752010-08-24 06:29:42 +000011708ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011709Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11710 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011711 Expr *Base, Expr *Idx) {
11712 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011713 DeclarationName OpName =
11714 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11715
11716 // If either side is type-dependent, create an appropriate dependent
11717 // expression.
11718 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11719
Craig Topperc3ec1492014-05-26 06:22:03 +000011720 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011721 // CHECKME: no 'operator' keyword?
11722 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11723 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011724 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011725 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011726 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011727 /*ADL*/ true, /*Overloaded*/ false,
11728 UnresolvedSetIterator(),
11729 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011730 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011731
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011732 return new (Context)
11733 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11734 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011735 }
11736
John McCall4124c492011-10-17 18:40:02 +000011737 // Handle placeholders on both operands.
11738 if (checkPlaceholderForOverload(*this, Args[0]))
11739 return ExprError();
11740 if (checkPlaceholderForOverload(*this, Args[1]))
11741 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011742
Sebastian Redladba46e2009-10-29 20:17:01 +000011743 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011744 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011745
11746 // Subscript can only be overloaded as a member function.
11747
11748 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011749 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011750
11751 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011752 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011753
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011754 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11755
Sebastian Redladba46e2009-10-29 20:17:01 +000011756 // Perform overload resolution.
11757 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011758 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011759 case OR_Success: {
11760 // We found a built-in operator or an overloaded operator.
11761 FunctionDecl *FnDecl = Best->Function;
11762
11763 if (FnDecl) {
11764 // We matched an overloaded operator. Build a call to that
11765 // operator.
11766
John McCalla0296f72010-03-19 07:35:19 +000011767 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011768
Sebastian Redladba46e2009-10-29 20:17:01 +000011769 // Convert the arguments.
11770 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011771 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011772 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011773 Best->FoundDecl, Method);
11774 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011775 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011776 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011777
Anders Carlssona68e51e2010-01-29 18:37:50 +000011778 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011779 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011780 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011781 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011782 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011783 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011784 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011785 if (InputInit.isInvalid())
11786 return ExprError();
11787
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011788 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011789
Sebastian Redladba46e2009-10-29 20:17:01 +000011790 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011791 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11792 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011793 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011794 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011795 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011796 OpLocInfo.getLoc(),
11797 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011798 if (FnExpr.isInvalid())
11799 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011800
Richard Smithc1564702013-11-15 02:58:23 +000011801 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011802 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011803 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11804 ResultTy = ResultTy.getNonLValueExprType(Context);
11805
John McCallb268a282010-08-23 23:25:46 +000011806 CXXOperatorCallExpr *TheCall =
11807 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011808 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011809 ResultTy, VK, RLoc,
11810 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011811
Alp Toker314cc812014-01-25 16:55:45 +000011812 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011813 return ExprError();
11814
John McCallb268a282010-08-23 23:25:46 +000011815 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011816 } else {
11817 // We matched a built-in operator. Convert the arguments, then
11818 // break out so that we will build the appropriate built-in
11819 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011820 ExprResult ArgsRes0 =
11821 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11822 Best->Conversions[0], AA_Passing);
11823 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011824 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011825 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011826
11827 ExprResult ArgsRes1 =
11828 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11829 Best->Conversions[1], AA_Passing);
11830 if (ArgsRes1.isInvalid())
11831 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011832 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011833
11834 break;
11835 }
11836 }
11837
11838 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011839 if (CandidateSet.empty())
11840 Diag(LLoc, diag::err_ovl_no_oper)
11841 << Args[0]->getType() << /*subscript*/ 0
11842 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11843 else
11844 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11845 << Args[0]->getType()
11846 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011847 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011848 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011849 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011850 }
11851
11852 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011853 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011854 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011855 << Args[0]->getType() << Args[1]->getType()
11856 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011857 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011858 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011859 return ExprError();
11860
11861 case OR_Deleted:
11862 Diag(LLoc, diag::err_ovl_deleted_oper)
11863 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011864 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011865 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011866 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011867 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011868 return ExprError();
11869 }
11870
11871 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011872 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011873}
11874
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011875/// BuildCallToMemberFunction - Build a call to a member
11876/// function. MemExpr is the expression that refers to the member
11877/// function (and includes the object parameter), Args/NumArgs are the
11878/// arguments to the function call (not including the object
11879/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011880/// expression refers to a non-static member function or an overloaded
11881/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011882ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011883Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011884 SourceLocation LParenLoc,
11885 MultiExprArg Args,
11886 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011887 assert(MemExprE->getType() == Context.BoundMemberTy ||
11888 MemExprE->getType() == Context.OverloadTy);
11889
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011890 // Dig out the member expression. This holds both the object
11891 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011892 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011893
John McCall0009fcc2011-04-26 20:42:42 +000011894 // Determine whether this is a call to a pointer-to-member function.
11895 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11896 assert(op->getType() == Context.BoundMemberTy);
11897 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11898
11899 QualType fnType =
11900 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11901
11902 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11903 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011904 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011905
11906 // Check that the object type isn't more qualified than the
11907 // member function we're calling.
11908 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11909
11910 QualType objectType = op->getLHS()->getType();
11911 if (op->getOpcode() == BO_PtrMemI)
11912 objectType = objectType->castAs<PointerType>()->getPointeeType();
11913 Qualifiers objectQuals = objectType.getQualifiers();
11914
11915 Qualifiers difference = objectQuals - funcQuals;
11916 difference.removeObjCGCAttr();
11917 difference.removeAddressSpace();
11918 if (difference) {
11919 std::string qualsString = difference.getAsString();
11920 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11921 << fnType.getUnqualifiedType()
11922 << qualsString
11923 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11924 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011925
John McCall0009fcc2011-04-26 20:42:42 +000011926 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011927 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011928 resultType, valueKind, RParenLoc);
11929
Alp Toker314cc812014-01-25 16:55:45 +000011930 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011931 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011932 return ExprError();
11933
Craig Topperc3ec1492014-05-26 06:22:03 +000011934 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011935 return ExprError();
11936
Richard Trieu9be9c682013-06-22 02:30:38 +000011937 if (CheckOtherCall(call, proto))
11938 return ExprError();
11939
John McCall0009fcc2011-04-26 20:42:42 +000011940 return MaybeBindToTemporary(call);
11941 }
11942
David Majnemerced8bdf2015-02-25 17:36:15 +000011943 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11944 return new (Context)
11945 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11946
John McCall4124c492011-10-17 18:40:02 +000011947 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011948 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011949 return ExprError();
11950
John McCall10eae182009-11-30 22:42:35 +000011951 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011952 CXXMethodDecl *Method = nullptr;
11953 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11954 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011955 if (isa<MemberExpr>(NakedMemExpr)) {
11956 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011957 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011958 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011959 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011960 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011961 } else {
11962 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011963 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011964
John McCall6e9f8f62009-12-03 04:06:58 +000011965 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011966 Expr::Classification ObjectClassification
11967 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11968 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011969
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011970 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011971 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11972 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011973
John McCall2d74de92009-12-01 22:10:20 +000011974 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011975 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011976 if (UnresExpr->hasExplicitTemplateArgs()) {
11977 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11978 TemplateArgs = &TemplateArgsBuffer;
11979 }
11980
John McCall10eae182009-11-30 22:42:35 +000011981 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11982 E = UnresExpr->decls_end(); I != E; ++I) {
11983
John McCall6e9f8f62009-12-03 04:06:58 +000011984 NamedDecl *Func = *I;
11985 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11986 if (isa<UsingShadowDecl>(Func))
11987 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11988
Douglas Gregor02824322011-01-26 19:30:28 +000011989
Francois Pichet64225792011-01-18 05:04:39 +000011990 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011991 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011992 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011993 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011994 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011995 // If explicit template arguments were provided, we can't call a
11996 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011997 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011998 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011999
John McCalla0296f72010-03-19 07:35:19 +000012000 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012001 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012002 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012003 } else {
John McCall10eae182009-11-30 22:42:35 +000012004 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012005 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012006 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012007 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012008 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012009 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012010 }
Mike Stump11289f42009-09-09 15:08:12 +000012011
John McCall10eae182009-11-30 22:42:35 +000012012 DeclarationName DeclName = UnresExpr->getMemberName();
12013
John McCall4124c492011-10-17 18:40:02 +000012014 UnbridgedCasts.restore();
12015
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012016 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012017 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012018 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012019 case OR_Success:
12020 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012021 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012022 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012023 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12024 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012025 // If FoundDecl is different from Method (such as if one is a template
12026 // and the other a specialization), make sure DiagnoseUseOfDecl is
12027 // called on both.
12028 // FIXME: This would be more comprehensively addressed by modifying
12029 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12030 // being used.
12031 if (Method != FoundDecl.getDecl() &&
12032 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12033 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012034 break;
12035
12036 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012037 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012038 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012039 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012041 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012042 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012043
12044 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012045 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012046 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012047 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012048 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012049 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012050
12051 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012052 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012053 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012054 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012055 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012056 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012057 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012058 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012059 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012060 }
12061
John McCall16df1e52010-03-30 21:47:33 +000012062 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012063
John McCall2d74de92009-12-01 22:10:20 +000012064 // If overload resolution picked a static member, build a
12065 // non-member call based on that function.
12066 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012067 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12068 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012069 }
12070
John McCall10eae182009-11-30 22:42:35 +000012071 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012072 }
12073
Alp Toker314cc812014-01-25 16:55:45 +000012074 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012075 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12076 ResultType = ResultType.getNonLValueExprType(Context);
12077
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012078 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012079 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012080 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012081 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012082
Eli Bendersky291a57e2014-09-25 23:59:08 +000012083 // (CUDA B.1): Check for invalid calls between targets.
12084 if (getLangOpts().CUDA) {
12085 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12086 if (CheckCUDATarget(Caller, Method)) {
12087 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12088 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12089 << IdentifyCUDATarget(Caller);
12090 return ExprError();
12091 }
12092 }
12093 }
12094
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012095 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012096 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012097 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012098 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012099
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012100 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012101 // We only need to do this if there was actually an overload; otherwise
12102 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012103 if (!Method->isStatic()) {
12104 ExprResult ObjectArg =
12105 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12106 FoundDecl, Method);
12107 if (ObjectArg.isInvalid())
12108 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012109 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012110 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012111
12112 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012113 const FunctionProtoType *Proto =
12114 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012115 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012116 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012117 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012118
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012119 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012120
Richard Smith55ce3522012-06-25 20:30:08 +000012121 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012122 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012123
George Burgess IVaea6ade2015-09-25 17:53:16 +000012124 // In the case the method to call was not selected by the overloading
12125 // resolution process, we still need to handle the enable_if attribute. Do
12126 // that here, so it will not hide previous -- and more relevant -- errors
12127 if (isa<MemberExpr>(NakedMemExpr)) {
12128 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12129 Diag(MemExprE->getLocStart(),
12130 diag::err_ovl_no_viable_member_function_in_call)
12131 << Method << Method->getSourceRange();
12132 Diag(Method->getLocation(),
12133 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12134 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12135 return ExprError();
12136 }
12137 }
12138
Anders Carlsson47061ee2011-05-06 14:25:31 +000012139 if ((isa<CXXConstructorDecl>(CurContext) ||
12140 isa<CXXDestructorDecl>(CurContext)) &&
12141 TheCall->getMethodDecl()->isPure()) {
12142 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12143
Davide Italianoccb37382015-07-14 23:36:10 +000012144 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12145 MemExpr->performsVirtualDispatch(getLangOpts())) {
12146 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012147 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12148 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12149 << MD->getParent()->getDeclName();
12150
12151 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012152 if (getLangOpts().AppleKext)
12153 Diag(MemExpr->getLocStart(),
12154 diag::note_pure_qualified_call_kext)
12155 << MD->getParent()->getDeclName()
12156 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012157 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012158 }
John McCallb268a282010-08-23 23:25:46 +000012159 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012160}
12161
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012162/// BuildCallToObjectOfClassType - Build a call to an object of class
12163/// type (C++ [over.call.object]), which can end up invoking an
12164/// overloaded function call operator (@c operator()) or performing a
12165/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012166ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012167Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012168 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012169 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012170 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012171 if (checkPlaceholderForOverload(*this, Obj))
12172 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012173 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012174
12175 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012176 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012177 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012178
Nico Weberb58e51c2014-11-19 05:21:39 +000012179 assert(Object.get()->getType()->isRecordType() &&
12180 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012181 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012182
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012183 // C++ [over.call.object]p1:
12184 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012185 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012186 // candidate functions includes at least the function call
12187 // operators of T. The function call operators of T are obtained by
12188 // ordinary lookup of the name operator() in the context of
12189 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012190 OverloadCandidateSet CandidateSet(LParenLoc,
12191 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012192 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012193
John Wiegley01296292011-04-08 18:41:53 +000012194 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012195 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012196 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012197
John McCall27b18f82009-11-17 02:14:36 +000012198 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12199 LookupQualifiedName(R, Record->getDecl());
12200 R.suppressDiagnostics();
12201
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012202 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012203 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012204 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012205 Object.get()->Classify(Context),
12206 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012207 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012209
Douglas Gregorab7897a2008-11-19 22:57:39 +000012210 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012211 // In addition, for each (non-explicit in C++0x) conversion function
12212 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012213 //
12214 // operator conversion-type-id () cv-qualifier;
12215 //
12216 // where cv-qualifier is the same cv-qualification as, or a
12217 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012218 // denotes the type "pointer to function of (P1,...,Pn) returning
12219 // R", or the type "reference to pointer to function of
12220 // (P1,...,Pn) returning R", or the type "reference to function
12221 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012222 // is also considered as a candidate function. Similarly,
12223 // surrogate call functions are added to the set of candidate
12224 // functions for each conversion function declared in an
12225 // accessible base class provided the function is not hidden
12226 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012227 const auto &Conversions =
12228 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12229 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012230 NamedDecl *D = *I;
12231 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12232 if (isa<UsingShadowDecl>(D))
12233 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012234
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012235 // Skip over templated conversion functions; they aren't
12236 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012237 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012238 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012239
John McCall6e9f8f62009-12-03 04:06:58 +000012240 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012241 if (!Conv->isExplicit()) {
12242 // Strip the reference type (if any) and then the pointer type (if
12243 // any) to get down to what might be a function type.
12244 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12245 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12246 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012247
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012248 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12249 {
12250 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012251 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012252 }
12253 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012254 }
Mike Stump11289f42009-09-09 15:08:12 +000012255
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012256 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12257
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012258 // Perform overload resolution.
12259 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012260 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012261 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012262 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012263 // Overload resolution succeeded; we'll build the appropriate call
12264 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012265 break;
12266
12267 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012268 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012269 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012270 << Object.get()->getType() << /*call*/ 1
12271 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012272 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012273 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012274 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012275 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012277 break;
12278
12279 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012280 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012281 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012282 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012283 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012284 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012285
12286 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012287 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012288 diag::err_ovl_deleted_object_call)
12289 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012290 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012291 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012292 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012293 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012294 break;
Mike Stump11289f42009-09-09 15:08:12 +000012295 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012296
Douglas Gregorb412e172010-07-25 18:17:45 +000012297 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012298 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012299
John McCall4124c492011-10-17 18:40:02 +000012300 UnbridgedCasts.restore();
12301
Craig Topperc3ec1492014-05-26 06:22:03 +000012302 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012303 // Since there is no function declaration, this is one of the
12304 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012305 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012306 = cast<CXXConversionDecl>(
12307 Best->Conversions[0].UserDefined.ConversionFunction);
12308
Craig Topperc3ec1492014-05-26 06:22:03 +000012309 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12310 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012311 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12312 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012313 assert(Conv == Best->FoundDecl.getDecl() &&
12314 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012315 // We selected one of the surrogate functions that converts the
12316 // object parameter to a function pointer. Perform the conversion
12317 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012318
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012319 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012320 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012321 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12322 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012323 if (Call.isInvalid())
12324 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012325 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012326 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12327 CK_UserDefinedConversion, Call.get(),
12328 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012329
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012330 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012331 }
12332
Craig Topperc3ec1492014-05-26 06:22:03 +000012333 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012334
Douglas Gregorab7897a2008-11-19 22:57:39 +000012335 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12336 // that calls this method, using Object for the implicit object
12337 // parameter and passing along the remaining arguments.
12338 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012339
12340 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012341 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012342 return ExprError();
12343
Chandler Carruth8e543b32010-12-12 08:17:55 +000012344 const FunctionProtoType *Proto =
12345 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012346
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012347 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012348
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012349 DeclarationNameInfo OpLocInfo(
12350 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12351 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012352 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012353 HadMultipleCandidates,
12354 OpLocInfo.getLoc(),
12355 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012356 if (NewFn.isInvalid())
12357 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012358
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012359 // Build the full argument list for the method call (the implicit object
12360 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012361 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012362 MethodArgs[0] = Object.get();
12363 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12364
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012365 // Once we've built TheCall, all of the expressions are properly
12366 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012367 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012368 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12369 ResultTy = ResultTy.getNonLValueExprType(Context);
12370
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012371 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012372 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012373 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12374 ResultTy, VK, RParenLoc, false);
12375 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012376
Alp Toker314cc812014-01-25 16:55:45 +000012377 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012378 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012379
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012380 // We may have default arguments. If so, we need to allocate more
12381 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012382 if (Args.size() < NumParams)
12383 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012384
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012385 bool IsError = false;
12386
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012387 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012388 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012389 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012390 Best->FoundDecl, Method);
12391 if (ObjRes.isInvalid())
12392 IsError = true;
12393 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012394 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012395 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012396
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012397 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012398 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012399 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012400 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012401 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012402
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012403 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012404
John McCalldadc5752010-08-24 06:29:42 +000012405 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012406 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012407 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012408 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012409 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012410
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012411 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012412 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012413 } else {
John McCalldadc5752010-08-24 06:29:42 +000012414 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012415 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12416 if (DefArg.isInvalid()) {
12417 IsError = true;
12418 break;
12419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012420
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012421 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012422 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012423
12424 TheCall->setArg(i + 1, Arg);
12425 }
12426
12427 // If this is a variadic call, handle args passed through "...".
12428 if (Proto->isVariadic()) {
12429 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012430 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012431 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12432 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012433 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012434 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012435 }
12436 }
12437
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012438 if (IsError) return true;
12439
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012440 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012441
Richard Smith55ce3522012-06-25 20:30:08 +000012442 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012443 return true;
12444
John McCalle172be52010-08-24 06:09:16 +000012445 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012446}
12447
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012448/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012449/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012450/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012451ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012452Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12453 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012454 assert(Base->getType()->isRecordType() &&
12455 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012456
John McCall4124c492011-10-17 18:40:02 +000012457 if (checkPlaceholderForOverload(*this, Base))
12458 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012459
John McCallbc077cf2010-02-08 23:07:23 +000012460 SourceLocation Loc = Base->getExprLoc();
12461
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012462 // C++ [over.ref]p1:
12463 //
12464 // [...] An expression x->m is interpreted as (x.operator->())->m
12465 // for a class object x of type T if T::operator->() exists and if
12466 // the operator is selected as the best match function by the
12467 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012468 DeclarationName OpName =
12469 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012470 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012471 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012472
John McCallbc077cf2010-02-08 23:07:23 +000012473 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012474 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012475 return ExprError();
12476
John McCall27b18f82009-11-17 02:14:36 +000012477 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12478 LookupQualifiedName(R, BaseRecord->getDecl());
12479 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012480
12481 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012482 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012483 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012484 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012485 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012486
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012487 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12488
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012489 // Perform overload resolution.
12490 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012491 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012492 case OR_Success:
12493 // Overload resolution succeeded; we'll build the call below.
12494 break;
12495
12496 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012497 if (CandidateSet.empty()) {
12498 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012499 if (NoArrowOperatorFound) {
12500 // Report this specific error to the caller instead of emitting a
12501 // diagnostic, as requested.
12502 *NoArrowOperatorFound = true;
12503 return ExprError();
12504 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012505 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12506 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012507 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012508 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012509 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012510 }
12511 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012512 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012513 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012514 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012515 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012516
12517 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012518 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12519 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012520 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012521 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012522
12523 case OR_Deleted:
12524 Diag(OpLoc, diag::err_ovl_deleted_oper)
12525 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012526 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012527 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012528 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012529 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012530 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012531 }
12532
Craig Topperc3ec1492014-05-26 06:22:03 +000012533 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012534
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012535 // Convert the object parameter.
12536 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012537 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012538 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012539 Best->FoundDecl, Method);
12540 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012541 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012542 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012543
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012544 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012545 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012546 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012547 if (FnExpr.isInvalid())
12548 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012549
Alp Toker314cc812014-01-25 16:55:45 +000012550 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012551 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12552 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012553 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012554 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012555 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012556
Alp Toker314cc812014-01-25 16:55:45 +000012557 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012558 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012559
12560 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012561}
12562
Richard Smithbcc22fc2012-03-09 08:00:36 +000012563/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12564/// a literal operator described by the provided lookup results.
12565ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12566 DeclarationNameInfo &SuffixInfo,
12567 ArrayRef<Expr*> Args,
12568 SourceLocation LitEndLoc,
12569 TemplateArgumentListInfo *TemplateArgs) {
12570 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012571
Richard Smith100b24a2014-04-17 01:52:14 +000012572 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12573 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012574 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12575 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012576
Richard Smithbcc22fc2012-03-09 08:00:36 +000012577 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12578
Richard Smithbcc22fc2012-03-09 08:00:36 +000012579 // Perform overload resolution. This will usually be trivial, but might need
12580 // to perform substitutions for a literal operator template.
12581 OverloadCandidateSet::iterator Best;
12582 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12583 case OR_Success:
12584 case OR_Deleted:
12585 break;
12586
12587 case OR_No_Viable_Function:
12588 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12589 << R.getLookupName();
12590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12591 return ExprError();
12592
12593 case OR_Ambiguous:
12594 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12595 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12596 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012597 }
12598
Richard Smithbcc22fc2012-03-09 08:00:36 +000012599 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012600 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12601 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012602 SuffixInfo.getLoc(),
12603 SuffixInfo.getInfo());
12604 if (Fn.isInvalid())
12605 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012606
12607 // Check the argument types. This should almost always be a no-op, except
12608 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012609 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012610 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012611 ExprResult InputInit = PerformCopyInitialization(
12612 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12613 SourceLocation(), Args[ArgIdx]);
12614 if (InputInit.isInvalid())
12615 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012616 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012617 }
12618
Alp Toker314cc812014-01-25 16:55:45 +000012619 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012620 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12621 ResultTy = ResultTy.getNonLValueExprType(Context);
12622
Richard Smithc67fdd42012-03-07 08:35:16 +000012623 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012624 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012625 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012626 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12627
Alp Toker314cc812014-01-25 16:55:45 +000012628 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012629 return ExprError();
12630
Craig Topperc3ec1492014-05-26 06:22:03 +000012631 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012632 return ExprError();
12633
12634 return MaybeBindToTemporary(UDL);
12635}
12636
Sam Panzer0f384432012-08-21 00:52:01 +000012637/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12638/// given LookupResult is non-empty, it is assumed to describe a member which
12639/// will be invoked. Otherwise, the function will be found via argument
12640/// dependent lookup.
12641/// CallExpr is set to a valid expression and FRS_Success returned on success,
12642/// otherwise CallExpr is set to ExprError() and some non-success value
12643/// is returned.
12644Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012645Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12646 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012647 const DeclarationNameInfo &NameInfo,
12648 LookupResult &MemberLookup,
12649 OverloadCandidateSet *CandidateSet,
12650 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012651 Scope *S = nullptr;
12652
Sam Panzer0f384432012-08-21 00:52:01 +000012653 CandidateSet->clear();
12654 if (!MemberLookup.empty()) {
12655 ExprResult MemberRef =
12656 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12657 /*IsPtr=*/false, CXXScopeSpec(),
12658 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012659 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012660 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012661 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012662 if (MemberRef.isInvalid()) {
12663 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012664 return FRS_DiagnosticIssued;
12665 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012666 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012667 if (CallExpr->isInvalid()) {
12668 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012669 return FRS_DiagnosticIssued;
12670 }
12671 } else {
12672 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012673 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012674 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012675 NestedNameSpecifierLoc(), NameInfo,
12676 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012677 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012678
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012679 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012680 CandidateSet, CallExpr);
12681 if (CandidateSet->empty() || CandidateSetError) {
12682 *CallExpr = ExprError();
12683 return FRS_NoViableFunction;
12684 }
12685 OverloadCandidateSet::iterator Best;
12686 OverloadingResult OverloadResult =
12687 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12688
12689 if (OverloadResult == OR_No_Viable_Function) {
12690 *CallExpr = ExprError();
12691 return FRS_NoViableFunction;
12692 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012693 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012694 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012695 OverloadResult,
12696 /*AllowTypoCorrection=*/false);
12697 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12698 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012699 return FRS_DiagnosticIssued;
12700 }
12701 }
12702 return FRS_Success;
12703}
12704
12705
Douglas Gregorcd695e52008-11-10 20:40:00 +000012706/// FixOverloadedFunctionReference - E is an expression that refers to
12707/// a C++ overloaded function (possibly with some parentheses and
12708/// perhaps a '&' around it). We have resolved the overloaded function
12709/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012710/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012711Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012712 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012713 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012714 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12715 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012716 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012717 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012718
Douglas Gregor51c538b2009-11-20 19:42:02 +000012719 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012720 }
12721
Douglas Gregor51c538b2009-11-20 19:42:02 +000012722 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012723 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12724 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012725 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012726 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012727 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012728 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012729 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012730 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012731
12732 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012733 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012734 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012735 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012736 }
12737
Douglas Gregor51c538b2009-11-20 19:42:02 +000012738 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012739 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012740 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012741 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12742 if (Method->isStatic()) {
12743 // Do nothing: static member functions aren't any different
12744 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012745 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012746 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012747 // UnresolvedLookupExpr holding an overloaded member function
12748 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012749 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12750 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012751 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012752 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012753
John McCalld14a8642009-11-21 08:51:07 +000012754 assert(isa<DeclRefExpr>(SubExpr)
12755 && "fixed to something other than a decl ref");
12756 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12757 && "fixed to a member ref with no nested name qualifier");
12758
12759 // We have taken the address of a pointer to member
12760 // function. Perform the computation here so that we get the
12761 // appropriate pointer to member type.
12762 QualType ClassType
12763 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12764 QualType MemPtrType
12765 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12766
John McCall7decc9e2010-11-18 06:31:45 +000012767 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12768 VK_RValue, OK_Ordinary,
12769 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012770 }
12771 }
John McCall16df1e52010-03-30 21:47:33 +000012772 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12773 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012774 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012775 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012776
John McCalle3027922010-08-25 11:45:40 +000012777 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012778 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012779 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012780 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012781 }
John McCalld14a8642009-11-21 08:51:07 +000012782
12783 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012784 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012785 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012786 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012787 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12788 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012789 }
12790
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012791 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12792 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012793 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012794 Fn,
John McCall113bee02012-03-10 09:33:50 +000012795 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012796 ULE->getNameLoc(),
12797 Fn->getType(),
12798 VK_LValue,
12799 Found.getDecl(),
12800 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012801 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012802 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12803 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012804 }
12805
John McCall10eae182009-11-30 22:42:35 +000012806 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012807 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012808 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012809 if (MemExpr->hasExplicitTemplateArgs()) {
12810 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12811 TemplateArgs = &TemplateArgsBuffer;
12812 }
John McCall6b51f282009-11-23 01:53:49 +000012813
John McCall2d74de92009-12-01 22:10:20 +000012814 Expr *Base;
12815
John McCall7decc9e2010-11-18 06:31:45 +000012816 // If we're filling in a static method where we used to have an
12817 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012818 if (MemExpr->isImplicitAccess()) {
12819 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012820 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12821 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012822 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012823 Fn,
John McCall113bee02012-03-10 09:33:50 +000012824 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012825 MemExpr->getMemberLoc(),
12826 Fn->getType(),
12827 VK_LValue,
12828 Found.getDecl(),
12829 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012830 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012831 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12832 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012833 } else {
12834 SourceLocation Loc = MemExpr->getMemberLoc();
12835 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012836 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012837 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012838 Base = new (Context) CXXThisExpr(Loc,
12839 MemExpr->getBaseType(),
12840 /*isImplicit=*/true);
12841 }
John McCall2d74de92009-12-01 22:10:20 +000012842 } else
John McCallc3007a22010-10-26 07:05:15 +000012843 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012844
John McCall4adb38c2011-04-27 00:36:17 +000012845 ExprValueKind valueKind;
12846 QualType type;
12847 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12848 valueKind = VK_LValue;
12849 type = Fn->getType();
12850 } else {
12851 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012852 type = Context.BoundMemberTy;
12853 }
12854
12855 MemberExpr *ME = MemberExpr::Create(
12856 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12857 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12858 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12859 OK_Ordinary);
12860 ME->setHadMultipleCandidates(true);
12861 MarkMemberReferenced(ME);
12862 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012864
John McCallc3007a22010-10-26 07:05:15 +000012865 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012866}
12867
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012868ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012869 DeclAccessPair Found,
12870 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012871 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012872}