blob: 0e53ffa83fefceeb6ba6a0caec6db6fb960487a5 [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"
George Burgess IV177399e2017-01-09 04:12:14 +000032#include "llvm/ADT/Optional.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000034#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000037#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
Richard Smith17c00b42014-11-12 01:24:00 +000039using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000040using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000041
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000042static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000043 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000046}
47
Nick Lewycky134af912013-02-07 05:08:22 +000048/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000049static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000050CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000051 const Expr *Base, bool HadMultipleCandidates,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000052 SourceLocation Loc = SourceLocation(),
Douglas Gregore9d62932011-07-15 16:25:15 +000053 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000054 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000055 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000056 // If FoundDecl is different from Fn (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000057 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000058 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000063 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000064 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000066 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000067 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000070
Akira Hatanaka22461672017-07-13 06:08:27 +000071 S.MarkDeclRefReferenced(DRE, Base);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000072 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000074}
75
John McCall5c32be02010-08-24 20:38:10 +000076static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000078 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000079 bool CStyle,
80 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000081
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000082static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000083 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000087static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000091 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000093
94
95static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000096CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000097 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000120 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Promotion,
122 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000131 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000132 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000133 ICR_Conversion,
Egor Churaevc217f372017-03-21 12:55:55 +0000134 ICR_OCL_Scalar_Widening,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000137 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000156 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Integral conversion",
162 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000167 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000168 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000172 "Complex-real conversion",
173 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000174 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000177 "C specific type conversion",
178 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Richard Smith66e05fe2012-01-18 05:21:49 +0000258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000267 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000294 APValue &ConstantValue,
295 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
Richard Smith66e05fe2012-01-18 05:21:49 +0000309 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
Richard Smith66e05fe2012-01-18 05:21:49 +0000320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000327 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000333 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000334
335 // If it's value-dependent, we can't tell whether it's narrowing.
336 if (Initializer->isValueDependent())
337 return NK_Dependent_Narrowing;
338
Simon Pilgrimf9409872017-06-01 18:13:02 +0000339 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000352 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000389 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000390 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000402 case ICK_Integral_Conversion:
403 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
Richard Smith25a80d42012-06-13 01:07:41 +0000422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000431 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000432 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000462/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000464LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000477
478 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000492 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000515 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 }
517}
518
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000521void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000522 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 switch (ConversionKind) {
526 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000528 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 break;
530 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536 break;
John McCall0d1da222010-01-12 00:44:57 +0000537 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000538 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000539 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000541 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 break;
543 }
544
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546}
547
John McCall0d1da222010-01-12 00:44:57 +0000548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000564 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000565 // template argument information.
566 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
Richard Smith9b534542015-12-31 02:02:54 +0000575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000589 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000591 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 return Result;
655}
John McCall0d1da222010-01-12 00:44:57 +0000656
Larisse Voufo98b20f12013-07-19 23:00:19 +0000657void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000660 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000666 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000667 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000671 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000672 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000673 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000674 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000675 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000678
679 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000680 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Douglas Gregor461761d2010-05-08 18:20:53 +0000688 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000689 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 break;
691 }
692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Larisse Voufo98b20f12013-07-19 23:00:19 +0000694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000697 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000698}
699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000703 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000707 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000708 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000709 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000711 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000712 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000716 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000724 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 break;
726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 return TemplateParameter();
729}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Larisse Voufo98b20f12013-07-19 23:00:19 +0000731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000743 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000744 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000746
Richard Smith9b534542015-12-31 02:02:54 +0000747 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000748 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753
Richard Smith44ecdbd2013-01-31 05:19:49 +0000754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000757 }
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000760}
761
Larisse Voufo98b20f12013-07-19 23:00:19 +0000762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000765 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000770 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000771 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000772 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000773 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000774 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000777 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000778 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000779 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Douglas Gregor461761d2010-05-08 18:20:53 +0000783 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000784 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 break;
786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000794 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000799 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000800 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000801 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000802 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000804
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000806 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000807 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000808 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000811
Douglas Gregor461761d2010-05-08 18:20:53 +0000812 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000813 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000814 break;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000818}
819
Richard Smith9b534542015-12-31 02:02:54 +0000820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
Richard Smithc92d2062017-01-05 23:02:44 +0000826 default:
827 return llvm::None;
828 }
Richard Smith9b534542015-12-31 02:02:54 +0000829}
830
Benjamin Kramer97e59492012-10-09 15:52:25 +0000831void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000832 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000838}
839
Richard Smith67ef14f2017-09-26 18:37:55 +0000840void OverloadCandidateSet::clear(CandidateSetKind CSK) {
Benjamin Kramer97e59492012-10-09 15:52:25 +0000841 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000844 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000845 Functions.clear();
Richard Smith67ef14f2017-09-26 18:37:55 +0000846 Kind = CSK;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000847}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
John McCall4124c492011-10-17 18:40:02 +0000849namespace {
850 class UnbridgedCastsSet {
851 struct Entry {
852 Expr **Addr;
853 Expr *Saved;
854 };
855 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000856
John McCall4124c492011-10-17 18:40:02 +0000857 public:
858 void save(Sema &S, Expr *&E) {
859 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
860 Entry entry = { &E, E };
861 Entries.push_back(entry);
862 E = S.stripARCUnbridgedCast(E);
863 }
864
865 void restore() {
866 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000867 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000868 *i->Addr = i->Saved;
869 }
870 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000871}
John McCall4124c492011-10-17 18:40:02 +0000872
873/// checkPlaceholderForOverload - Do any interesting placeholder-like
874/// preprocessing on the given expression.
875///
876/// \param unbridgedCasts a collection to which to add unbridged casts;
877/// without this, they will be immediately diagnosed as errors
878///
879/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000880static bool
881checkPlaceholderForOverload(Sema &S, Expr *&E,
882 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000883 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
884 // We can't handle overloaded expressions here because overload
885 // resolution might reasonably tweak them.
886 if (placeholder->getKind() == BuiltinType::Overload) return false;
887
888 // If the context potentially accepts unbridged ARC casts, strip
889 // the unbridged cast and add it to the collection for later restoration.
890 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891 unbridgedCasts) {
892 unbridgedCasts->save(S, E);
893 return false;
894 }
895
896 // Go ahead and check everything else.
897 ExprResult result = S.CheckPlaceholderExpr(E);
898 if (result.isInvalid())
899 return true;
900
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000901 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000902 return false;
903 }
904
905 // Nothing to do.
906 return false;
907}
908
909/// checkArgPlaceholdersForOverload - Check a set of call operands for
910/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000911static bool checkArgPlaceholdersForOverload(Sema &S,
912 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000913 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000914 for (unsigned i = 0, e = Args.size(); i != e; ++i)
915 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000916 return true;
917
918 return false;
919}
920
George Burgess IV2d82b092017-04-06 00:23:31 +0000921/// Determine whether the given New declaration is an overload of the
922/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923/// New and Old cannot be overloaded, e.g., if New has the same signature as
924/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925/// functions (or function templates) at all. When it does return Ovl_Match or
926/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
928/// declaration.
929///
930/// Example: Given the following input:
931///
932/// void f(int, float); // #1
933/// void f(int, int); // #2
934/// int f(int, int); // #3
935///
936/// When we process #1, there is no previous declaration of "f", so IsOverload
937/// will not be used.
938///
939/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940/// the parameter types, we see that #1 and #2 are overloaded (since they have
941/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
942/// unchanged.
943///
944/// When we process #3, Old is an overload set containing #1 and #2. We compare
945/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947/// functions are not part of the signature), IsOverload returns Ovl_Match and
948/// MatchedDecl will be set to point to the FunctionDecl for #2.
949///
950/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951/// by a using declaration. The rules for whether to hide shadow declarations
952/// ignore some properties which otherwise figure into a function template's
953/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000954Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000955Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000958 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000959 NamedDecl *OldD = *I;
960
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
964
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
968
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970 }
971
Richard Smithf091e122015-09-15 01:28:55 +0000972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975 continue;
976
John McCalle9cccd82010-06-16 08:42:20 +0000977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000985
Alp Tokera2794f92014-01-22 07:29:52 +0000986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990 continue;
991 }
992
Alp Tokera2794f92014-01-22 07:29:52 +0000993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000995 continue;
996
John McCalldaa3d6b2009-12-09 03:35:25 +0000997 Match = *I;
998 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000999 }
Richard Smith151c4562016-12-20 21:35:28 +00001000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001010 //
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 Match = *I;
1015 return Ovl_NonFunction;
1016 }
John McCall84d87672009-12-10 09:41:52 +00001017 } else {
John McCall1f82f242009-11-18 22:49:29 +00001018 // (C++ 13p1):
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001021 Match = *I;
1022 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001023 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024 }
John McCall1f82f242009-11-18 22:49:29 +00001025
John McCalldaa3d6b2009-12-09 03:35:25 +00001026 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001027}
1028
Richard Smithac974a32013-06-30 09:48:50 +00001029bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1032 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001033 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001034
David Majnemerc729b0b2013-09-16 22:44:20 +00001035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1037 return false;
1038
John McCall1f82f242009-11-18 22:49:29 +00001039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001046 return true;
1047
1048 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001051
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1055
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060 return false;
1061
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001064
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001069 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001070 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001071 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001072 return true;
1073
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1079 // signature.
1080 //
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001083 //
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001086 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001090 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001091 return true;
1092
1093 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001095 //
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001103 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001106 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001118 }
1119 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
Richard Smith574f4f62013-01-14 05:37:29 +00001122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001126 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001127 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001129 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001130 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001131
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001136 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1145 return true;
1146
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1155 return true;
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001159 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001160 return true;
1161 }
1162
Justin Lebarba122ab2016-03-30 23:30:21 +00001163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1167 return false;
1168
Artem Belevich94a55e82015-09-22 17:22:59 +00001169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001171 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001172 return false;
1173
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175
Justin Lebar53b000af2016-10-03 16:48:27 +00001176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001178 return NewTarget != OldTarget;
1179 }
1180
John McCall1f82f242009-11-18 22:49:29 +00001181 // The signatures match; this is not an overload.
1182 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183}
1184
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001185/// \brief Checks availability of the function depending on the current
1186/// function context. Inside an unavailable function, unavailability is ignored.
1187///
1188/// \returns true if \arg FD is unavailable and current context is inside
1189/// an available function, false otherwise.
1190bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001191 if (!FD->isUnavailable())
1192 return false;
1193
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1196 do {
1197 if (C->isUnavailable())
1198 return false;
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001201}
1202
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001203/// \brief Tries a user-defined conversion from From to ToType.
1204///
1205/// Produces an implicit conversion sequence for when a standard conversion
1206/// is not an option. See TryImplicitConversion for more information.
1207static ImplicitConversionSequence
1208TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001215 ImplicitConversionSequence ICS;
1216
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1219 // we can perform.
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221 return ICS;
1222 }
1223
1224 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1230 case OR_Success:
1231 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 QualType FromCanon
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 QualType ToCanon
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001257 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1260 }
1261 }
Richard Smith48372b62015-01-27 03:30:40 +00001262 break;
1263
1264 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001265 ICS.setAmbiguous();
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1270 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001272 break;
Richard Smith48372b62015-01-27 03:30:40 +00001273
1274 // Fall through.
1275 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001277 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001278 }
1279
1280 return ICS;
1281}
1282
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001283/// TryImplicitConversion - Attempt to perform an implicit conversion
1284/// from the given expression (Expr) to the given type (ToType). This
1285/// function returns an implicit conversion sequence that can be used
1286/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287///
1288/// void f(float f);
1289/// void g(int i) { f(i); }
1290///
1291/// this routine would produce an implicit conversion sequence to
1292/// describe the initialization of f from i, which will be a standard
1293/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295//
1296/// Note that this routine only determines how the conversion can be
1297/// performed; it does not actually perform the conversion. As such,
1298/// it will not produce any diagnostics if no conversion is available,
1299/// but will instead return an implicit conversion sequence of kind
1300/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001301///
1302/// If @p SuppressUserConversions, then user-defined conversions are
1303/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001304/// If @p AllowExplicit, then explicit user-defined conversions are
1305/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001306///
1307/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308/// writeback conversion, which allows __autoreleasing id* parameters to
1309/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001310static ImplicitConversionSequence
1311TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001314 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001315 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001321 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001322 return ICS;
1323 }
1324
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001327 return ICS;
1328 }
1329
Douglas Gregor836a7e82010-08-11 02:15:33 +00001330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001341 ICS.setStandard();
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor5ab11652010-04-17 22:01:05 +00001346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001350 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor5ab11652010-04-17 22:01:05 +00001352 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001354 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Douglas Gregor836a7e82010-08-11 02:15:33 +00001356 return ICS;
1357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001363}
1364
John McCall31168b02011-06-15 23:02:42 +00001365ImplicitConversionSequence
1366Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1368 bool AllowExplicit,
1369 bool InOverloadResolution,
1370 bool CStyle,
1371 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001372 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001373 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001374 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001377}
1378
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001379/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001380/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001381/// converted expression. Flavor is the kind of conversion we're
1382/// performing, used in the error message. If @p AllowExplicit,
1383/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001384ExprResult
1385Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001386 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001387 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001389}
1390
John Wiegley01296292011-04-08 18:41:53 +00001391ExprResult
1392Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001393 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001394 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001395 if (checkPlaceholderForOverload(*this, From))
1396 return ExprError();
1397
John McCall31168b02011-06-15 23:02:42 +00001398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001400 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001401 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1407 AllowExplicit,
1408 /*InOverloadResolution=*/false,
1409 /*CStyle=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001412 return PerformImplicitConversion(From, ToType, ICS, Action);
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
1415/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001416/// conversion that strips "noexcept" or "noreturn" off the nested function
1417/// type.
1418bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001419 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1421 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
John McCall991eb4b2010-12-21 00:44:39 +00001423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001424 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001425 // where F adds one of the following at most once:
1426 // - a pointer
1427 // - a member pointer
1428 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001429 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1446 return false;
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001449 } else {
1450 return false;
1451 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001452
John McCall991eb4b2010-12-21 00:44:39 +00001453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456 return false;
1457 }
1458
Richard Smith3c4f8d22016-10-16 17:54:23 +00001459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001461
Richard Smith6f427402016-10-20 00:01:36 +00001462 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464
1465 bool Changed = false;
1466
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470 Changed = true;
1471 }
1472
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
1478 Context.getFunctionType(FromFPT->getReturnType(),
1479 FromFPT->getParamTypes(),
1480 FromFPT->getExtProtoInfo().withExceptionSpec(
1481 FunctionProtoType::ExceptionSpecInfo()))
1482 .getTypePtr());
1483 Changed = true;
1484 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00001485
1486 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1487 // only if the ExtParameterInfo lists of the two function prototypes can be
1488 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1489 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1490 bool CanUseToFPT, CanUseFromFPT;
1491 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1492 CanUseFromFPT, NewParamInfos) &&
1493 CanUseToFPT && !CanUseFromFPT) {
1494 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1495 ExtInfo.ExtParameterInfos =
1496 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1497 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1498 FromFPT->getParamTypes(), ExtInfo);
1499 FromFn = QT->getAs<FunctionType>();
1500 Changed = true;
1501 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001502 }
1503
1504 if (!Changed)
1505 return false;
1506
John McCall991eb4b2010-12-21 00:44:39 +00001507 assert(QualType(FromFn, 0).isCanonical());
1508 if (QualType(FromFn, 0) != CanTo) return false;
1509
1510 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001511 return true;
1512}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001513
Douglas Gregor46188682010-05-18 22:42:18 +00001514/// \brief Determine whether the conversion from FromType to ToType is a valid
1515/// vector conversion.
1516///
1517/// \param ICK Will be set to the vector conversion kind, if this is a vector
1518/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001519static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001521 // We need at least one of these types to be a vector type to have a vector
1522 // conversion.
1523 if (!ToType->isVectorType() && !FromType->isVectorType())
1524 return false;
1525
1526 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001527 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001528 return false;
1529
1530 // There are no conversions between extended vector types, only identity.
1531 if (ToType->isExtVectorType()) {
1532 // There are no conversions between extended vector types other than the
1533 // identity conversion.
1534 if (FromType->isExtVectorType())
1535 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536
Douglas Gregor46188682010-05-18 22:42:18 +00001537 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001538 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001539 ICK = ICK_Vector_Splat;
1540 return true;
1541 }
1542 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001543
1544 // We can perform the conversion between vector types in the following cases:
1545 // 1)vector types are equivalent AltiVec and GCC vector types
1546 // 2)lax vector conversions are permitted and the vector types are of the
1547 // same size
1548 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001549 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1550 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001551 ICK = ICK_Vector_Conversion;
1552 return true;
1553 }
Douglas Gregor46188682010-05-18 22:42:18 +00001554 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001555
Douglas Gregor46188682010-05-18 22:42:18 +00001556 return false;
1557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001559static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1560 bool InOverloadResolution,
1561 StandardConversionSequence &SCS,
1562 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001563
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564/// IsStandardConversion - Determines whether there is a standard
1565/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1566/// expression From to the type ToType. Standard conversion sequences
1567/// only consider non-class types; for conversions that involve class
1568/// types, use TryImplicitConversion. If a conversion exists, SCS will
1569/// contain the standard conversion sequence required to perform this
1570/// conversion and this routine will return true. Otherwise, this
1571/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001572static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1573 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001574 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001575 bool CStyle,
1576 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001578
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001579 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001580 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001581 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001582 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001583 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001585 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001586 // abort early. When overloading in C, however, we do permit them.
1587 if (S.getLangOpts().CPlusPlus &&
1588 (FromType->isRecordType() || ToType->isRecordType()))
1589 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001590
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 // The first conversion can be an lvalue-to-rvalue conversion,
1592 // array-to-pointer conversion, or function-to-pointer conversion
1593 // (C++ 4p1).
1594
John McCall5c32be02010-08-24 20:38:10 +00001595 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001596 DeclAccessPair AccessPair;
1597 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001599 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001600 // We were able to resolve the address of the overloaded function,
1601 // so we can convert to the type of that function.
1602 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001603 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001604
1605 // we can sometimes resolve &foo<int> regardless of ToType, so check
1606 // if the type matches (identity) or we are converting to bool
1607 if (!S.Context.hasSameUnqualifiedType(
1608 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1609 QualType resultTy;
1610 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001611 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001612 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001613 // otherwise, only a boolean conversion is standard
1614 if (!ToType->isBooleanType())
1615 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001617
Chandler Carruthffce2452011-03-29 08:08:18 +00001618 // Check if the "from" expression is taking the address of an overloaded
1619 // function and recompute the FromType accordingly. Take advantage of the
1620 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001621 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001622 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1623 if (Method && !Method->isStatic()) {
1624 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1625 "Non-unary operator on non-static member address");
1626 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1627 == UO_AddrOf &&
1628 "Non-address-of operator on non-static member address");
1629 const Type *ClassType
1630 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1631 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001632 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1633 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1634 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001635 "Non-address-of operator for overloaded function expression");
1636 FromType = S.Context.getPointerType(FromType);
1637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
Douglas Gregor980fb162010-04-29 18:24:40 +00001639 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001640 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1641 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001642 assert(S.Context.hasSameType(
1643 FromType,
1644 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001645 } else {
1646 return false;
1647 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001648 }
John McCall154a2fd2011-08-30 00:57:29 +00001649 // Lvalue-to-rvalue conversion (C++11 4.1):
1650 // A glvalue (3.10) of a non-function, non-array type T can
1651 // be converted to a prvalue.
1652 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001653 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001654 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001655 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657
Douglas Gregorc79862f2012-04-12 17:51:55 +00001658 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001659 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001660 // of the type of the lvalue ...
1661 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1662 FromType = Atomic->getValueType();
1663
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 // If T is a non-class type, the type of the rvalue is the
1665 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001666 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1667 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001669 } else if (FromType->isArrayType()) {
1670 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001671 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672
1673 // An lvalue or rvalue of type "array of N T" or "array of unknown
1674 // bound of T" can be converted to an rvalue of type "pointer to
1675 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001676 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677
John McCall5c32be02010-08-24 20:38:10 +00001678 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001679 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001680 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681
1682 // For the purpose of ranking in overload resolution
1683 // (13.3.3.1.1), this conversion is considered an
1684 // array-to-pointer conversion followed by a qualification
1685 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001686 SCS.Second = ICK_Identity;
1687 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001688 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001689 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001690 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001691 }
John McCall086a4642010-11-24 05:12:34 +00001692 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001693 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001694 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001696 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1697 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1698 if (!S.checkAddressOfFunctionIsAvailable(FD))
1699 return false;
1700
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701 // An lvalue of function type T can be converted to an rvalue of
1702 // type "pointer to T." The result is a pointer to the
1703 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001704 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001705 } else {
1706 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001709 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
1711 // The second conversion can be an integral promotion, floating
1712 // point promotion, integral conversion, floating point conversion,
1713 // floating-integral conversion, pointer conversion,
1714 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001715 // For overloading in C, this can also be a "compatible-type"
1716 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001717 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001718 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001719 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 // The unqualified versions of the types are the same: there's no
1721 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001722 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001723 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001724 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001725 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001727 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001728 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001729 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001731 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001732 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001733 SCS.Second = ICK_Complex_Promotion;
1734 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001735 } else if (ToType->isBooleanType() &&
1736 (FromType->isArithmeticType() ||
1737 FromType->isAnyPointerType() ||
1738 FromType->isBlockPointerType() ||
1739 FromType->isMemberPointerType() ||
1740 FromType->isNullPtrType())) {
1741 // Boolean conversions (C++ 4.12).
1742 SCS.Second = ICK_Boolean_Conversion;
1743 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001744 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001745 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001746 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001747 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001749 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001750 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001751 SCS.Second = ICK_Complex_Conversion;
1752 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001753 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1754 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001755 // Complex-real conversions (C99 6.3.1.7)
1756 SCS.Second = ICK_Complex_Real;
1757 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001758 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001759 // FIXME: disable conversions between long double and __float128 if
1760 // their representation is different until there is back end support
1761 // We of course allow this conversion if long double is really double.
1762 if (&S.Context.getFloatTypeSemantics(FromType) !=
1763 &S.Context.getFloatTypeSemantics(ToType)) {
1764 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1765 ToType == S.Context.LongDoubleTy) ||
1766 (FromType == S.Context.LongDoubleTy &&
1767 ToType == S.Context.Float128Ty));
1768 if (Float128AndLongDouble &&
1769 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001770 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001771 return false;
1772 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001773 // Floating point conversions (C++ 4.8).
1774 SCS.Second = ICK_Floating_Conversion;
1775 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001777 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001778 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001779 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001780 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001781 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001783 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001784 SCS.Second = ICK_Block_Pointer_Conversion;
1785 } else if (AllowObjCWritebackConversion &&
1786 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1787 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001788 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1789 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001790 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001791 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001792 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001793 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001794 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001795 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001796 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001797 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001798 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001799 SCS.Second = SecondICK;
1800 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001801 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001802 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001803 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001804 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001805 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001806 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1807 InOverloadResolution,
1808 SCS, CStyle)) {
1809 SCS.Second = ICK_TransparentUnionConversion;
1810 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001811 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1812 CStyle)) {
1813 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001814 // appropriately.
1815 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001816 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001817 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001818 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001819 SCS.Second = ICK_Zero_Event_Conversion;
1820 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001821 } else if (ToType->isQueueT() &&
1822 From->isIntegerConstantExpr(S.getASTContext()) &&
1823 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1824 SCS.Second = ICK_Zero_Queue_Conversion;
1825 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 } else {
1827 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001828 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001830 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001832 // The third conversion can be a function pointer conversion or a
1833 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001834 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001835 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1836 // Function pointer conversions (removing 'noexcept') including removal of
1837 // 'noreturn' (Clang extension).
1838 SCS.Third = ICK_Function_Conversion;
1839 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1840 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001841 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001842 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001843 FromType = ToType;
1844 } else {
1845 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001846 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001847 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001848
1849 // C++ [over.best.ics]p6:
1850 // [...] Any difference in top-level cv-qualification is
1851 // subsumed by the initialization itself and does not constitute
1852 // a conversion. [...]
1853 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1854 QualType CanonTo = S.Context.getCanonicalType(ToType);
1855 if (CanonFrom.getLocalUnqualifiedType()
1856 == CanonTo.getLocalUnqualifiedType() &&
1857 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1858 FromType = ToType;
1859 CanonFrom = CanonTo;
1860 }
1861
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001862 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001863
George Burgess IV45461812015-10-11 20:13:20 +00001864 if (CanonFrom == CanonTo)
1865 return true;
1866
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001867 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001868 // this is a bad conversion sequence, unless we're resolving an overload in C.
1869 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001870 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001871
George Burgess IV45461812015-10-11 20:13:20 +00001872 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001873 Sema::AssignConvertType Conv =
1874 S.CheckSingleAssignmentConstraints(ToType, ER,
1875 /*Diagnose=*/false,
1876 /*DiagnoseCFAudited=*/false,
1877 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001878 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001879 switch (Conv) {
1880 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001881 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001882 break;
1883 // For our purposes, discarding qualifiers is just as bad as using an
1884 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1885 // qualifiers, as well.
1886 case Sema::CompatiblePointerDiscardsQualifiers:
1887 case Sema::IncompatiblePointer:
1888 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001889 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001890 break;
1891 default:
George Burgess IV45461812015-10-11 20:13:20 +00001892 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001893 }
George Burgess IV45461812015-10-11 20:13:20 +00001894
George Burgess IV6098fd12016-09-03 00:28:25 +00001895 // First can only be an lvalue conversion, so we pretend that this was the
1896 // second conversion. First should already be valid from earlier in the
1897 // function.
1898 SCS.Second = SecondConv;
1899 SCS.setToType(1, ToType);
1900
1901 // Third is Identity, because Second should rank us worse than any other
1902 // conversion. This could also be ICK_Qualification, but it's simpler to just
1903 // lump everything in with the second conversion, and we don't gain anything
1904 // from making this ICK_Qualification.
1905 SCS.Third = ICK_Identity;
1906 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001907 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001908}
George Burgess IV2099b542016-09-02 22:59:57 +00001909
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001910static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001911IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001912 QualType &ToType,
1913 bool InOverloadResolution,
1914 StandardConversionSequence &SCS,
1915 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001916
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001917 const RecordType *UT = ToType->getAsUnionType();
1918 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1919 return false;
1920 // The field to initialize within the transparent union.
1921 RecordDecl *UD = UT->getDecl();
1922 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001923 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001924 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1925 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001926 ToType = it->getType();
1927 return true;
1928 }
1929 }
1930 return false;
1931}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001932
1933/// IsIntegralPromotion - Determines whether the conversion from the
1934/// expression From (whose potentially-adjusted type is FromType) to
1935/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1936/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001937bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001938 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001939 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001940 if (!To) {
1941 return false;
1942 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001943
1944 // An rvalue of type char, signed char, unsigned char, short int, or
1945 // unsigned short int can be converted to an rvalue of type int if
1946 // int can represent all the values of the source type; otherwise,
1947 // the source rvalue can be converted to an rvalue of type unsigned
1948 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001949 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1950 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001951 if (// We can promote any signed, promotable integer type to an int
1952 (FromType->isSignedIntegerType() ||
1953 // We can promote any unsigned integer type whose size is
1954 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001955 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001956 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001957 }
1958
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001959 return To->getKind() == BuiltinType::UInt;
1960 }
1961
Richard Smithb9c5a602012-09-13 21:18:54 +00001962 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963 // A prvalue of an unscoped enumeration type whose underlying type is not
1964 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1965 // following types that can represent all the values of the enumeration
1966 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1967 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001968 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001970 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 // with lowest integer conversion rank (4.13) greater than the rank of long
1972 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001973 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001974 // C++11 [conv.prom]p4:
1975 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1976 // can be converted to a prvalue of its underlying type. Moreover, if
1977 // integral promotion can be applied to its underlying type, a prvalue of an
1978 // unscoped enumeration type whose underlying type is fixed can also be
1979 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001980 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1981 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1982 // provided for a scoped enumeration.
1983 if (FromEnumType->getDecl()->isScoped())
1984 return false;
1985
Richard Smithb9c5a602012-09-13 21:18:54 +00001986 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001987 // even if that's not the promoted type. Note that the check for promoting
1988 // the underlying type is based on the type alone, and does not consider
1989 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001990 if (FromEnumType->getDecl()->isFixed()) {
1991 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1992 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001993 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001994 }
1995
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001996 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001998 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001999 return Context.hasSameUnqualifiedType(
2000 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00002001 }
John McCall56774992009-12-09 09:09:27 +00002002
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002003 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2005 // to an rvalue a prvalue of the first of the following types that can
2006 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002007 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002009 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002010 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002011 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002013 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002014 // Determine whether the type we're converting from is signed or
2015 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002016 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002019 // The types we'll try to promote to, in the appropriate
2020 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002021 QualType PromoteTypes[6] = {
2022 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002023 Context.LongTy, Context.UnsignedLongTy ,
2024 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002025 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002026 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002027 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2028 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002029 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002030 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2031 // We found the type that we can promote to. If this is the
2032 // type we wanted, we have a promotion. Otherwise, no
2033 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002034 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002035 }
2036 }
2037 }
2038
2039 // An rvalue for an integral bit-field (9.6) can be converted to an
2040 // rvalue of type int if int can represent all the values of the
2041 // bit-field; otherwise, it can be converted to unsigned int if
2042 // unsigned int can represent all the values of the bit-field. If
2043 // the bit-field is larger yet, no integral promotion applies to
2044 // it. If the bit-field has an enumerated type, it is treated as any
2045 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002046 // FIXME: We should delay checking of bit-fields until we actually perform the
2047 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002048 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002049 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002050 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002051 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002052 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002053 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002054 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002056 // Are we promoting to an int from a bitfield that fits in an int?
2057 if (BitWidth < ToSize ||
2058 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2059 return To->getKind() == BuiltinType::Int;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002062 // Are we promoting to an unsigned int from an unsigned bitfield
2063 // that fits into an unsigned int?
2064 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2065 return To->getKind() == BuiltinType::UInt;
2066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002068 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002069 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002070 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073 // An rvalue of type bool can be converted to an rvalue of type int,
2074 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002075 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002076 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002077 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002078
2079 return false;
2080}
2081
2082/// IsFloatingPointPromotion - Determines whether the conversion from
2083/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2084/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002085bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002086 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2087 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002088 /// An rvalue of type float can be converted to an rvalue of type
2089 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002090 if (FromBuiltin->getKind() == BuiltinType::Float &&
2091 ToBuiltin->getKind() == BuiltinType::Double)
2092 return true;
2093
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002094 // C99 6.3.1.5p1:
2095 // When a float is promoted to double or long double, or a
2096 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002097 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002098 (FromBuiltin->getKind() == BuiltinType::Float ||
2099 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002100 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2101 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002102 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002103
2104 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002105 if (!getLangOpts().NativeHalfType &&
2106 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002107 ToBuiltin->getKind() == BuiltinType::Float)
2108 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002109 }
2110
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002111 return false;
2112}
2113
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002114/// \brief Determine if a conversion is a complex promotion.
2115///
2116/// A complex promotion is defined as a complex -> complex conversion
2117/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002118/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002119bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002120 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002121 if (!FromComplex)
2122 return false;
2123
John McCall9dd450b2009-09-21 23:43:11 +00002124 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002125 if (!ToComplex)
2126 return false;
2127
2128 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002129 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002131 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002132}
2133
Douglas Gregor237f96c2008-11-26 23:31:11 +00002134/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2135/// the pointer type FromPtr to a pointer to type ToPointee, with the
2136/// same type qualifiers as FromPtr has on its pointee type. ToType,
2137/// if non-empty, will be a pointer to ToType that may or may not have
2138/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002139///
Mike Stump11289f42009-09-09 15:08:12 +00002140static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002141BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002142 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002143 ASTContext &Context,
2144 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002145 assert((FromPtr->getTypeClass() == Type::Pointer ||
2146 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2147 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
John McCall31168b02011-06-15 23:02:42 +00002149 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002150 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002151 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152
2153 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002154 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002155 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002156 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002157
John McCall31168b02011-06-15 23:02:42 +00002158 if (StripObjCLifetime)
2159 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002160
Mike Stump11289f42009-09-09 15:08:12 +00002161 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002162 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002163 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002164 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002165 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002166
2167 // Build a pointer to ToPointee. It has the right qualifiers
2168 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002169 if (isa<ObjCObjectPointerType>(ToType))
2170 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002171 return Context.getPointerType(ToPointee);
2172 }
2173
2174 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002175 QualType QualifiedCanonToPointee
2176 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002178 if (isa<ObjCObjectPointerType>(ToType))
2179 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2180 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002181}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
Mike Stump11289f42009-09-09 15:08:12 +00002183static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002184 bool InOverloadResolution,
2185 ASTContext &Context) {
2186 // Handle value-dependent integral null pointer constants correctly.
2187 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2188 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002189 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002190 return !InOverloadResolution;
2191
Douglas Gregor56751b52009-09-25 04:25:58 +00002192 return Expr->isNullPointerConstant(Context,
2193 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2194 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002195}
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002197/// IsPointerConversion - Determines whether the conversion of the
2198/// expression From, which has the (possibly adjusted) type FromType,
2199/// can be converted to the type ToType via a pointer conversion (C++
2200/// 4.10). If so, returns true and places the converted type (that
2201/// might differ from ToType in its cv-qualifiers at some level) into
2202/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002203///
Douglas Gregora29dc052008-11-27 01:19:21 +00002204/// This routine also supports conversions to and from block pointers
2205/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2206/// pointers to interfaces. FIXME: Once we've determined the
2207/// appropriate overloading rules for Objective-C, we may want to
2208/// split the Objective-C checks into a different routine; however,
2209/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002210/// conversions, so for now they live here. IncompatibleObjC will be
2211/// set if the conversion is an allowed Objective-C conversion that
2212/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002213bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002214 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002215 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002216 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002217 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002218 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2219 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002220 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002221
Mike Stump11289f42009-09-09 15:08:12 +00002222 // Conversion from a null pointer constant to any Objective-C pointer type.
2223 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002224 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002225 ConvertedType = ToType;
2226 return true;
2227 }
2228
Douglas Gregor231d1c62008-11-27 00:15:41 +00002229 // Blocks: Block pointers can be converted to void*.
2230 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002231 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002232 ConvertedType = ToType;
2233 return true;
2234 }
2235 // Blocks: A null pointer constant can be converted to a block
2236 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002237 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002238 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002239 ConvertedType = ToType;
2240 return true;
2241 }
2242
Sebastian Redl576fd422009-05-10 18:38:11 +00002243 // If the left-hand-side is nullptr_t, the right side can be a null
2244 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002245 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002246 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002247 ConvertedType = ToType;
2248 return true;
2249 }
2250
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002251 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252 if (!ToTypePtr)
2253 return false;
2254
2255 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002256 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002257 ConvertedType = ToType;
2258 return true;
2259 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002260
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002262 // , including objective-c pointers.
2263 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002264 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002265 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002266 ConvertedType = BuildSimilarlyQualifiedPointerType(
2267 FromType->getAs<ObjCObjectPointerType>(),
2268 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002269 ToType, Context);
2270 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002271 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002272 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002273 if (!FromTypePtr)
2274 return false;
2275
2276 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002278 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002279 // pointer conversion, so don't do all of the work below.
2280 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2281 return false;
2282
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283 // An rvalue of type "pointer to cv T," where T is an object type,
2284 // can be converted to an rvalue of type "pointer to cv void" (C++
2285 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002286 if (FromPointeeType->isIncompleteOrObjectType() &&
2287 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002289 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002290 ToType, Context,
2291 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292 return true;
2293 }
2294
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002295 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002296 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002297 ToPointeeType->isVoidType()) {
2298 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2299 ToPointeeType,
2300 ToType, Context);
2301 return true;
2302 }
2303
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002304 // When we're overloading in C, we allow a special kind of pointer
2305 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002307 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002308 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002309 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002310 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002311 return true;
2312 }
2313
Douglas Gregor5c407d92008-10-23 00:40:37 +00002314 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002315 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002316 // An rvalue of type "pointer to cv D," where D is a class type,
2317 // can be converted to an rvalue of type "pointer to cv B," where
2318 // B is a base class (clause 10) of D. If B is an inaccessible
2319 // (clause 11) or ambiguous (10.2) base class of D, a program that
2320 // necessitates this conversion is ill-formed. The result of the
2321 // conversion is a pointer to the base class sub-object of the
2322 // derived class object. The null pointer value is converted to
2323 // the null pointer value of the destination type.
2324 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002325 // Note that we do not check for ambiguity or inaccessibility
2326 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002327 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002328 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002329 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002330 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002331 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002332 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002333 ToType, Context);
2334 return true;
2335 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002336
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002337 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2338 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2339 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340 ToPointeeType,
2341 ToType, Context);
2342 return true;
2343 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002344
Douglas Gregora119f102008-12-19 19:13:09 +00002345 return false;
2346}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002347
Douglas Gregoraec25842011-04-26 23:16:46 +00002348/// \brief Adopt the given qualifiers for the given type.
2349static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2350 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002351
Douglas Gregoraec25842011-04-26 23:16:46 +00002352 // Check whether qualifiers already match.
2353 if (TQs == Qs)
2354 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002355
Douglas Gregoraec25842011-04-26 23:16:46 +00002356 if (Qs.compatiblyIncludes(TQs))
2357 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002358
Douglas Gregoraec25842011-04-26 23:16:46 +00002359 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2360}
Douglas Gregora119f102008-12-19 19:13:09 +00002361
2362/// isObjCPointerConversion - Determines whether this is an
2363/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2364/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002365bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002366 QualType& ConvertedType,
2367 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002369 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002370
Douglas Gregoraec25842011-04-26 23:16:46 +00002371 // The set of qualifiers on the type we're converting from.
2372 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002373
Steve Naroff7cae42b2009-07-10 23:34:53 +00002374 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002375 const ObjCObjectPointerType* ToObjCPtr =
2376 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002377 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002378 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002379
Steve Naroff7cae42b2009-07-10 23:34:53 +00002380 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002381 // If the pointee types are the same (ignoring qualifications),
2382 // then this is not a pointer conversion.
2383 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2384 FromObjCPtr->getPointeeType()))
2385 return false;
2386
Douglas Gregorab209d82015-07-07 03:58:42 +00002387 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002388 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002389 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2390 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002391 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002392 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2393 FromObjCPtr->getPointeeType()))
2394 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002395 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002396 ToObjCPtr->getPointeeType(),
2397 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002398 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002399 return true;
2400 }
2401
2402 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2403 // Okay: this is some kind of implicit downcast of Objective-C
2404 // interfaces, which is permitted. However, we're going to
2405 // complain about it.
2406 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002408 ToObjCPtr->getPointeeType(),
2409 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002410 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002411 return true;
2412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002414 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002415 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002416 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002417 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002418 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002419 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002420 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002421 // to a block pointer type.
2422 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002424 return true;
2425 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002426 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002429 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002430 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002431 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002432 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002433 return true;
2434 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002435 else
Douglas Gregora119f102008-12-19 19:13:09 +00002436 return false;
2437
Douglas Gregor033f56d2008-12-23 00:53:59 +00002438 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002439 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002440 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002441 else if (const BlockPointerType *FromBlockPtr =
2442 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002443 FromPointeeType = FromBlockPtr->getPointeeType();
2444 else
Douglas Gregora119f102008-12-19 19:13:09 +00002445 return false;
2446
Douglas Gregora119f102008-12-19 19:13:09 +00002447 // If we have pointers to pointers, recursively check whether this
2448 // is an Objective-C conversion.
2449 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2450 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2451 IncompatibleObjC)) {
2452 // We always complain about this conversion.
2453 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002454 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002455 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002456 return true;
2457 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002458 // Allow conversion of pointee being objective-c pointer to another one;
2459 // as in I* to id.
2460 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2461 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2462 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2463 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002464
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002465 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002466 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002467 return true;
2468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469
Douglas Gregor033f56d2008-12-23 00:53:59 +00002470 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002471 // differences in the argument and result types are in Objective-C
2472 // pointer conversions. If so, we permit the conversion (but
2473 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002474 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002475 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002476 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002477 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002478 if (FromFunctionType && ToFunctionType) {
2479 // If the function types are exactly the same, this isn't an
2480 // Objective-C pointer conversion.
2481 if (Context.getCanonicalType(FromPointeeType)
2482 == Context.getCanonicalType(ToPointeeType))
2483 return false;
2484
2485 // Perform the quick checks that will tell us whether these
2486 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002487 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002488 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2489 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2490 return false;
2491
2492 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002493 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2494 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002495 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002496 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2497 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2501 } else {
2502 // Function types are too different. Abort.
2503 return false;
2504 }
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregora119f102008-12-19 19:13:09 +00002506 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002507 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002508 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002509 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2510 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002511 if (Context.getCanonicalType(FromArgType)
2512 == Context.getCanonicalType(ToArgType)) {
2513 // Okay, the types match exactly. Nothing to do.
2514 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2515 ConvertedType, IncompatibleObjC)) {
2516 // Okay, we have an Objective-C pointer conversion.
2517 HasObjCConversion = true;
2518 } else {
2519 // Argument types are too different. Abort.
2520 return false;
2521 }
2522 }
2523
2524 if (HasObjCConversion) {
2525 // We had an Objective-C conversion. Allow this pointer
2526 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002527 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002528 IncompatibleObjC = true;
2529 return true;
2530 }
2531 }
2532
Sebastian Redl72b597d2009-01-25 19:43:20 +00002533 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002535
John McCall31168b02011-06-15 23:02:42 +00002536/// \brief Determine whether this is an Objective-C writeback conversion,
2537/// used for parameter passing when performing automatic reference counting.
2538///
2539/// \param FromType The type we're converting form.
2540///
2541/// \param ToType The type we're converting to.
2542///
2543/// \param ConvertedType The type that will be produced after applying
2544/// this conversion.
2545bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2546 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002547 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002548 Context.hasSameUnqualifiedType(FromType, ToType))
2549 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002550
John McCall31168b02011-06-15 23:02:42 +00002551 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2552 QualType ToPointee;
2553 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2554 ToPointee = ToPointer->getPointeeType();
2555 else
2556 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002557
John McCall31168b02011-06-15 23:02:42 +00002558 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002559 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002560 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002561 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002562 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002563
John McCall31168b02011-06-15 23:02:42 +00002564 // Argument must be a pointer to __strong to __weak.
2565 QualType FromPointee;
2566 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2567 FromPointee = FromPointer->getPointeeType();
2568 else
2569 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002570
John McCall31168b02011-06-15 23:02:42 +00002571 Qualifiers FromQuals = FromPointee.getQualifiers();
2572 if (!FromPointee->isObjCLifetimeType() ||
2573 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2574 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2575 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002576
John McCall31168b02011-06-15 23:02:42 +00002577 // Make sure that we have compatible qualifiers.
2578 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2579 if (!ToQuals.compatiblyIncludes(FromQuals))
2580 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002581
John McCall31168b02011-06-15 23:02:42 +00002582 // Remove qualifiers from the pointee type we're converting from; they
2583 // aren't used in the compatibility check belong, and we'll be adding back
2584 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2585 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002586
John McCall31168b02011-06-15 23:02:42 +00002587 // The unqualified form of the pointee types must be compatible.
2588 ToPointee = ToPointee.getUnqualifiedType();
2589 bool IncompatibleObjC;
2590 if (Context.typesAreCompatible(FromPointee, ToPointee))
2591 FromPointee = ToPointee;
2592 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2593 IncompatibleObjC))
2594 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002595
John McCall31168b02011-06-15 23:02:42 +00002596 /// \brief Construct the type we're converting to, which is a pointer to
2597 /// __autoreleasing pointee.
2598 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2599 ConvertedType = Context.getPointerType(FromPointee);
2600 return true;
2601}
2602
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002603bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2604 QualType& ConvertedType) {
2605 QualType ToPointeeType;
2606 if (const BlockPointerType *ToBlockPtr =
2607 ToType->getAs<BlockPointerType>())
2608 ToPointeeType = ToBlockPtr->getPointeeType();
2609 else
2610 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002611
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002612 QualType FromPointeeType;
2613 if (const BlockPointerType *FromBlockPtr =
2614 FromType->getAs<BlockPointerType>())
2615 FromPointeeType = FromBlockPtr->getPointeeType();
2616 else
2617 return false;
2618 // We have pointer to blocks, check whether the only
2619 // differences in the argument and result types are in Objective-C
2620 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002621
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002622 const FunctionProtoType *FromFunctionType
2623 = FromPointeeType->getAs<FunctionProtoType>();
2624 const FunctionProtoType *ToFunctionType
2625 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002626
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002627 if (!FromFunctionType || !ToFunctionType)
2628 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002629
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002630 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002631 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002632
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002633 // Perform the quick checks that will tell us whether these
2634 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002635 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002636 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2637 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002638
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002639 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2640 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2641 if (FromEInfo != ToEInfo)
2642 return false;
2643
2644 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002645 if (Context.hasSameType(FromFunctionType->getReturnType(),
2646 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002647 // Okay, the types match exactly. Nothing to do.
2648 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002649 QualType RHS = FromFunctionType->getReturnType();
2650 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002651 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002652 !RHS.hasQualifiers() && LHS.hasQualifiers())
2653 LHS = LHS.getUnqualifiedType();
2654
2655 if (Context.hasSameType(RHS,LHS)) {
2656 // OK exact match.
2657 } else if (isObjCPointerConversion(RHS, LHS,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2660 return false;
2661 // Okay, we have an Objective-C pointer conversion.
2662 }
2663 else
2664 return false;
2665 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002666
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002667 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002668 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002669 ArgIdx != NumArgs; ++ArgIdx) {
2670 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002671 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2672 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002673 if (Context.hasSameType(FromArgType, ToArgType)) {
2674 // Okay, the types match exactly. Nothing to do.
2675 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2676 ConvertedType, IncompatibleObjC)) {
2677 if (IncompatibleObjC)
2678 return false;
2679 // Okay, we have an Objective-C pointer conversion.
2680 } else
2681 // Argument types are too different. Abort.
2682 return false;
2683 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002684
2685 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2686 bool CanUseToFPT, CanUseFromFPT;
2687 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2688 CanUseToFPT, CanUseFromFPT,
2689 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002690 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002691
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002692 ConvertedType = ToType;
2693 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002694}
2695
Richard Trieucaff2472011-11-23 22:32:32 +00002696enum {
2697 ft_default,
2698 ft_different_class,
2699 ft_parameter_arity,
2700 ft_parameter_mismatch,
2701 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002702 ft_qualifer_mismatch,
2703 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002704};
2705
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002706/// Attempts to get the FunctionProtoType from a Type. Handles
2707/// MemberFunctionPointers properly.
2708static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2709 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2710 return FPT;
2711
2712 if (auto *MPT = FromType->getAs<MemberPointerType>())
2713 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2714
2715 return nullptr;
2716}
2717
Richard Trieucaff2472011-11-23 22:32:32 +00002718/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2719/// function types. Catches different number of parameter, mismatch in
2720/// parameter types, and different return types.
2721void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2722 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002723 // If either type is not valid, include no extra info.
2724 if (FromType.isNull() || ToType.isNull()) {
2725 PDiag << ft_default;
2726 return;
2727 }
2728
Richard Trieucaff2472011-11-23 22:32:32 +00002729 // Get the function type from the pointers.
2730 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2731 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2732 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002733 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002734 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2735 << QualType(FromMember->getClass(), 0);
2736 return;
2737 }
2738 FromType = FromMember->getPointeeType();
2739 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002740 }
2741
Richard Trieu96ed5b62011-12-13 23:19:45 +00002742 if (FromType->isPointerType())
2743 FromType = FromType->getPointeeType();
2744 if (ToType->isPointerType())
2745 ToType = ToType->getPointeeType();
2746
2747 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002748 FromType = FromType.getNonReferenceType();
2749 ToType = ToType.getNonReferenceType();
2750
Richard Trieucaff2472011-11-23 22:32:32 +00002751 // Don't print extra info for non-specialized template functions.
2752 if (FromType->isInstantiationDependentType() &&
2753 !FromType->getAs<TemplateSpecializationType>()) {
2754 PDiag << ft_default;
2755 return;
2756 }
2757
Richard Trieu96ed5b62011-12-13 23:19:45 +00002758 // No extra info for same types.
2759 if (Context.hasSameType(FromType, ToType)) {
2760 PDiag << ft_default;
2761 return;
2762 }
2763
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002764 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2765 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002766
2767 // Both types need to be function types.
2768 if (!FromFunction || !ToFunction) {
2769 PDiag << ft_default;
2770 return;
2771 }
2772
Alp Toker9cacbab2014-01-20 20:26:09 +00002773 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2774 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2775 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002776 return;
2777 }
2778
2779 // Handle different parameter types.
2780 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002781 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002782 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002783 << ToFunction->getParamType(ArgPos)
2784 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002785 return;
2786 }
2787
2788 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002789 if (!Context.hasSameType(FromFunction->getReturnType(),
2790 ToFunction->getReturnType())) {
2791 PDiag << ft_return_type << ToFunction->getReturnType()
2792 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002793 return;
2794 }
2795
2796 unsigned FromQuals = FromFunction->getTypeQuals(),
2797 ToQuals = ToFunction->getTypeQuals();
2798 if (FromQuals != ToQuals) {
2799 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2800 return;
2801 }
2802
Richard Smith3c4f8d22016-10-16 17:54:23 +00002803 // Handle exception specification differences on canonical type (in C++17
2804 // onwards).
2805 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2806 ->isNothrow(Context) !=
2807 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2808 ->isNothrow(Context)) {
2809 PDiag << ft_noexcept;
2810 return;
2811 }
2812
Richard Trieucaff2472011-11-23 22:32:32 +00002813 // Unable to find a difference, so add no extra info.
2814 PDiag << ft_default;
2815}
2816
Alp Toker9cacbab2014-01-20 20:26:09 +00002817/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002818/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002819/// they have same number of arguments. If the parameters are different,
2820/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002821bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2822 const FunctionProtoType *NewType,
2823 unsigned *ArgPos) {
2824 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2825 N = NewType->param_type_begin(),
2826 E = OldType->param_type_end();
2827 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002828 if (!Context.hasSameType(O->getUnqualifiedType(),
2829 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002830 if (ArgPos)
2831 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002832 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002833 }
2834 }
2835 return true;
2836}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002837
Douglas Gregor39c16d42008-10-24 04:54:22 +00002838/// CheckPointerConversion - Check the pointer conversion from the
2839/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002840/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002841/// conversions for which IsPointerConversion has already returned
2842/// true. It returns true and produces a diagnostic if there was an
2843/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002844bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002845 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002846 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002847 bool IgnoreBaseAccess,
2848 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002849 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002850 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002851
John McCall8cb679e2010-11-15 09:13:47 +00002852 Kind = CK_BitCast;
2853
George Burgess IV60bc9722016-01-13 23:36:34 +00002854 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002855 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002856 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002857 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2858 DiagRuntimeBehavior(From->getExprLoc(), From,
2859 PDiag(diag::warn_impcast_bool_to_null_pointer)
2860 << ToType << From->getSourceRange());
2861 else if (!isUnevaluatedContext())
2862 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2863 << ToType << From->getSourceRange();
2864 }
John McCall9320b872011-09-09 05:25:32 +00002865 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2866 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002867 QualType FromPointeeType = FromPtrType->getPointeeType(),
2868 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002869
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002870 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2871 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002872 // We must have a derived-to-base conversion. Check an
2873 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002874 unsigned InaccessibleID = 0;
2875 unsigned AmbigiousID = 0;
2876 if (Diagnose) {
2877 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2878 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2879 }
2880 if (CheckDerivedToBaseConversion(
2881 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2882 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2883 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002884 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002886 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002887 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002888 }
David Majnemer6bf02822015-10-31 08:42:14 +00002889
George Burgess IV60bc9722016-01-13 23:36:34 +00002890 if (Diagnose && !IsCStyleOrFunctionalCast &&
2891 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002892 assert(getLangOpts().MSVCCompat &&
2893 "this should only be possible with MSVCCompat!");
2894 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2895 << From->getSourceRange();
2896 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002897 }
John McCall9320b872011-09-09 05:25:32 +00002898 } else if (const ObjCObjectPointerType *ToPtrType =
2899 ToType->getAs<ObjCObjectPointerType>()) {
2900 if (const ObjCObjectPointerType *FromPtrType =
2901 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002902 // Objective-C++ conversions are always okay.
2903 // FIXME: We should have a different class of conversions for the
2904 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002905 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002906 return false;
John McCall9320b872011-09-09 05:25:32 +00002907 } else if (FromType->isBlockPointerType()) {
2908 Kind = CK_BlockPointerToObjCPointerCast;
2909 } else {
2910 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002911 }
John McCall9320b872011-09-09 05:25:32 +00002912 } else if (ToType->isBlockPointerType()) {
2913 if (!FromType->isBlockPointerType())
2914 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002915 }
John McCall8cb679e2010-11-15 09:13:47 +00002916
2917 // We shouldn't fall into this case unless it's valid for other
2918 // reasons.
2919 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2920 Kind = CK_NullToPointer;
2921
Douglas Gregor39c16d42008-10-24 04:54:22 +00002922 return false;
2923}
2924
Sebastian Redl72b597d2009-01-25 19:43:20 +00002925/// IsMemberPointerConversion - Determines whether the conversion of the
2926/// expression From, which has the (possibly adjusted) type FromType, can be
2927/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2928/// If so, returns true and places the converted type (that might differ from
2929/// ToType in its cv-qualifiers at some level) into ConvertedType.
2930bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002931 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002932 bool InOverloadResolution,
2933 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002934 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002935 if (!ToTypePtr)
2936 return false;
2937
2938 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002939 if (From->isNullPointerConstant(Context,
2940 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2941 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002942 ConvertedType = ToType;
2943 return true;
2944 }
2945
2946 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002947 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002948 if (!FromTypePtr)
2949 return false;
2950
2951 // A pointer to member of B can be converted to a pointer to member of D,
2952 // where D is derived from B (C++ 4.11p2).
2953 QualType FromClass(FromTypePtr->getClass(), 0);
2954 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002955
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002956 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002957 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002958 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2959 ToClass.getTypePtr());
2960 return true;
2961 }
2962
2963 return false;
2964}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
Sebastian Redl72b597d2009-01-25 19:43:20 +00002966/// CheckMemberPointerConversion - Check the member pointer conversion from the
2967/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002968/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002969/// for which IsMemberPointerConversion has already returned true. It returns
2970/// true and produces a diagnostic if there was an error, or returns false
2971/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002972bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002973 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002974 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002975 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002976 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002977 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002978 if (!FromPtrType) {
2979 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002981 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002982 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002983 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002984 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002985 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002986
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002987 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002988 assert(ToPtrType && "No member pointer cast has a target type "
2989 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002990
Sebastian Redled8f2002009-01-28 18:33:18 +00002991 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2992 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002993
Sebastian Redled8f2002009-01-28 18:33:18 +00002994 // FIXME: What about dependent types?
2995 assert(FromClass->isRecordType() && "Pointer into non-class.");
2996 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002997
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002998 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002999 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00003000 bool DerivationOkay =
3001 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003002 assert(DerivationOkay &&
3003 "Should not have been called if derivation isn't OK.");
3004 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003005
Sebastian Redled8f2002009-01-28 18:33:18 +00003006 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3007 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003008 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3009 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3010 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3011 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003012 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003013
Douglas Gregor89ee6822009-02-28 01:32:25 +00003014 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003015 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3016 << FromClass << ToClass << QualType(VBase, 0)
3017 << From->getSourceRange();
3018 return true;
3019 }
3020
John McCall5b0829a2010-02-10 09:31:12 +00003021 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003022 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3023 Paths.front(),
3024 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003025
Anders Carlssond7923c62009-08-22 23:33:40 +00003026 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003027 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003028 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003029 return false;
3030}
3031
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003032/// Determine whether the lifetime conversion between the two given
3033/// qualifiers sets is nontrivial.
3034static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3035 Qualifiers ToQuals) {
3036 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003037 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003038 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3039 return false;
3040
3041 return true;
3042}
3043
Douglas Gregor9a657932008-10-21 23:43:52 +00003044/// IsQualificationConversion - Determines whether the conversion from
3045/// an rvalue of type FromType to ToType is a qualification conversion
3046/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003047///
3048/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3049/// when the qualification conversion involves a change in the Objective-C
3050/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003051bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003053 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003054 FromType = Context.getCanonicalType(FromType);
3055 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003056 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003057
Douglas Gregor9a657932008-10-21 23:43:52 +00003058 // If FromType and ToType are the same type, this is not a
3059 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003060 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003061 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003062
Douglas Gregor9a657932008-10-21 23:43:52 +00003063 // (C++ 4.4p4):
3064 // A conversion can add cv-qualifiers at levels other than the first
3065 // in multi-level pointers, subject to the following rules: [...]
3066 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003067 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003068 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003069 // Within each iteration of the loop, we check the qualifiers to
3070 // determine if this still looks like a qualification
3071 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003072 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003073 // until there are no more pointers or pointers-to-members left to
3074 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003075 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003076
Douglas Gregor90609aa2011-04-25 18:40:17 +00003077 Qualifiers FromQuals = FromType.getQualifiers();
3078 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003079
3080 // Ignore __unaligned qualifier if this type is void.
3081 if (ToType.getUnqualifiedType()->isVoidType())
3082 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003083
John McCall31168b02011-06-15 23:02:42 +00003084 // Objective-C ARC:
3085 // Check Objective-C lifetime conversions.
3086 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3087 UnwrappedAnyPointer) {
3088 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003089 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3090 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003091 FromQuals.removeObjCLifetime();
3092 ToQuals.removeObjCLifetime();
3093 } else {
3094 // Qualification conversions cannot cast between different
3095 // Objective-C lifetime qualifiers.
3096 return false;
3097 }
3098 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003099
Douglas Gregorf30053d2011-05-08 06:09:53 +00003100 // Allow addition/removal of GC attributes but not changing GC attributes.
3101 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3102 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3103 FromQuals.removeObjCGCAttr();
3104 ToQuals.removeObjCGCAttr();
3105 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003106
Douglas Gregor9a657932008-10-21 23:43:52 +00003107 // -- for every j > 0, if const is in cv 1,j then const is in cv
3108 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003109 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003110 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003111
Douglas Gregor9a657932008-10-21 23:43:52 +00003112 // -- if the cv 1,j and cv 2,j are different, then const is in
3113 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003114 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003115 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003116 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003117
Douglas Gregor9a657932008-10-21 23:43:52 +00003118 // Keep track of whether all prior cv-qualifiers in the "to" type
3119 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003120 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003121 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003122 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003123
3124 // We are left with FromType and ToType being the pointee types
3125 // after unwrapping the original FromType and ToType the same number
3126 // of types. If we unwrapped any pointers, and if FromType and
3127 // ToType have the same unqualified type (since we checked
3128 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003129 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003130}
3131
Douglas Gregorc79862f2012-04-12 17:51:55 +00003132/// \brief - Determine whether this is a conversion from a scalar type to an
3133/// atomic type.
3134///
3135/// If successful, updates \c SCS's second and third steps in the conversion
3136/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003137static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3138 bool InOverloadResolution,
3139 StandardConversionSequence &SCS,
3140 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003141 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3142 if (!ToAtomic)
3143 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003144
Douglas Gregorc79862f2012-04-12 17:51:55 +00003145 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003146 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003147 InOverloadResolution, InnerSCS,
3148 CStyle, /*AllowObjCWritebackConversion=*/false))
3149 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003150
Douglas Gregorc79862f2012-04-12 17:51:55 +00003151 SCS.Second = InnerSCS.Second;
3152 SCS.setToType(1, InnerSCS.getToType(1));
3153 SCS.Third = InnerSCS.Third;
3154 SCS.QualificationIncludesObjCLifetime
3155 = InnerSCS.QualificationIncludesObjCLifetime;
3156 SCS.setToType(2, InnerSCS.getToType(2));
3157 return true;
3158}
3159
Sebastian Redle5417162012-03-27 18:33:03 +00003160static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3161 CXXConstructorDecl *Constructor,
3162 QualType Type) {
3163 const FunctionProtoType *CtorType =
3164 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003165 if (CtorType->getNumParams() > 0) {
3166 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003167 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3168 return true;
3169 }
3170 return false;
3171}
3172
Sebastian Redl82ace982012-02-11 23:51:08 +00003173static OverloadingResult
3174IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3175 CXXRecordDecl *To,
3176 UserDefinedConversionSequence &User,
3177 OverloadCandidateSet &CandidateSet,
3178 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003179 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003180 for (auto *D : S.LookupConstructors(To)) {
3181 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003182 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003183 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003184
Richard Smithc2bebe92016-05-11 20:37:46 +00003185 bool Usable = !Info.Constructor->isInvalidDecl() &&
3186 S.isInitListConstructor(Info.Constructor) &&
3187 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003188 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003189 // If the first argument is (a reference to) the target type,
3190 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003191 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3192 S.Context, Info.Constructor, ToType);
3193 if (Info.ConstructorTmpl)
3194 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3195 /*ExplicitArgs*/ nullptr, From,
3196 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003197 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003198 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3199 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003200 }
3201 }
3202
3203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3204
3205 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003206 switch (auto Result =
3207 CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003208 Best)) {
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003209 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003210 case OR_Success: {
3211 // Record the standard conversion we used and the conversion function.
3212 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003213 QualType ThisType = Constructor->getThisType(S.Context);
3214 // Initializer lists don't have conversions as such.
3215 User.Before.setAsIdentityConversion();
3216 User.HadMultipleCandidates = HadMultipleCandidates;
3217 User.ConversionFunction = Constructor;
3218 User.FoundConversionFunction = Best->FoundDecl;
3219 User.After.setAsIdentityConversion();
3220 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3221 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003222 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003223 }
3224
3225 case OR_No_Viable_Function:
3226 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003227 case OR_Ambiguous:
3228 return OR_Ambiguous;
3229 }
3230
3231 llvm_unreachable("Invalid OverloadResult!");
3232}
3233
Douglas Gregor576e98c2009-01-30 23:27:23 +00003234/// Determines whether there is a user-defined conversion sequence
3235/// (C++ [over.ics.user]) that converts expression From to the type
3236/// ToType. If such a conversion exists, User will contain the
3237/// user-defined conversion sequence that performs such a conversion
3238/// and this routine will return true. Otherwise, this routine returns
3239/// false and User is unspecified.
3240///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003241/// \param AllowExplicit true if the conversion should consider C++0x
3242/// "explicit" conversion functions as well as non-explicit conversion
3243/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003244///
3245/// \param AllowObjCConversionOnExplicit true if the conversion should
3246/// allow an extra Objective-C pointer conversion on uses of explicit
3247/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003248static OverloadingResult
3249IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003250 UserDefinedConversionSequence &User,
3251 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003252 bool AllowExplicit,
3253 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003254 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Richard Smith67ef14f2017-09-26 18:37:55 +00003255 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003256
Douglas Gregor5ab11652010-04-17 22:01:05 +00003257 // Whether we will only visit constructors.
3258 bool ConstructorsOnly = false;
3259
3260 // If the type we are conversion to is a class type, enumerate its
3261 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003262 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003263 // C++ [over.match.ctor]p1:
3264 // When objects of class type are direct-initialized (8.5), or
3265 // copy-initialized from an expression of the same or a
3266 // derived class type (8.5), overload resolution selects the
3267 // constructor. [...] For copy-initialization, the candidate
3268 // functions are all the converting constructors (12.3.1) of
3269 // that class. The argument list is the expression-list within
3270 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003271 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003272 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003273 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003274 ConstructorsOnly = true;
3275
Richard Smithdb0ac552015-12-18 22:40:25 +00003276 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003277 // We're not going to find any constructors.
3278 } else if (CXXRecordDecl *ToRecordDecl
3279 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003280
3281 Expr **Args = &From;
3282 unsigned NumArgs = 1;
3283 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003284 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003285 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003286 OverloadingResult Result = IsInitializerListConstructorConversion(
3287 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3288 if (Result != OR_No_Viable_Function)
3289 return Result;
3290 // Never mind.
Richard Smith67ef14f2017-09-26 18:37:55 +00003291 CandidateSet.clear(
3292 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Sebastian Redl82ace982012-02-11 23:51:08 +00003293
3294 // If we're list-initializing, we pass the individual elements as
3295 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003296 Args = InitList->getInits();
3297 NumArgs = InitList->getNumInits();
3298 ListInitializing = true;
3299 }
3300
Richard Smithc2bebe92016-05-11 20:37:46 +00003301 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3302 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003303 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003304 continue;
John McCalla0296f72010-03-19 07:35:19 +00003305
Richard Smithc2bebe92016-05-11 20:37:46 +00003306 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003307 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003308 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003309 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003310 Usable = Usable &&
3311 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003312 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003313 bool SuppressUserConversions = !ConstructorsOnly;
3314 if (SuppressUserConversions && ListInitializing) {
3315 SuppressUserConversions = false;
3316 if (NumArgs == 1) {
3317 // If the first argument is (a reference to) the target type,
3318 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003319 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003320 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003321 }
3322 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003323 if (Info.ConstructorTmpl)
3324 S.AddTemplateOverloadCandidate(
3325 Info.ConstructorTmpl, Info.FoundDecl,
3326 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3327 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003328 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003329 // Allow one user-defined conversion when user specifies a
3330 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003331 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003332 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003333 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003334 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003335 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003336 }
3337 }
3338
Douglas Gregor5ab11652010-04-17 22:01:05 +00003339 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003340 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003341 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003342 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003343 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003344 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003345 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003346 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3347 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003348 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3349 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003350 DeclAccessPair FoundDecl = I.getPair();
3351 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003352 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3353 if (isa<UsingShadowDecl>(D))
3354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3355
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003356 CXXConversionDecl *Conv;
3357 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003358 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3359 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003360 else
John McCallda4458e2010-03-31 01:36:47 +00003361 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003362
3363 if (AllowExplicit || !Conv->isExplicit()) {
3364 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003365 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3366 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003367 CandidateSet,
3368 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003369 else
John McCall5c32be02010-08-24 20:38:10 +00003370 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003371 From, ToType, CandidateSet,
3372 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003373 }
3374 }
3375 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003376 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003377
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3379
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003380 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003381 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003382 Best)) {
John McCall5c32be02010-08-24 20:38:10 +00003383 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003384 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003385 // Record the standard conversion we used and the conversion function.
3386 if (CXXConstructorDecl *Constructor
3387 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3388 // C++ [over.ics.user]p1:
3389 // If the user-defined conversion is specified by a
3390 // constructor (12.3.1), the initial standard conversion
3391 // sequence converts the source type to the type required by
3392 // the argument of the constructor.
3393 //
3394 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003395 if (isa<InitListExpr>(From)) {
3396 // Initializer lists don't have conversions as such.
3397 User.Before.setAsIdentityConversion();
3398 } else {
3399 if (Best->Conversions[0].isEllipsis())
3400 User.EllipsisConversion = true;
3401 else {
3402 User.Before = Best->Conversions[0].Standard;
3403 User.EllipsisConversion = false;
3404 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003405 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003406 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003407 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003408 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003409 User.After.setAsIdentityConversion();
3410 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3411 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003412 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003413 }
3414 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003415 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3416 // C++ [over.ics.user]p1:
3417 //
3418 // [...] If the user-defined conversion is specified by a
3419 // conversion function (12.3.2), the initial standard
3420 // conversion sequence converts the source type to the
3421 // implicit object parameter of the conversion function.
3422 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003423 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003424 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003425 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003426 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003427
John McCall5c32be02010-08-24 20:38:10 +00003428 // C++ [over.ics.user]p2:
3429 // The second standard conversion sequence converts the
3430 // result of the user-defined conversion to the target type
3431 // for the sequence. Since an implicit conversion sequence
3432 // is an initialization, the special rules for
3433 // initialization by user-defined conversion apply when
3434 // selecting the best user-defined conversion for a
3435 // user-defined conversion sequence (see 13.3.3 and
3436 // 13.3.3.1).
3437 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003438 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003439 }
David Blaikie8a40f702012-01-17 06:56:22 +00003440 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003441
John McCall5c32be02010-08-24 20:38:10 +00003442 case OR_No_Viable_Function:
3443 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
John McCall5c32be02010-08-24 20:38:10 +00003445 case OR_Ambiguous:
3446 return OR_Ambiguous;
3447 }
3448
David Blaikie8a40f702012-01-17 06:56:22 +00003449 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003450}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003452bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003453Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003454 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003455 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3456 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003458 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003459 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003460 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003461 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3462 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003463 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003464 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003465 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003466 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003467 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003468 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003469 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003470 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003471 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003473}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003474
Douglas Gregor2837aa22012-02-22 17:32:19 +00003475/// \brief Compare the user-defined conversion functions or constructors
3476/// of two user-defined conversion sequences to determine whether any ordering
3477/// is possible.
3478static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003479compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003480 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003481 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003482 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003483
Douglas Gregor2837aa22012-02-22 17:32:19 +00003484 // Objective-C++:
3485 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003486 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003487 // respectively, always prefer the conversion to a function pointer,
3488 // because the function pointer is more lightweight and is more likely
3489 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003490 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003491 if (!Conv1)
3492 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003493
Douglas Gregor2837aa22012-02-22 17:32:19 +00003494 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3495 if (!Conv2)
3496 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003497
Douglas Gregor2837aa22012-02-22 17:32:19 +00003498 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3499 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3500 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3501 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003502 return Block1 ? ImplicitConversionSequence::Worse
3503 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003504 }
3505
3506 return ImplicitConversionSequence::Indistinguishable;
3507}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003508
3509static bool hasDeprecatedStringLiteralToCharPtrConversion(
3510 const ImplicitConversionSequence &ICS) {
3511 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3512 (ICS.isUserDefined() &&
3513 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3514}
3515
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003516/// CompareImplicitConversionSequences - Compare two implicit
3517/// conversion sequences to determine whether one is better than the
3518/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003519static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003520CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003521 const ImplicitConversionSequence& ICS1,
3522 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003523{
3524 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3525 // conversion sequences (as defined in 13.3.3.1)
3526 // -- a standard conversion sequence (13.3.3.1.1) is a better
3527 // conversion sequence than a user-defined conversion sequence or
3528 // an ellipsis conversion sequence, and
3529 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3530 // conversion sequence than an ellipsis conversion sequence
3531 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003532 //
John McCall0d1da222010-01-12 00:44:57 +00003533 // C++0x [over.best.ics]p10:
3534 // For the purpose of ranking implicit conversion sequences as
3535 // described in 13.3.3.2, the ambiguous conversion sequence is
3536 // treated as a user-defined sequence that is indistinguishable
3537 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003538
3539 // String literal to 'char *' conversion has been deprecated in C++03. It has
3540 // been removed from C++11. We still accept this conversion, if it happens at
3541 // the best viable function. Otherwise, this conversion is considered worse
3542 // than ellipsis conversion. Consider this as an extension; this is not in the
3543 // standard. For example:
3544 //
3545 // int &f(...); // #1
3546 // void f(char*); // #2
3547 // void g() { int &r = f("foo"); }
3548 //
3549 // In C++03, we pick #2 as the best viable function.
3550 // In C++11, we pick #1 as the best viable function, because ellipsis
3551 // conversion is better than string-literal to char* conversion (since there
3552 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3553 // convert arguments, #2 would be the best viable function in C++11.
3554 // If the best viable function has this conversion, a warning will be issued
3555 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3556
3557 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3558 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3559 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3560 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3561 ? ImplicitConversionSequence::Worse
3562 : ImplicitConversionSequence::Better;
3563
Douglas Gregor5ab11652010-04-17 22:01:05 +00003564 if (ICS1.getKindRank() < ICS2.getKindRank())
3565 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003566 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003567 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003568
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003569 // The following checks require both conversion sequences to be of
3570 // the same kind.
3571 if (ICS1.getKind() != ICS2.getKind())
3572 return ImplicitConversionSequence::Indistinguishable;
3573
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003574 ImplicitConversionSequence::CompareKind Result =
3575 ImplicitConversionSequence::Indistinguishable;
3576
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003577 // Two implicit conversion sequences of the same form are
3578 // indistinguishable conversion sequences unless one of the
3579 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003580
Larisse Voufo19d08672015-01-27 18:47:05 +00003581 // List-initialization sequence L1 is a better conversion sequence than
3582 // list-initialization sequence L2 if:
3583 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3584 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003585 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003586 // and N1 is smaller than N2.,
3587 // even if one of the other rules in this paragraph would otherwise apply.
3588 if (!ICS1.isBad()) {
3589 if (ICS1.isStdInitializerListElement() &&
3590 !ICS2.isStdInitializerListElement())
3591 return ImplicitConversionSequence::Better;
3592 if (!ICS1.isStdInitializerListElement() &&
3593 ICS2.isStdInitializerListElement())
3594 return ImplicitConversionSequence::Worse;
3595 }
3596
John McCall0d1da222010-01-12 00:44:57 +00003597 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003598 // Standard conversion sequence S1 is a better conversion sequence than
3599 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003600 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003601 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003602 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003603 // User-defined conversion sequence U1 is a better conversion
3604 // sequence than another user-defined conversion sequence U2 if
3605 // they contain the same user-defined conversion function or
3606 // constructor and if the second standard conversion sequence of
3607 // U1 is better than the second standard conversion sequence of
3608 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003609 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003610 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003611 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003612 ICS1.UserDefined.After,
3613 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003614 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003615 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003616 ICS1.UserDefined.ConversionFunction,
3617 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003618 }
3619
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003620 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003621}
3622
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003623static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3624 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3625 Qualifiers Quals;
3626 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003630 return Context.hasSameUnqualifiedType(T1, T2);
3631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003633// Per 13.3.3.2p3, compare the given standard conversion sequences to
3634// determine if one is a proper subset of the other.
3635static ImplicitConversionSequence::CompareKind
3636compareStandardConversionSubsets(ASTContext &Context,
3637 const StandardConversionSequence& SCS1,
3638 const StandardConversionSequence& SCS2) {
3639 ImplicitConversionSequence::CompareKind Result
3640 = ImplicitConversionSequence::Indistinguishable;
3641
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003643 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003644 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3645 return ImplicitConversionSequence::Better;
3646 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3647 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003649 if (SCS1.Second != SCS2.Second) {
3650 if (SCS1.Second == ICK_Identity)
3651 Result = ImplicitConversionSequence::Better;
3652 else if (SCS2.Second == ICK_Identity)
3653 Result = ImplicitConversionSequence::Worse;
3654 else
3655 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003656 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003657 return ImplicitConversionSequence::Indistinguishable;
3658
3659 if (SCS1.Third == SCS2.Third) {
3660 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3661 : ImplicitConversionSequence::Indistinguishable;
3662 }
3663
3664 if (SCS1.Third == ICK_Identity)
3665 return Result == ImplicitConversionSequence::Worse
3666 ? ImplicitConversionSequence::Indistinguishable
3667 : ImplicitConversionSequence::Better;
3668
3669 if (SCS2.Third == ICK_Identity)
3670 return Result == ImplicitConversionSequence::Better
3671 ? ImplicitConversionSequence::Indistinguishable
3672 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003674 return ImplicitConversionSequence::Indistinguishable;
3675}
3676
Douglas Gregore696ebb2011-01-26 14:52:12 +00003677/// \brief Determine whether one of the given reference bindings is better
3678/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003679static bool
3680isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3681 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003682 // C++0x [over.ics.rank]p3b4:
3683 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3684 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003686 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003688 // reference*.
3689 //
3690 // FIXME: Rvalue references. We're going rogue with the above edits,
3691 // because the semantics in the current C++0x working paper (N3225 at the
3692 // time of this writing) break the standard definition of std::forward
3693 // and std::reference_wrapper when dealing with references to functions.
3694 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003695 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3696 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3697 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698
Douglas Gregore696ebb2011-01-26 14:52:12 +00003699 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3700 SCS2.IsLvalueReference) ||
3701 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003702 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003703}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003705/// CompareStandardConversionSequences - Compare two standard
3706/// conversion sequences to determine whether one is better than the
3707/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003708static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003709CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003710 const StandardConversionSequence& SCS1,
3711 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003712{
3713 // Standard conversion sequence S1 is a better conversion sequence
3714 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3715
3716 // -- S1 is a proper subsequence of S2 (comparing the conversion
3717 // sequences in the canonical form defined by 13.3.3.1.1,
3718 // excluding any Lvalue Transformation; the identity conversion
3719 // sequence is considered to be a subsequence of any
3720 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003721 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003722 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003723 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003724
3725 // -- the rank of S1 is better than the rank of S2 (by the rules
3726 // defined below), or, if not that,
3727 ImplicitConversionRank Rank1 = SCS1.getRank();
3728 ImplicitConversionRank Rank2 = SCS2.getRank();
3729 if (Rank1 < Rank2)
3730 return ImplicitConversionSequence::Better;
3731 else if (Rank2 < Rank1)
3732 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3735 // are indistinguishable unless one of the following rules
3736 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003738 // A conversion that is not a conversion of a pointer, or
3739 // pointer to member, to bool is better than another conversion
3740 // that is such a conversion.
3741 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3742 return SCS2.isPointerConversionToBool()
3743 ? ImplicitConversionSequence::Better
3744 : ImplicitConversionSequence::Worse;
3745
Douglas Gregor5c407d92008-10-23 00:40:37 +00003746 // C++ [over.ics.rank]p4b2:
3747 //
3748 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003749 // conversion of B* to A* is better than conversion of B* to
3750 // void*, and conversion of A* to void* is better than conversion
3751 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003752 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003753 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003754 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003755 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003756 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3757 // Exactly one of the conversion sequences is a conversion to
3758 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003759 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3760 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003761 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3762 // Neither conversion sequence converts to a void pointer; compare
3763 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003764 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003765 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003766 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003767 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3768 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003769 // Both conversion sequences are conversions to void
3770 // pointers. Compare the source types to determine if there's an
3771 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003772 QualType FromType1 = SCS1.getFromType();
3773 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003774
3775 // Adjust the types we're converting from via the array-to-pointer
3776 // conversion, if we need to.
3777 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003778 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003779 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003780 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003782 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3783 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003784
Richard Smith0f59cb32015-12-18 21:45:41 +00003785 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003786 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003787 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003788 return ImplicitConversionSequence::Worse;
3789
3790 // Objective-C++: If one interface is more specific than the
3791 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003792 const ObjCObjectPointerType* FromObjCPtr1
3793 = FromType1->getAs<ObjCObjectPointerType>();
3794 const ObjCObjectPointerType* FromObjCPtr2
3795 = FromType2->getAs<ObjCObjectPointerType>();
3796 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003797 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003798 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003799 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003800 FromObjCPtr1);
3801 if (AssignLeft != AssignRight) {
3802 return AssignLeft? ImplicitConversionSequence::Better
3803 : ImplicitConversionSequence::Worse;
3804 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003805 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003806 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003807
3808 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3809 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003810 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003811 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003812 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003813
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003814 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003815 // Check for a better reference binding based on the kind of bindings.
3816 if (isBetterReferenceBindingKind(SCS1, SCS2))
3817 return ImplicitConversionSequence::Better;
3818 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3819 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Sebastian Redlb28b4072009-03-22 23:49:27 +00003821 // C++ [over.ics.rank]p3b4:
3822 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3823 // which the references refer are the same type except for
3824 // top-level cv-qualifiers, and the type to which the reference
3825 // initialized by S2 refers is more cv-qualified than the type
3826 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003827 QualType T1 = SCS1.getToType(2);
3828 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003829 T1 = S.Context.getCanonicalType(T1);
3830 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003831 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003832 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3833 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003834 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003835 // Objective-C++ ARC: If the references refer to objects with different
3836 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003837 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003838 SCS2.ObjCLifetimeConversionBinding) {
3839 return SCS1.ObjCLifetimeConversionBinding
3840 ? ImplicitConversionSequence::Worse
3841 : ImplicitConversionSequence::Better;
3842 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003843
Chandler Carruth8e543b32010-12-12 08:17:55 +00003844 // If the type is an array type, promote the element qualifiers to the
3845 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003846 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003847 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003848 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003849 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003850 if (T2.isMoreQualifiedThan(T1))
3851 return ImplicitConversionSequence::Better;
3852 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003853 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003854 }
3855 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003856
Francois Pichet08d2fa02011-09-18 21:37:37 +00003857 // In Microsoft mode, prefer an integral conversion to a
3858 // floating-to-integral conversion if the integral conversion
3859 // is between types of the same size.
3860 // For example:
3861 // void f(float);
3862 // void f(int);
3863 // int main {
3864 // long a;
3865 // f(a);
3866 // }
3867 // Here, MSVC will call f(int) instead of generating a compile error
3868 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003869 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3870 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003871 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003872 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003873 return ImplicitConversionSequence::Better;
3874
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003875 return ImplicitConversionSequence::Indistinguishable;
3876}
3877
3878/// CompareQualificationConversions - Compares two standard conversion
3879/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003880/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003881static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003882CompareQualificationConversions(Sema &S,
3883 const StandardConversionSequence& SCS1,
3884 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003885 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003886 // -- S1 and S2 differ only in their qualification conversion and
3887 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3888 // cv-qualification signature of type T1 is a proper subset of
3889 // the cv-qualification signature of type T2, and S1 is not the
3890 // deprecated string literal array-to-pointer conversion (4.2).
3891 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3892 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3893 return ImplicitConversionSequence::Indistinguishable;
3894
3895 // FIXME: the example in the standard doesn't use a qualification
3896 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003897 QualType T1 = SCS1.getToType(2);
3898 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003899 T1 = S.Context.getCanonicalType(T1);
3900 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003901 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003902 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3903 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003904
3905 // If the types are the same, we won't learn anything by unwrapped
3906 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003907 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003908 return ImplicitConversionSequence::Indistinguishable;
3909
Chandler Carruth607f38e2009-12-29 07:16:59 +00003910 // If the type is an array type, promote the element qualifiers to the type
3911 // for comparison.
3912 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003913 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003914 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003915 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003916
Mike Stump11289f42009-09-09 15:08:12 +00003917 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003918 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003919
John McCall31168b02011-06-15 23:02:42 +00003920 // Objective-C++ ARC:
3921 // Prefer qualification conversions not involving a change in lifetime
3922 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003923 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003924 SCS2.QualificationIncludesObjCLifetime) {
3925 Result = SCS1.QualificationIncludesObjCLifetime
3926 ? ImplicitConversionSequence::Worse
3927 : ImplicitConversionSequence::Better;
3928 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003929
John McCall5c32be02010-08-24 20:38:10 +00003930 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003931 // Within each iteration of the loop, we check the qualifiers to
3932 // determine if this still looks like a qualification
3933 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003934 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003935 // until there are no more pointers or pointers-to-members left
3936 // to unwrap. This essentially mimics what
3937 // IsQualificationConversion does, but here we're checking for a
3938 // strict subset of qualifiers.
3939 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3940 // The qualifiers are the same, so this doesn't tell us anything
3941 // about how the sequences rank.
3942 ;
3943 else if (T2.isMoreQualifiedThan(T1)) {
3944 // T1 has fewer qualifiers, so it could be the better sequence.
3945 if (Result == ImplicitConversionSequence::Worse)
3946 // Neither has qualifiers that are a subset of the other's
3947 // qualifiers.
3948 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003949
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003950 Result = ImplicitConversionSequence::Better;
3951 } else if (T1.isMoreQualifiedThan(T2)) {
3952 // T2 has fewer qualifiers, so it could be the better sequence.
3953 if (Result == ImplicitConversionSequence::Better)
3954 // Neither has qualifiers that are a subset of the other's
3955 // qualifiers.
3956 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003957
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003958 Result = ImplicitConversionSequence::Worse;
3959 } else {
3960 // Qualifiers are disjoint.
3961 return ImplicitConversionSequence::Indistinguishable;
3962 }
3963
3964 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003965 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003966 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003967 }
3968
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003969 // Check that the winning standard conversion sequence isn't using
3970 // the deprecated string literal array to pointer conversion.
3971 switch (Result) {
3972 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003973 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003974 Result = ImplicitConversionSequence::Indistinguishable;
3975 break;
3976
3977 case ImplicitConversionSequence::Indistinguishable:
3978 break;
3979
3980 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003981 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003982 Result = ImplicitConversionSequence::Indistinguishable;
3983 break;
3984 }
3985
3986 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003987}
3988
Douglas Gregor5c407d92008-10-23 00:40:37 +00003989/// CompareDerivedToBaseConversions - Compares two standard conversion
3990/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003991/// various kinds of derived-to-base conversions (C++
3992/// [over.ics.rank]p4b3). As part of these checks, we also look at
3993/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003994static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003995CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003996 const StandardConversionSequence& SCS1,
3997 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003998 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003999 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00004000 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004001 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004002
4003 // Adjust the types we're converting from via the array-to-pointer
4004 // conversion, if we need to.
4005 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004006 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004007 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004008 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004009
4010 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004011 FromType1 = S.Context.getCanonicalType(FromType1);
4012 ToType1 = S.Context.getCanonicalType(ToType1);
4013 FromType2 = S.Context.getCanonicalType(FromType2);
4014 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004015
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004016 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004017 //
4018 // If class B is derived directly or indirectly from class A and
4019 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004020 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004021 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004022 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004023 SCS2.Second == ICK_Pointer_Conversion &&
4024 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4025 FromType1->isPointerType() && FromType2->isPointerType() &&
4026 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004027 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004028 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004029 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004030 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004031 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004032 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004033 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004034 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004035
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004036 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004038 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004039 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004040 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004041 return ImplicitConversionSequence::Worse;
4042 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004043
4044 // -- conversion of B* to A* is better than conversion of C* to A*,
4045 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004046 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004047 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004048 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004049 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004050 }
4051 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4052 SCS2.Second == ICK_Pointer_Conversion) {
4053 const ObjCObjectPointerType *FromPtr1
4054 = FromType1->getAs<ObjCObjectPointerType>();
4055 const ObjCObjectPointerType *FromPtr2
4056 = FromType2->getAs<ObjCObjectPointerType>();
4057 const ObjCObjectPointerType *ToPtr1
4058 = ToType1->getAs<ObjCObjectPointerType>();
4059 const ObjCObjectPointerType *ToPtr2
4060 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004061
Douglas Gregor058d3de2011-01-31 18:51:41 +00004062 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4063 // Apply the same conversion ranking rules for Objective-C pointer types
4064 // that we do for C++ pointers to class types. However, we employ the
4065 // Objective-C pseudo-subtyping relationship used for assignment of
4066 // Objective-C pointer types.
4067 bool FromAssignLeft
4068 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4069 bool FromAssignRight
4070 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4071 bool ToAssignLeft
4072 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4073 bool ToAssignRight
4074 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004075
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004076 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004077 // type is better than a conversion to 'id'.
4078 if (ToPtr1->isObjCIdType() &&
4079 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCIdType() &&
4082 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4083 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004084
4085 // A conversion to a non-id object pointer type is better than a
4086 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004087 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4088 return ImplicitConversionSequence::Worse;
4089 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4090 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004091
4092 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004093 // type is better than a conversion to 'Class'.
4094 if (ToPtr1->isObjCClassType() &&
4095 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4096 return ImplicitConversionSequence::Worse;
4097 if (ToPtr2->isObjCClassType() &&
4098 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4099 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004100
4101 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004102 // conversion to a qualified 'Class' type.
4103 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4104 return ImplicitConversionSequence::Worse;
4105 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4106 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004107
Douglas Gregor058d3de2011-01-31 18:51:41 +00004108 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004109 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004110 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004111 (ToAssignLeft != ToAssignRight)) {
4112 if (FromPtr1->isSpecialized()) {
4113 // "conversion of B<A> * to B * is better than conversion of B * to
4114 // C *.
4115 bool IsFirstSame =
4116 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4117 bool IsSecondSame =
4118 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4119 if (IsFirstSame) {
4120 if (!IsSecondSame)
4121 return ImplicitConversionSequence::Better;
4122 } else if (IsSecondSame)
4123 return ImplicitConversionSequence::Worse;
4124 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004125 return ToAssignLeft? ImplicitConversionSequence::Worse
4126 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004127 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004128
4129 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4130 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4131 (FromAssignLeft != FromAssignRight))
4132 return FromAssignLeft? ImplicitConversionSequence::Better
4133 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004134 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004135 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004136
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004137 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004138 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4139 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4140 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004142 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004144 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004146 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004148 ToType2->getAs<MemberPointerType>();
4149 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4150 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4151 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4152 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4153 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4154 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4155 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4156 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004157 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004158 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004159 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004160 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004161 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004162 return ImplicitConversionSequence::Better;
4163 }
4164 // conversion of B::* to C::* is better than conversion of A::* to C::*
4165 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004166 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004167 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004168 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004169 return ImplicitConversionSequence::Worse;
4170 }
4171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregor5ab11652010-04-17 22:01:05 +00004173 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004174 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004175 // -- binding of an expression of type C to a reference of type
4176 // B& is better than binding an expression of type C to a
4177 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004178 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4179 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004180 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004181 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004182 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004183 return ImplicitConversionSequence::Worse;
4184 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004185
Douglas Gregor2fe98832008-11-03 19:09:14 +00004186 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004187 // -- binding of an expression of type B to a reference of type
4188 // A& is better than binding an expression of type C to a
4189 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004190 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4191 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004192 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004193 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004194 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004195 return ImplicitConversionSequence::Worse;
4196 }
4197 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004198
Douglas Gregor5c407d92008-10-23 00:40:37 +00004199 return ImplicitConversionSequence::Indistinguishable;
4200}
4201
Douglas Gregor45bb4832013-03-26 23:36:30 +00004202/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4203/// C++ class.
4204static bool isTypeValid(QualType T) {
4205 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4206 return !Record->isInvalidDecl();
4207
4208 return true;
4209}
4210
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004211/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4212/// determine whether they are reference-related,
4213/// reference-compatible, reference-compatible with added
4214/// qualification, or incompatible, for use in C++ initialization by
4215/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4216/// type, and the first type (T1) is the pointee type of the reference
4217/// type being initialized.
4218Sema::ReferenceCompareResult
4219Sema::CompareReferenceRelationship(SourceLocation Loc,
4220 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004221 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004222 bool &ObjCConversion,
4223 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004224 assert(!OrigT1->isReferenceType() &&
4225 "T1 must be the pointee type of the reference type");
4226 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4227
4228 QualType T1 = Context.getCanonicalType(OrigT1);
4229 QualType T2 = Context.getCanonicalType(OrigT2);
4230 Qualifiers T1Quals, T2Quals;
4231 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4232 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4233
4234 // C++ [dcl.init.ref]p4:
4235 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4236 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4237 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004238 DerivedToBase = false;
4239 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004240 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004241 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004242 if (UnqualT1 == UnqualT2) {
4243 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004244 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004245 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004246 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004247 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004248 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4249 UnqualT2->isObjCObjectOrInterfaceType() &&
4250 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4251 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004252 else if (UnqualT2->isFunctionType() &&
4253 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4254 // C++1z [dcl.init.ref]p4:
4255 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4256 // function" and T1 is "function"
4257 //
4258 // We extend this to also apply to 'noreturn', so allow any function
4259 // conversion between function types.
4260 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261 else
4262 return Ref_Incompatible;
4263
4264 // At this point, we know that T1 and T2 are reference-related (at
4265 // least).
4266
4267 // If the type is an array type, promote the element qualifiers to the type
4268 // for comparison.
4269 if (isa<ArrayType>(T1) && T1Quals)
4270 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4271 if (isa<ArrayType>(T2) && T2Quals)
4272 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4273
4274 // C++ [dcl.init.ref]p4:
4275 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4276 // reference-related to T2 and cv1 is the same cv-qualification
4277 // as, or greater cv-qualification than, cv2. For purposes of
4278 // overload resolution, cases for which cv1 is greater
4279 // cv-qualification than cv2 are identified as
4280 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004281 //
4282 // Note that we also require equivalence of Objective-C GC and address-space
4283 // qualifiers when performing these computations, so that e.g., an int in
4284 // address space 1 is not reference-compatible with an int in address
4285 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004286 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4287 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004288 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4289 ObjCLifetimeConversion = true;
4290
John McCall31168b02011-06-15 23:02:42 +00004291 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004292 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004293 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004294
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004295 // MS compiler ignores __unaligned qualifier for references; do the same.
4296 T1Quals.removeUnaligned();
4297 T2Quals.removeUnaligned();
4298
Richard Smithce766292016-10-21 23:01:55 +00004299 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004301 else
4302 return Ref_Related;
4303}
4304
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004305/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004306/// with DeclType. Return true if something definite is found.
4307static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004308FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4309 QualType DeclType, SourceLocation DeclLoc,
4310 Expr *Init, QualType T2, bool AllowRvalues,
4311 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004312 assert(T2->isRecordType() && "Can only find conversions of record types.");
4313 CXXRecordDecl *T2RecordDecl
4314 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4315
Richard Smith67ef14f2017-09-26 18:37:55 +00004316 OverloadCandidateSet CandidateSet(
4317 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004318 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4319 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004320 NamedDecl *D = *I;
4321 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4322 if (isa<UsingShadowDecl>(D))
4323 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4324
4325 FunctionTemplateDecl *ConvTemplate
4326 = dyn_cast<FunctionTemplateDecl>(D);
4327 CXXConversionDecl *Conv;
4328 if (ConvTemplate)
4329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4330 else
4331 Conv = cast<CXXConversionDecl>(D);
4332
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004334 // explicit conversions, skip it.
4335 if (!AllowExplicit && Conv->isExplicit())
4336 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregor836a7e82010-08-11 02:15:33 +00004338 if (AllowRvalues) {
4339 bool DerivedToBase = false;
4340 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004341 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004342
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004343 // If we are initializing an rvalue reference, don't permit conversion
4344 // functions that return lvalues.
4345 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4346 const ReferenceType *RefType
4347 = Conv->getConversionType()->getAs<LValueReferenceType>();
4348 if (RefType && !RefType->getPointeeType()->isFunctionType())
4349 continue;
4350 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004351
Douglas Gregor836a7e82010-08-11 02:15:33 +00004352 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004353 S.CompareReferenceRelationship(
4354 DeclLoc,
4355 Conv->getConversionType().getNonReferenceType()
4356 .getUnqualifiedType(),
4357 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004358 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004359 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004360 continue;
4361 } else {
4362 // If the conversion function doesn't return a reference type,
4363 // it can't be considered for this conversion. An rvalue reference
4364 // is only acceptable if its referencee is a function type.
4365
4366 const ReferenceType *RefType =
4367 Conv->getConversionType()->getAs<ReferenceType>();
4368 if (!RefType ||
4369 (!RefType->isLValueReferenceType() &&
4370 !RefType->getPointeeType()->isFunctionType()))
4371 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Douglas Gregor836a7e82010-08-11 02:15:33 +00004374 if (ConvTemplate)
4375 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004376 Init, DeclType, CandidateSet,
4377 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004378 else
4379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004380 DeclType, CandidateSet,
4381 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004382 }
4383
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004384 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4385
Sebastian Redld92badf2010-06-30 18:13:39 +00004386 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004387 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004388 case OR_Success:
4389 // C++ [over.ics.ref]p1:
4390 //
4391 // [...] If the parameter binds directly to the result of
4392 // applying a conversion function to the argument
4393 // expression, the implicit conversion sequence is a
4394 // user-defined conversion sequence (13.3.3.1.2), with the
4395 // second standard conversion sequence either an identity
4396 // conversion or, if the conversion function returns an
4397 // entity of a type that is a derived class of the parameter
4398 // type, a derived-to-base Conversion.
4399 if (!Best->FinalConversion.DirectBinding)
4400 return false;
4401
4402 ICS.setUserDefined();
4403 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4404 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004405 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004406 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004407 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004408 ICS.UserDefined.EllipsisConversion = false;
4409 assert(ICS.UserDefined.After.ReferenceBinding &&
4410 ICS.UserDefined.After.DirectBinding &&
4411 "Expected a direct reference binding!");
4412 return true;
4413
4414 case OR_Ambiguous:
4415 ICS.setAmbiguous();
4416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4417 Cand != CandidateSet.end(); ++Cand)
4418 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004419 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004420 return true;
4421
4422 case OR_No_Viable_Function:
4423 case OR_Deleted:
4424 // There was no suitable conversion, or we found a deleted
4425 // conversion; continue with other checks.
4426 return false;
4427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
David Blaikie8a40f702012-01-17 06:56:22 +00004429 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004430}
4431
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004432/// \brief Compute an implicit conversion sequence for reference
4433/// initialization.
4434static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004435TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004436 SourceLocation DeclLoc,
4437 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004438 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004439 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4440
4441 // Most paths end in a failed conversion.
4442 ImplicitConversionSequence ICS;
4443 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4444
4445 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4446 QualType T2 = Init->getType();
4447
4448 // If the initializer is the address of an overloaded function, try
4449 // to resolve the overloaded function. If all goes well, T2 is the
4450 // type of the resulting function.
4451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452 DeclAccessPair Found;
4453 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4454 false, Found))
4455 T2 = Fn->getType();
4456 }
4457
4458 // Compute some basic properties of the types and the initializer.
4459 bool isRValRef = DeclType->isRValueReferenceType();
4460 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004461 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004462 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004463 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004464 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004465 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004466 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004468
Sebastian Redld92badf2010-06-30 18:13:39 +00004469 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004470 // A reference to type "cv1 T1" is initialized by an expression
4471 // of type "cv2 T2" as follows:
4472
Sebastian Redld92badf2010-06-30 18:13:39 +00004473 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004474 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004475 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4476 // reference-compatible with "cv2 T2," or
4477 //
4478 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004479 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004481 // When a parameter of reference type binds directly (8.5.3)
4482 // to an argument expression, the implicit conversion sequence
4483 // is the identity conversion, unless the argument expression
4484 // has a type that is a derived class of the parameter type,
4485 // in which case the implicit conversion sequence is a
4486 // derived-to-base Conversion (13.3.3.1).
4487 ICS.setStandard();
4488 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004489 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4490 : ObjCConversion? ICK_Compatible_Conversion
4491 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004492 ICS.Standard.Third = ICK_Identity;
4493 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4494 ICS.Standard.setToType(0, T2);
4495 ICS.Standard.setToType(1, T1);
4496 ICS.Standard.setToType(2, T1);
4497 ICS.Standard.ReferenceBinding = true;
4498 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004499 ICS.Standard.IsLvalueReference = !isRValRef;
4500 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4501 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004502 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004503 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004505 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004506
Sebastian Redld92badf2010-06-30 18:13:39 +00004507 // Nothing more to do: the inaccessibility/ambiguity check for
4508 // derived-to-base conversions is suppressed when we're
4509 // computing the implicit conversion sequence (C++
4510 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004511 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004512 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004513
Sebastian Redld92badf2010-06-30 18:13:39 +00004514 // -- has a class type (i.e., T2 is a class type), where T1 is
4515 // not reference-related to T2, and can be implicitly
4516 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4517 // is reference-compatible with "cv3 T3" 92) (this
4518 // conversion is selected by enumerating the applicable
4519 // conversion functions (13.3.1.6) and choosing the best
4520 // one through overload resolution (13.3)),
4521 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004522 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004523 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004524 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4525 Init, T2, /*AllowRvalues=*/false,
4526 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004527 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004528 }
4529 }
4530
Sebastian Redld92badf2010-06-30 18:13:39 +00004531 // -- Otherwise, the reference shall be an lvalue reference to a
4532 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004533 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004534 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004535 return ICS;
4536
Douglas Gregorf143cd52011-01-24 16:14:37 +00004537 // -- If the initializer expression
4538 //
4539 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004540 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004541 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004542 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004543 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4544 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004545 ICS.setStandard();
4546 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004548 : ObjCConversion? ICK_Compatible_Conversion
4549 : ICK_Identity;
4550 ICS.Standard.Third = ICK_Identity;
4551 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4552 ICS.Standard.setToType(0, T2);
4553 ICS.Standard.setToType(1, T1);
4554 ICS.Standard.setToType(2, T1);
4555 ICS.Standard.ReferenceBinding = true;
4556 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4557 // binding unless we're binding to a class prvalue.
4558 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4559 // allow the use of rvalue references in C++98/03 for the benefit of
4560 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004562 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004563 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004564 ICS.Standard.IsLvalueReference = !isRValRef;
4565 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004567 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004568 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004569 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004570 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573
Douglas Gregorf143cd52011-01-24 16:14:37 +00004574 // -- has a class type (i.e., T2 is a class type), where T1 is not
4575 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576 // an xvalue, class prvalue, or function lvalue of type
4577 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004578 // "cv3 T3",
4579 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004581 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004583 // class subobject).
4584 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004585 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004586 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4587 Init, T2, /*AllowRvalues=*/true,
4588 AllowExplicit)) {
4589 // In the second case, if the reference is an rvalue reference
4590 // and the second standard conversion sequence of the
4591 // user-defined conversion sequence includes an lvalue-to-rvalue
4592 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004594 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4595 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4596
Douglas Gregor95273c32011-01-21 16:36:05 +00004597 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
Richard Smith19172c42014-07-14 02:28:44 +00004600 // A temporary of function type cannot be created; don't even try.
4601 if (T1->isFunctionType())
4602 return ICS;
4603
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004604 // -- Otherwise, a temporary of type "cv1 T1" is created and
4605 // initialized from the initializer expression using the
4606 // rules for a non-reference copy initialization (8.5). The
4607 // reference is then bound to the temporary. If T1 is
4608 // reference-related to T2, cv1 must be the same
4609 // cv-qualification as, or greater cv-qualification than,
4610 // cv2; otherwise, the program is ill-formed.
4611 if (RefRelationship == Sema::Ref_Related) {
4612 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4613 // we would be reference-compatible or reference-compatible with
4614 // added qualification. But that wasn't the case, so the reference
4615 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004616 //
4617 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004618 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004619 Qualifiers T1Quals = T1.getQualifiers();
4620 Qualifiers T2Quals = T2.getQualifiers();
4621 T1Quals.removeObjCGCAttr();
4622 T1Quals.removeObjCLifetime();
4623 T2Quals.removeObjCGCAttr();
4624 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004625 // MS compiler ignores __unaligned qualifier for references; do the same.
4626 T1Quals.removeUnaligned();
4627 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004628 if (!T1Quals.compatiblyIncludes(T2Quals))
4629 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004630 }
4631
4632 // If at least one of the types is a class type, the types are not
4633 // related, and we aren't allowed any user conversions, the
4634 // reference binding fails. This case is important for breaking
4635 // recursion, since TryImplicitConversion below will attempt to
4636 // create a temporary through the use of a copy constructor.
4637 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638 (T1->isRecordType() || T2->isRecordType()))
4639 return ICS;
4640
Douglas Gregorcba72b12011-01-21 05:18:22 +00004641 // If T1 is reference-related to T2 and the reference is an rvalue
4642 // reference, the initializer expression shall not be an lvalue.
4643 if (RefRelationship >= Sema::Ref_Related &&
4644 isRValRef && Init->Classify(S.Context).isLValue())
4645 return ICS;
4646
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004647 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004648 // When a parameter of reference type is not bound directly to
4649 // an argument expression, the conversion sequence is the one
4650 // required to convert the argument expression to the
4651 // underlying type of the reference according to
4652 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4653 // to copy-initializing a temporary of the underlying type with
4654 // the argument expression. Any difference in top-level
4655 // cv-qualification is subsumed by the initialization itself
4656 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004657 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4658 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004659 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004660 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004661 /*AllowObjCWritebackConversion=*/false,
4662 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004663
4664 // Of course, that's still a reference binding.
4665 if (ICS.isStandard()) {
4666 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004667 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004668 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004669 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004670 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004671 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004672 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004673 const ReferenceType *LValRefType =
4674 ICS.UserDefined.ConversionFunction->getReturnType()
4675 ->getAs<LValueReferenceType>();
4676
4677 // C++ [over.ics.ref]p3:
4678 // Except for an implicit object parameter, for which see 13.3.1, a
4679 // standard conversion sequence cannot be formed if it requires [...]
4680 // binding an rvalue reference to an lvalue other than a function
4681 // lvalue.
4682 // Note that the function case is not possible here.
4683 if (DeclType->isRValueReferenceType() && LValRefType) {
4684 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4685 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4686 // reference to an rvalue!
4687 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4688 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004689 }
Richard Smith19172c42014-07-14 02:28:44 +00004690
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004691 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004692 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004693 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4694 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004695 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4696 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004697 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004698
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004699 return ICS;
4700}
4701
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004702static ImplicitConversionSequence
4703TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4704 bool SuppressUserConversions,
4705 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004706 bool AllowObjCWritebackConversion,
4707 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004708
4709/// TryListConversion - Try to copy-initialize a value of type ToType from the
4710/// initializer list From.
4711static ImplicitConversionSequence
4712TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4713 bool SuppressUserConversions,
4714 bool InOverloadResolution,
4715 bool AllowObjCWritebackConversion) {
4716 // C++11 [over.ics.list]p1:
4717 // When an argument is an initializer list, it is not an expression and
4718 // special rules apply for converting it to a parameter type.
4719
4720 ImplicitConversionSequence Result;
4721 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4722
Sebastian Redl09edce02012-01-23 22:09:39 +00004723 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004724 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004725 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004726 return Result;
4727
Larisse Voufo19d08672015-01-27 18:47:05 +00004728 // Per DR1467:
4729 // If the parameter type is a class X and the initializer list has a single
4730 // element of type cv U, where U is X or a class derived from X, the
4731 // implicit conversion sequence is the one required to convert the element
4732 // to the parameter type.
4733 //
4734 // Otherwise, if the parameter type is a character array [... ]
4735 // and the initializer list has a single element that is an
4736 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4737 // implicit conversion sequence is the identity conversion.
4738 if (From->getNumInits() == 1) {
4739 if (ToType->isRecordType()) {
4740 QualType InitType = From->getInit(0)->getType();
4741 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004742 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004743 return TryCopyInitialization(S, From->getInit(0), ToType,
4744 SuppressUserConversions,
4745 InOverloadResolution,
4746 AllowObjCWritebackConversion);
4747 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004748 // FIXME: Check the other conditions here: array of character type,
4749 // initializer is a string literal.
4750 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004751 InitializedEntity Entity =
4752 InitializedEntity::InitializeParameter(S.Context, ToType,
4753 /*Consumed=*/false);
4754 if (S.CanPerformCopyInitialization(Entity, From)) {
4755 Result.setStandard();
4756 Result.Standard.setAsIdentityConversion();
4757 Result.Standard.setFromType(ToType);
4758 Result.Standard.setAllToTypes(ToType);
4759 return Result;
4760 }
4761 }
4762 }
4763
4764 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004765 // C++11 [over.ics.list]p2:
4766 // If the parameter type is std::initializer_list<X> or "array of X" and
4767 // all the elements can be implicitly converted to X, the implicit
4768 // conversion sequence is the worst conversion necessary to convert an
4769 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004770 //
4771 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004772 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004773 // list has exactly N elements or if it has fewer than N elements and X is
4774 // default-constructible, and if all the elements of the initializer list
4775 // can be implicitly converted to X, the implicit conversion sequence is
4776 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004777 //
4778 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004779 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004780 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004781 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004782 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004783 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004784 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004785 if (!X.isNull()) {
4786 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4787 Expr *Init = From->getInit(i);
4788 ImplicitConversionSequence ICS =
4789 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4790 InOverloadResolution,
4791 AllowObjCWritebackConversion);
4792 // If a single element isn't convertible, fail.
4793 if (ICS.isBad()) {
4794 Result = ICS;
4795 break;
4796 }
4797 // Otherwise, look for the worst conversion.
4798 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004799 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4800 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004801 ImplicitConversionSequence::Worse)
4802 Result = ICS;
4803 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004804
4805 // For an empty list, we won't have computed any conversion sequence.
4806 // Introduce the identity conversion sequence.
4807 if (From->getNumInits() == 0) {
4808 Result.setStandard();
4809 Result.Standard.setAsIdentityConversion();
4810 Result.Standard.setFromType(ToType);
4811 Result.Standard.setAllToTypes(ToType);
4812 }
4813
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004814 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004815 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004816 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004817
Larisse Voufo19d08672015-01-27 18:47:05 +00004818 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004819 // C++11 [over.ics.list]p3:
4820 // Otherwise, if the parameter is a non-aggregate class X and overload
4821 // resolution chooses a single best constructor [...] the implicit
4822 // conversion sequence is a user-defined conversion sequence. If multiple
4823 // constructors are viable but none is better than the others, the
4824 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004825 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4826 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004827 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4828 /*AllowExplicit=*/false,
4829 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004830 AllowObjCWritebackConversion,
4831 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004832 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004833
Larisse Voufo19d08672015-01-27 18:47:05 +00004834 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004835 // C++11 [over.ics.list]p4:
4836 // Otherwise, if the parameter has an aggregate type which can be
4837 // initialized from the initializer list [...] the implicit conversion
4838 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004839 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004840 // Type is an aggregate, argument is an init list. At this point it comes
4841 // down to checking whether the initialization works.
4842 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004843 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4844 // need to call into the initialization code here; overload resolution
4845 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004846 InitializedEntity Entity =
4847 InitializedEntity::InitializeParameter(S.Context, ToType,
4848 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004849 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004850 Result.setUserDefined();
4851 Result.UserDefined.Before.setAsIdentityConversion();
4852 // Initializer lists don't have a type.
4853 Result.UserDefined.Before.setFromType(QualType());
4854 Result.UserDefined.Before.setAllToTypes(QualType());
4855
4856 Result.UserDefined.After.setAsIdentityConversion();
4857 Result.UserDefined.After.setFromType(ToType);
4858 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004859 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004860 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004861 return Result;
4862 }
4863
Larisse Voufo19d08672015-01-27 18:47:05 +00004864 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004865 // C++11 [over.ics.list]p5:
4866 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004867 if (ToType->isReferenceType()) {
4868 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4869 // mention initializer lists in any way. So we go by what list-
4870 // initialization would do and try to extrapolate from that.
4871
4872 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4873
4874 // If the initializer list has a single element that is reference-related
4875 // to the parameter type, we initialize the reference from that.
4876 if (From->getNumInits() == 1) {
4877 Expr *Init = From->getInit(0);
4878
4879 QualType T2 = Init->getType();
4880
4881 // If the initializer is the address of an overloaded function, try
4882 // to resolve the overloaded function. If all goes well, T2 is the
4883 // type of the resulting function.
4884 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4885 DeclAccessPair Found;
4886 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4887 Init, ToType, false, Found))
4888 T2 = Fn->getType();
4889 }
4890
4891 // Compute some basic properties of the types and the initializer.
4892 bool dummy1 = false;
4893 bool dummy2 = false;
4894 bool dummy3 = false;
4895 Sema::ReferenceCompareResult RefRelationship
4896 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4897 dummy2, dummy3);
4898
Richard Smith4d2bbd72013-09-06 01:22:42 +00004899 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004900 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4901 SuppressUserConversions,
4902 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004903 }
Sebastian Redldf888642011-12-03 14:54:30 +00004904 }
4905
4906 // Otherwise, we bind the reference to a temporary created from the
4907 // initializer list.
4908 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4909 InOverloadResolution,
4910 AllowObjCWritebackConversion);
4911 if (Result.isFailure())
4912 return Result;
4913 assert(!Result.isEllipsis() &&
4914 "Sub-initialization cannot result in ellipsis conversion.");
4915
4916 // Can we even bind to a temporary?
4917 if (ToType->isRValueReferenceType() ||
4918 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4919 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4920 Result.UserDefined.After;
4921 SCS.ReferenceBinding = true;
4922 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4923 SCS.BindsToRvalue = true;
4924 SCS.BindsToFunctionLvalue = false;
4925 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4926 SCS.ObjCLifetimeConversionBinding = false;
4927 } else
4928 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4929 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004930 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004931 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004932
Larisse Voufo19d08672015-01-27 18:47:05 +00004933 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004934 // C++11 [over.ics.list]p6:
4935 // Otherwise, if the parameter type is not a class:
4936 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004937 // - if the initializer list has one element that is not itself an
4938 // initializer list, the implicit conversion sequence is the one
4939 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004940 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004941 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004942 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4943 SuppressUserConversions,
4944 InOverloadResolution,
4945 AllowObjCWritebackConversion);
4946 // - if the initializer list has no elements, the implicit conversion
4947 // sequence is the identity conversion.
4948 else if (NumInits == 0) {
4949 Result.setStandard();
4950 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004951 Result.Standard.setFromType(ToType);
4952 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004953 }
4954 return Result;
4955 }
4956
Larisse Voufo19d08672015-01-27 18:47:05 +00004957 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004958 // C++11 [over.ics.list]p7:
4959 // In all cases other than those enumerated above, no conversion is possible
4960 return Result;
4961}
4962
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004963/// TryCopyInitialization - Try to copy-initialize a value of type
4964/// ToType from the expression From. Return the implicit conversion
4965/// sequence required to pass this argument, which may be a bad
4966/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004967/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004968/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004969static ImplicitConversionSequence
4970TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004971 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004972 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004973 bool AllowObjCWritebackConversion,
4974 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004975 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4976 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4977 InOverloadResolution,AllowObjCWritebackConversion);
4978
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004979 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004980 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004981 /*FIXME:*/From->getLocStart(),
4982 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004983 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004984
John McCall5c32be02010-08-24 20:38:10 +00004985 return TryImplicitConversion(S, From, ToType,
4986 SuppressUserConversions,
4987 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004988 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004989 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004990 AllowObjCWritebackConversion,
4991 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004992}
4993
Anna Zaks1b068122011-07-28 19:46:48 +00004994static bool TryCopyInitialization(const CanQualType FromQTy,
4995 const CanQualType ToQTy,
4996 Sema &S,
4997 SourceLocation Loc,
4998 ExprValueKind FromVK) {
4999 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5000 ImplicitConversionSequence ICS =
5001 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5002
5003 return !ICS.isBad();
5004}
5005
Douglas Gregor436424c2008-11-18 23:14:02 +00005006/// TryObjectArgumentInitialization - Try to initialize the object
5007/// parameter of the given member function (@c Method) from the
5008/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005009static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005010TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005011 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005012 CXXMethodDecl *Method,
5013 CXXRecordDecl *ActingContext) {
5014 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005015 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5016 // const volatile object.
5017 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5018 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005019 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005020
5021 // Set up the conversion sequence as a "bad" conversion, to allow us
5022 // to exit early.
5023 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005024
5025 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005026 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005027 FromType = PT->getPointeeType();
5028
Douglas Gregor02824322011-01-26 19:30:28 +00005029 // When we had a pointer, it's implicitly dereferenced, so we
5030 // better have an lvalue.
5031 assert(FromClassification.isLValue());
5032 }
5033
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005034 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005035
Douglas Gregor02824322011-01-26 19:30:28 +00005036 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005038 // parameter is
5039 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005040 // - "lvalue reference to cv X" for functions declared without a
5041 // ref-qualifier or with the & ref-qualifier
5042 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005043 // ref-qualifier
5044 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005046 // cv-qualification on the member function declaration.
5047 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005049 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005050 // (C++ [over.match.funcs]p5). We perform a simplified version of
5051 // reference binding here, that allows class rvalues to bind to
5052 // non-constant references.
5053
Douglas Gregor02824322011-01-26 19:30:28 +00005054 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005055 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005057 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005058 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005059 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005060 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005061 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005062 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005063
5064 // Check that we have either the same type or a derived type. It
5065 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005066 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005067 ImplicitConversionKind SecondKind;
5068 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5069 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005070 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005071 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005072 else {
John McCall65eb8792010-02-25 01:37:24 +00005073 ICS.setBad(BadConversionSequence::unrelated_class,
5074 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005075 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005076 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005077
Douglas Gregor02824322011-01-26 19:30:28 +00005078 // Check the ref-qualifier.
5079 switch (Method->getRefQualifier()) {
5080 case RQ_None:
5081 // Do nothing; we don't care about lvalueness or rvalueness.
5082 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Douglas Gregor02824322011-01-26 19:30:28 +00005084 case RQ_LValue:
5085 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5086 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005088 ImplicitParamType);
5089 return ICS;
5090 }
5091 break;
5092
5093 case RQ_RValue:
5094 if (!FromClassification.isRValue()) {
5095 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005097 ImplicitParamType);
5098 return ICS;
5099 }
5100 break;
5101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
Douglas Gregor436424c2008-11-18 23:14:02 +00005103 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005104 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005105 ICS.Standard.setAsIdentityConversion();
5106 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005107 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005108 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005109 ICS.Standard.ReferenceBinding = true;
5110 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005112 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005113 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5114 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5115 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005116 return ICS;
5117}
5118
5119/// PerformObjectArgumentInitialization - Perform initialization of
5120/// the implicit object parameter for the given Method with the given
5121/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005122ExprResult
5123Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005125 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005126 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005127 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005128 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005129 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005130
Douglas Gregor02824322011-01-26 19:30:28 +00005131 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005132 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005133 FromRecordType = PT->getPointeeType();
5134 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005135 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005136 } else {
5137 FromRecordType = From->getType();
5138 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005139 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005140 }
5141
John McCall6e9f8f62009-12-03 04:06:58 +00005142 // Note that we always use the true parent context when performing
5143 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005144 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005145 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5146 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005147 if (ICS.isBad()) {
5148 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5149 Qualifiers FromQs = FromRecordType.getQualifiers();
5150 Qualifiers ToQs = DestType.getQualifiers();
5151 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5152 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005153 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005154 diag::err_member_function_call_bad_cvr)
5155 << Method->getDeclName() << FromRecordType << (CVR - 1)
5156 << From->getSourceRange();
5157 Diag(Method->getLocation(), diag::note_previous_decl)
5158 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005159 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005160 }
5161 }
5162
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005163 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005164 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005165 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005166 }
Mike Stump11289f42009-09-09 15:08:12 +00005167
John Wiegley01296292011-04-08 18:41:53 +00005168 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5169 ExprResult FromRes =
5170 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5171 if (FromRes.isInvalid())
5172 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005173 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005174 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005175
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005176 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005177 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005178 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005179 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005180}
5181
Douglas Gregor5fb53972009-01-14 15:45:31 +00005182/// TryContextuallyConvertToBool - Attempt to contextually convert the
5183/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005184static ImplicitConversionSequence
5185TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005186 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005187 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005188 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005189 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005190 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005191 /*AllowObjCWritebackConversion=*/false,
5192 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005193}
5194
5195/// PerformContextuallyConvertToBool - Perform a contextual conversion
5196/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005197ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005198 if (checkPlaceholderForOverload(*this, From))
5199 return ExprError();
5200
John McCall5c32be02010-08-24 20:38:10 +00005201 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005202 if (!ICS.isBad())
5203 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Fariborz Jahanian76197412009-11-18 18:26:29 +00005205 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005206 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005207 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005208 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005209 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005210}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Richard Smithf8379a02012-01-18 23:55:52 +00005212/// Check that the specified conversion is permitted in a converted constant
5213/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5214/// is acceptable.
5215static bool CheckConvertedConstantConversions(Sema &S,
5216 StandardConversionSequence &SCS) {
5217 // Since we know that the target type is an integral or unscoped enumeration
5218 // type, most conversion kinds are impossible. All possible First and Third
5219 // conversions are fine.
5220 switch (SCS.Second) {
5221 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005222 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005223 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005224 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005225 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005226 return true;
5227
5228 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005229 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005230 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5231 // conversion, so we allow it in a converted constant expression.
5232 //
5233 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5234 // a lot of popular code. We should at least add a warning for this
5235 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005236 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5237 SCS.getToType(2)->isBooleanType();
5238
Richard Smith410cc892014-11-26 03:26:53 +00005239 case ICK_Pointer_Conversion:
5240 case ICK_Pointer_Member:
5241 // C++1z: null pointer conversions and null member pointer conversions are
5242 // only permitted if the source type is std::nullptr_t.
5243 return SCS.getFromType()->isNullPtrType();
5244
5245 case ICK_Floating_Promotion:
5246 case ICK_Complex_Promotion:
5247 case ICK_Floating_Conversion:
5248 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005249 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005250 case ICK_Compatible_Conversion:
5251 case ICK_Derived_To_Base:
5252 case ICK_Vector_Conversion:
5253 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005254 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005255 case ICK_Block_Pointer_Conversion:
5256 case ICK_TransparentUnionConversion:
5257 case ICK_Writeback_Conversion:
5258 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005259 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005260 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005261 return false;
5262
5263 case ICK_Lvalue_To_Rvalue:
5264 case ICK_Array_To_Pointer:
5265 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005266 llvm_unreachable("found a first conversion kind in Second");
5267
Richard Smithf8379a02012-01-18 23:55:52 +00005268 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005269 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005270
5271 case ICK_Num_Conversion_Kinds:
5272 break;
5273 }
5274
5275 llvm_unreachable("unknown conversion kind");
5276}
5277
5278/// CheckConvertedConstantExpression - Check that the expression From is a
5279/// converted constant expression of type T, perform the conversion and produce
5280/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005281static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5282 QualType T, APValue &Value,
5283 Sema::CCEKind CCE,
5284 bool RequireInt) {
5285 assert(S.getLangOpts().CPlusPlus11 &&
5286 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005287
Richard Smith410cc892014-11-26 03:26:53 +00005288 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005289 return ExprError();
5290
Richard Smith410cc892014-11-26 03:26:53 +00005291 // C++1z [expr.const]p3:
5292 // A converted constant expression of type T is an expression,
5293 // implicitly converted to type T, where the converted
5294 // expression is a constant expression and the implicit conversion
5295 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005296 // C++1z [stmt.if]p2:
5297 // If the if statement is of the form if constexpr, the value of the
5298 // condition shall be a contextually converted constant expression of type
5299 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005300 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005301 CCE == Sema::CCEK_ConstexprIf
5302 ? TryContextuallyConvertToBool(S, From)
5303 : TryCopyInitialization(S, From, T,
5304 /*SuppressUserConversions=*/false,
5305 /*InOverloadResolution=*/false,
5306 /*AllowObjcWritebackConversion=*/false,
5307 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005308 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005309 switch (ICS.getKind()) {
5310 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005311 SCS = &ICS.Standard;
5312 break;
5313 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005314 // We are converting to a non-class type, so the Before sequence
5315 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005316 SCS = &ICS.UserDefined.After;
5317 break;
5318 case ImplicitConversionSequence::AmbiguousConversion:
5319 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005320 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5321 return S.Diag(From->getLocStart(),
5322 diag::err_typecheck_converted_constant_expression)
5323 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005324 return ExprError();
5325
5326 case ImplicitConversionSequence::EllipsisConversion:
5327 llvm_unreachable("ellipsis conversion in converted constant expression");
5328 }
5329
Richard Smith410cc892014-11-26 03:26:53 +00005330 // Check that we would only use permitted conversions.
5331 if (!CheckConvertedConstantConversions(S, *SCS)) {
5332 return S.Diag(From->getLocStart(),
5333 diag::err_typecheck_converted_constant_expression_disallowed)
5334 << From->getType() << From->getSourceRange() << T;
5335 }
5336 // [...] and where the reference binding (if any) binds directly.
5337 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5338 return S.Diag(From->getLocStart(),
5339 diag::err_typecheck_converted_constant_expression_indirect)
5340 << From->getType() << From->getSourceRange() << T;
5341 }
5342
5343 ExprResult Result =
5344 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005345 if (Result.isInvalid())
5346 return Result;
5347
5348 // Check for a narrowing implicit conversion.
5349 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005350 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005351 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005352 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005353 case NK_Dependent_Narrowing:
5354 // Implicit conversion to a narrower type, but the expression is
5355 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005356 case NK_Variable_Narrowing:
5357 // Implicit conversion to a narrower type, and the value is not a constant
5358 // expression. We'll diagnose this in a moment.
5359 case NK_Not_Narrowing:
5360 break;
5361
5362 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005363 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005364 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005365 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005366 break;
5367
5368 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005369 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005370 << CCE << /*Constant*/0 << From->getType() << T;
5371 break;
5372 }
5373
Richard Smith52e624f2016-12-21 21:42:57 +00005374 if (Result.get()->isValueDependent()) {
5375 Value = APValue();
5376 return Result;
5377 }
5378
Richard Smithf8379a02012-01-18 23:55:52 +00005379 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005380 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005381 Expr::EvalResult Eval;
5382 Eval.Diag = &Notes;
5383
Richard Smith410cc892014-11-26 03:26:53 +00005384 if ((T->isReferenceType()
5385 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5386 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5387 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005388 // The expression can't be folded, so we can't keep it at this position in
5389 // the AST.
5390 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005391 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005392 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005393
5394 if (Notes.empty()) {
5395 // It's a constant expression.
5396 return Result;
5397 }
Richard Smithf8379a02012-01-18 23:55:52 +00005398 }
5399
5400 // It's not a constant expression. Produce an appropriate diagnostic.
5401 if (Notes.size() == 1 &&
5402 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005403 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005404 else {
Richard Smith410cc892014-11-26 03:26:53 +00005405 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005406 << CCE << From->getSourceRange();
5407 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005408 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005409 }
Richard Smith410cc892014-11-26 03:26:53 +00005410 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005411}
5412
Richard Smith410cc892014-11-26 03:26:53 +00005413ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5414 APValue &Value, CCEKind CCE) {
5415 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5416}
5417
5418ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5419 llvm::APSInt &Value,
5420 CCEKind CCE) {
5421 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5422
5423 APValue V;
5424 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005425 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005426 Value = V.getInt();
5427 return R;
5428}
5429
5430
John McCallfec112d2011-09-09 06:11:02 +00005431/// dropPointerConversions - If the given standard conversion sequence
5432/// involves any pointer conversions, remove them. This may change
5433/// the result type of the conversion sequence.
5434static void dropPointerConversion(StandardConversionSequence &SCS) {
5435 if (SCS.Second == ICK_Pointer_Conversion) {
5436 SCS.Second = ICK_Identity;
5437 SCS.Third = ICK_Identity;
5438 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5439 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005440}
John McCall5c32be02010-08-24 20:38:10 +00005441
John McCallfec112d2011-09-09 06:11:02 +00005442/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5443/// convert the expression From to an Objective-C pointer type.
5444static ImplicitConversionSequence
5445TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5446 // Do an implicit conversion to 'id'.
5447 QualType Ty = S.Context.getObjCIdType();
5448 ImplicitConversionSequence ICS
5449 = TryImplicitConversion(S, From, Ty,
5450 // FIXME: Are these flags correct?
5451 /*SuppressUserConversions=*/false,
5452 /*AllowExplicit=*/true,
5453 /*InOverloadResolution=*/false,
5454 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005455 /*AllowObjCWritebackConversion=*/false,
5456 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005457
5458 // Strip off any final conversions to 'id'.
5459 switch (ICS.getKind()) {
5460 case ImplicitConversionSequence::BadConversion:
5461 case ImplicitConversionSequence::AmbiguousConversion:
5462 case ImplicitConversionSequence::EllipsisConversion:
5463 break;
5464
5465 case ImplicitConversionSequence::UserDefinedConversion:
5466 dropPointerConversion(ICS.UserDefined.After);
5467 break;
5468
5469 case ImplicitConversionSequence::StandardConversion:
5470 dropPointerConversion(ICS.Standard);
5471 break;
5472 }
5473
5474 return ICS;
5475}
5476
5477/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5478/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005479/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005480ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005481 if (checkPlaceholderForOverload(*this, From))
5482 return ExprError();
5483
John McCall8b07ec22010-05-15 11:32:37 +00005484 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005485 ImplicitConversionSequence ICS =
5486 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005487 if (!ICS.isBad())
5488 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005489 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005490}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005491
Richard Smith8dd34252012-02-04 07:07:42 +00005492/// Determine whether the provided type is an integral type, or an enumeration
5493/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005494bool Sema::ICEConvertDiagnoser::match(QualType T) {
5495 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5496 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005497}
5498
Larisse Voufo236bec22013-06-10 06:50:24 +00005499static ExprResult
5500diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5501 Sema::ContextualImplicitConverter &Converter,
5502 QualType T, UnresolvedSetImpl &ViableConversions) {
5503
5504 if (Converter.Suppress)
5505 return ExprError();
5506
5507 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5508 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5509 CXXConversionDecl *Conv =
5510 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5511 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5512 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5513 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005514 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005515}
5516
5517static bool
5518diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5519 Sema::ContextualImplicitConverter &Converter,
5520 QualType T, bool HadMultipleCandidates,
5521 UnresolvedSetImpl &ExplicitConversions) {
5522 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5523 DeclAccessPair Found = ExplicitConversions[0];
5524 CXXConversionDecl *Conversion =
5525 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5526
5527 // The user probably meant to invoke the given explicit
5528 // conversion; use it.
5529 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5530 std::string TypeStr;
5531 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5532
5533 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5534 << FixItHint::CreateInsertion(From->getLocStart(),
5535 "static_cast<" + TypeStr + ">(")
5536 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005537 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005538 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5539
5540 // If we aren't in a SFINAE context, build a call to the
5541 // explicit conversion function.
5542 if (SemaRef.isSFINAEContext())
5543 return true;
5544
Craig Topperc3ec1492014-05-26 06:22:03 +00005545 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005546 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5547 HadMultipleCandidates);
5548 if (Result.isInvalid())
5549 return true;
5550 // Record usage of conversion in an implicit cast.
5551 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005552 CK_UserDefinedConversion, Result.get(),
5553 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005554 }
5555 return false;
5556}
5557
5558static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5559 Sema::ContextualImplicitConverter &Converter,
5560 QualType T, bool HadMultipleCandidates,
5561 DeclAccessPair &Found) {
5562 CXXConversionDecl *Conversion =
5563 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005564 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005565
5566 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5567 if (!Converter.SuppressConversion) {
5568 if (SemaRef.isSFINAEContext())
5569 return true;
5570
5571 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5572 << From->getSourceRange();
5573 }
5574
5575 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5576 HadMultipleCandidates);
5577 if (Result.isInvalid())
5578 return true;
5579 // Record usage of conversion in an implicit cast.
5580 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005581 CK_UserDefinedConversion, Result.get(),
5582 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005583 return false;
5584}
5585
5586static ExprResult finishContextualImplicitConversion(
5587 Sema &SemaRef, SourceLocation Loc, Expr *From,
5588 Sema::ContextualImplicitConverter &Converter) {
5589 if (!Converter.match(From->getType()) && !Converter.Suppress)
5590 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5591 << From->getSourceRange();
5592
5593 return SemaRef.DefaultLvalueConversion(From);
5594}
5595
5596static void
5597collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5598 UnresolvedSetImpl &ViableConversions,
5599 OverloadCandidateSet &CandidateSet) {
5600 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5601 DeclAccessPair FoundDecl = ViableConversions[I];
5602 NamedDecl *D = FoundDecl.getDecl();
5603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5604 if (isa<UsingShadowDecl>(D))
5605 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5606
5607 CXXConversionDecl *Conv;
5608 FunctionTemplateDecl *ConvTemplate;
5609 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5610 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5611 else
5612 Conv = cast<CXXConversionDecl>(D);
5613
5614 if (ConvTemplate)
5615 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005616 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5617 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005618 else
5619 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005620 ToType, CandidateSet,
5621 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005622 }
5623}
5624
Richard Smithccc11812013-05-21 19:05:48 +00005625/// \brief Attempt to convert the given expression to a type which is accepted
5626/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005627///
Richard Smithccc11812013-05-21 19:05:48 +00005628/// This routine will attempt to convert an expression of class type to a
5629/// type accepted by the specified converter. In C++11 and before, the class
5630/// must have a single non-explicit conversion function converting to a matching
5631/// type. In C++1y, there can be multiple such conversion functions, but only
5632/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005633///
Douglas Gregor4799d032010-06-30 00:20:43 +00005634/// \param Loc The source location of the construct that requires the
5635/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005636///
James Dennett18348b62012-06-22 08:52:37 +00005637/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005638///
Richard Smithccc11812013-05-21 19:05:48 +00005639/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005640///
Douglas Gregor4799d032010-06-30 00:20:43 +00005641/// \returns The expression, converted to an integral or enumeration type if
5642/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005643ExprResult Sema::PerformContextualImplicitConversion(
5644 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005645 // We can't perform any more checking for type-dependent expressions.
5646 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005647 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
Eli Friedman1da70392012-01-26 00:26:18 +00005649 // Process placeholders immediately.
5650 if (From->hasPlaceholderType()) {
5651 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 if (result.isInvalid())
5653 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005654 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005655 }
5656
Richard Smithccc11812013-05-21 19:05:48 +00005657 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005658 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005659 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005660 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005661
5662 // FIXME: Check for missing '()' if T is a function type?
5663
Richard Smithccc11812013-05-21 19:05:48 +00005664 // We can only perform contextual implicit conversions on objects of class
5665 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005666 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005667 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005668 if (!Converter.Suppress)
5669 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005670 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005673 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005674 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005675 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005676 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005677
5678 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005679 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005680
Craig Toppere14c0f82014-03-12 04:55:44 +00005681 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005682 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005683 }
Richard Smithccc11812013-05-21 19:05:48 +00005684 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005685
Richard Smithdb0ac552015-12-18 22:40:25 +00005686 if (Converter.Suppress ? !isCompleteType(Loc, T)
5687 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005688 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005690 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005691 UnresolvedSet<4>
5692 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005693 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005694 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005695 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Larisse Voufo236bec22013-06-10 06:50:24 +00005697 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005698 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005699
Larisse Voufo236bec22013-06-10 06:50:24 +00005700 // To check that there is only one target type, in C++1y:
5701 QualType ToType;
5702 bool HasUniqueTargetType = true;
5703
5704 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005705 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005706 NamedDecl *D = (*I)->getUnderlyingDecl();
5707 CXXConversionDecl *Conversion;
5708 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5709 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005710 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005711 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5712 else
5713 continue; // C++11 does not consider conversion operator templates(?).
5714 } else
5715 Conversion = cast<CXXConversionDecl>(D);
5716
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005717 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005718 "Conversion operator templates are considered potentially "
5719 "viable in C++1y");
5720
5721 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5722 if (Converter.match(CurToType) || ConvTemplate) {
5723
5724 if (Conversion->isExplicit()) {
5725 // FIXME: For C++1y, do we need this restriction?
5726 // cf. diagnoseNoViableConversion()
5727 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005728 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005729 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005730 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005731 if (ToType.isNull())
5732 ToType = CurToType.getUnqualifiedType();
5733 else if (HasUniqueTargetType &&
5734 (CurToType.getUnqualifiedType() != ToType))
5735 HasUniqueTargetType = false;
5736 }
5737 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005738 }
Richard Smith8dd34252012-02-04 07:07:42 +00005739 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005742 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005743 // C++1y [conv]p6:
5744 // ... An expression e of class type E appearing in such a context
5745 // is said to be contextually implicitly converted to a specified
5746 // type T and is well-formed if and only if e can be implicitly
5747 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005748 // for conversion functions whose return type is cv T or reference to
5749 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005750 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Larisse Voufo236bec22013-06-10 06:50:24 +00005752 // If no unique T is found:
5753 if (ToType.isNull()) {
5754 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5755 HadMultipleCandidates,
5756 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005757 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005758 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
Larisse Voufo236bec22013-06-10 06:50:24 +00005761 // If more than one unique Ts are found:
5762 if (!HasUniqueTargetType)
5763 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5764 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Larisse Voufo236bec22013-06-10 06:50:24 +00005766 // If one unique T is found:
5767 // First, build a candidate set from the previously recorded
5768 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005769 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005770 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5771 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Larisse Voufo236bec22013-06-10 06:50:24 +00005773 // Then, perform overload resolution over the candidate set.
5774 OverloadCandidateSet::iterator Best;
5775 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5776 case OR_Success: {
5777 // Apply this conversion.
5778 DeclAccessPair Found =
5779 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5780 if (recordConversion(*this, Loc, From, Converter, T,
5781 HadMultipleCandidates, Found))
5782 return ExprError();
5783 break;
5784 }
5785 case OR_Ambiguous:
5786 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5787 ViableConversions);
5788 case OR_No_Viable_Function:
5789 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5790 HadMultipleCandidates,
5791 ExplicitConversions))
5792 return ExprError();
5793 // fall through 'OR_Deleted' case.
5794 case OR_Deleted:
5795 // We'll complain below about a non-integral condition type.
5796 break;
5797 }
5798 } else {
5799 switch (ViableConversions.size()) {
5800 case 0: {
5801 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5802 HadMultipleCandidates,
5803 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005804 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005805
Larisse Voufo236bec22013-06-10 06:50:24 +00005806 // We'll complain below about a non-integral condition type.
5807 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005808 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005809 case 1: {
5810 // Apply this conversion.
5811 DeclAccessPair Found = ViableConversions[0];
5812 if (recordConversion(*this, Loc, From, Converter, T,
5813 HadMultipleCandidates, Found))
5814 return ExprError();
5815 break;
5816 }
5817 default:
5818 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819 ViableConversions);
5820 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005822
Larisse Voufo236bec22013-06-10 06:50:24 +00005823 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005824}
5825
Richard Smith100b24a2014-04-17 01:52:14 +00005826/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5827/// an acceptable non-member overloaded operator for a call whose
5828/// arguments have types T1 (and, if non-empty, T2). This routine
5829/// implements the check in C++ [over.match.oper]p3b2 concerning
5830/// enumeration types.
5831static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5832 FunctionDecl *Fn,
5833 ArrayRef<Expr *> Args) {
5834 QualType T1 = Args[0]->getType();
5835 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5836
5837 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5838 return true;
5839
5840 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5841 return true;
5842
5843 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5844 if (Proto->getNumParams() < 1)
5845 return false;
5846
5847 if (T1->isEnumeralType()) {
5848 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5849 if (Context.hasSameUnqualifiedType(T1, ArgType))
5850 return true;
5851 }
5852
5853 if (Proto->getNumParams() < 2)
5854 return false;
5855
5856 if (!T2.isNull() && T2->isEnumeralType()) {
5857 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5858 if (Context.hasSameUnqualifiedType(T2, ArgType))
5859 return true;
5860 }
5861
5862 return false;
5863}
5864
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005865/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005866/// candidate functions, using the given function call arguments. If
5867/// @p SuppressUserConversions, then don't allow user-defined
5868/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005869///
James Dennett2a4d13c2012-06-15 07:13:21 +00005870/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005871/// based on an incomplete set of function arguments. This feature is used by
5872/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005873void
5874Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005875 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005876 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005877 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005878 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005879 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005880 bool AllowExplicit,
5881 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005882 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005883 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005884 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005885 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005886 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005887
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005888 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005889 if (!isa<CXXConstructorDecl>(Method)) {
5890 // If we get here, it's because we're calling a member function
5891 // that is named without a member access expression (e.g.,
5892 // "this->f") that was either written explicitly or created
5893 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005894 // function, e.g., X::f(). We use an empty type for the implied
5895 // object argument (C++ [over.call.func]p3), and the acting context
5896 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005897 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005898 Expr::Classification::makeSimpleLValue(), Args,
5899 CandidateSet, SuppressUserConversions,
5900 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005901 return;
5902 }
5903 // We treat a constructor like a non-member function, since its object
5904 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005905 }
5906
Douglas Gregorff7028a2009-11-13 23:59:09 +00005907 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005908 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005909
Richard Smith100b24a2014-04-17 01:52:14 +00005910 // C++ [over.match.oper]p3:
5911 // if no operand has a class type, only those non-member functions in the
5912 // lookup set that have a first parameter of type T1 or "reference to
5913 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5914 // is a right operand) a second parameter of type T2 or "reference to
5915 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5916 // candidate functions.
5917 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5918 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5919 return;
5920
Richard Smith8b86f2d2013-11-04 01:48:18 +00005921 // C++11 [class.copy]p11: [DR1402]
5922 // A defaulted move constructor that is defined as deleted is ignored by
5923 // overload resolution.
5924 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5925 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5926 Constructor->isMoveConstructor())
5927 return;
5928
Douglas Gregor27381f32009-11-23 12:27:39 +00005929 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005930 EnterExpressionEvaluationContext Unevaluated(
5931 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005932
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005933 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005934 OverloadCandidate &Candidate =
5935 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005936 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005937 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005938 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005939 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005940 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005941 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942
John McCall578a1f82014-12-14 01:46:53 +00005943 if (Constructor) {
5944 // C++ [class.copy]p3:
5945 // A member function template is never instantiated to perform the copy
5946 // of a class object to an object of its class type.
5947 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005948 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005949 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005950 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5951 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005952 Candidate.Viable = false;
5953 Candidate.FailureKind = ovl_fail_illegal_constructor;
5954 return;
5955 }
Richard Smith836a3b42017-01-13 20:46:54 +00005956
5957 // C++ [over.match.funcs]p8: (proposed DR resolution)
5958 // A constructor inherited from class type C that has a first parameter
5959 // of type "reference to P" (including such a constructor instantiated
5960 // from a template) is excluded from the set of candidate functions when
5961 // constructing an object of type cv D if the argument list has exactly
5962 // one argument and D is reference-related to P and P is reference-related
5963 // to C.
5964 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5965 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5966 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5967 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5968 QualType C = Context.getRecordType(Constructor->getParent());
5969 QualType D = Context.getRecordType(Shadow->getParent());
5970 SourceLocation Loc = Args.front()->getExprLoc();
5971 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5972 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5973 Candidate.Viable = false;
5974 Candidate.FailureKind = ovl_fail_inhctor_slice;
5975 return;
5976 }
5977 }
John McCall578a1f82014-12-14 01:46:53 +00005978 }
5979
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005980 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005981
5982 // (C++ 13.3.2p2): A candidate function having fewer than m
5983 // parameters is viable only if it has an ellipsis in its parameter
5984 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005985 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005986 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005987 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005988 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005989 return;
5990 }
5991
5992 // (C++ 13.3.2p2): A candidate function having more than m parameters
5993 // is viable only if the (m+1)st parameter has a default argument
5994 // (8.3.6). For the purposes of overload resolution, the
5995 // parameter list is truncated on the right, so that there are
5996 // exactly m parameters.
5997 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005998 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005999 // Not enough arguments.
6000 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006001 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006002 return;
6003 }
6004
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006005 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006006 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006007 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006008 // Skip the check for callers that are implicit members, because in this
6009 // case we may not yet know what the member's target is; the target is
6010 // inferred for the member automatically, based on the bases and fields of
6011 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006012 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006013 Candidate.Viable = false;
6014 Candidate.FailureKind = ovl_fail_bad_target;
6015 return;
6016 }
6017
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006018 // Determine the implicit conversion sequences for each of the
6019 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006020 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006021 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6022 // We already formed a conversion sequence for this parameter during
6023 // template argument deduction.
6024 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006025 // (C++ 13.3.2p3): for F to be a viable function, there shall
6026 // exist for each argument an implicit conversion sequence
6027 // (13.3.3.1) that converts that argument to the corresponding
6028 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006029 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006030 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006031 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006033 /*InOverloadResolution=*/true,
6034 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006035 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006036 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006037 if (Candidate.Conversions[ArgIdx].isBad()) {
6038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006039 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006040 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006041 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006042 } else {
6043 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6044 // argument for which there is no corresponding parameter is
6045 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006046 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006047 }
6048 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006049
6050 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6051 Candidate.Viable = false;
6052 Candidate.FailureKind = ovl_fail_enable_if;
6053 Candidate.DeductionFailure.Data = FailedAttr;
6054 return;
6055 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006056
6057 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6058 Candidate.Viable = false;
6059 Candidate.FailureKind = ovl_fail_ext_disabled;
6060 return;
6061 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006062}
6063
Manman Rend2a3cd72016-04-07 19:30:20 +00006064ObjCMethodDecl *
6065Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6066 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6067 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006068 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006069
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006070 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6071 bool Match = true;
6072 ObjCMethodDecl *Method = Methods[b];
6073 unsigned NumNamedArgs = Sel.getNumArgs();
6074 // Method might have more arguments than selector indicates. This is due
6075 // to addition of c-style arguments in method.
6076 if (Method->param_size() > NumNamedArgs)
6077 NumNamedArgs = Method->param_size();
6078 if (Args.size() < NumNamedArgs)
6079 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006080
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006081 for (unsigned i = 0; i < NumNamedArgs; i++) {
6082 // We can't do any type-checking on a type-dependent argument.
6083 if (Args[i]->isTypeDependent()) {
6084 Match = false;
6085 break;
6086 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006087
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006088 ParmVarDecl *param = Method->parameters()[i];
6089 Expr *argExpr = Args[i];
6090 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006091
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006092 // Strip the unbridged-cast placeholder expression off unless it's
6093 // a consumed argument.
6094 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6095 !param->hasAttr<CFConsumedAttr>())
6096 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006097
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006098 // If the parameter is __unknown_anytype, move on to the next method.
6099 if (param->getType() == Context.UnknownAnyTy) {
6100 Match = false;
6101 break;
6102 }
George Burgess IV45461812015-10-11 20:13:20 +00006103
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006104 ImplicitConversionSequence ConversionState
6105 = TryCopyInitialization(*this, argExpr, param->getType(),
6106 /*SuppressUserConversions*/false,
6107 /*InOverloadResolution=*/true,
6108 /*AllowObjCWritebackConversion=*/
6109 getLangOpts().ObjCAutoRefCount,
6110 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006111 // This function looks for a reasonably-exact match, so we consider
6112 // incompatible pointer conversions to be a failure here.
6113 if (ConversionState.isBad() ||
6114 (ConversionState.isStandard() &&
6115 ConversionState.Standard.Second ==
6116 ICK_Incompatible_Pointer_Conversion)) {
6117 Match = false;
6118 break;
6119 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006120 }
6121 // Promote additional arguments to variadic methods.
6122 if (Match && Method->isVariadic()) {
6123 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6124 if (Args[i]->isTypeDependent()) {
6125 Match = false;
6126 break;
6127 }
6128 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6129 nullptr);
6130 if (Arg.isInvalid()) {
6131 Match = false;
6132 break;
6133 }
6134 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006135 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006136 // Check for extra arguments to non-variadic methods.
6137 if (Args.size() != NumNamedArgs)
6138 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006139 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6140 // Special case when selectors have no argument. In this case, select
6141 // one with the most general result type of 'id'.
6142 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6143 QualType ReturnT = Methods[b]->getReturnType();
6144 if (ReturnT->isObjCIdType())
6145 return Methods[b];
6146 }
6147 }
6148 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006149
6150 if (Match)
6151 return Method;
6152 }
6153 return nullptr;
6154}
6155
George Burgess IV2a6150d2015-10-16 01:17:38 +00006156// specific_attr_iterator iterates over enable_if attributes in reverse, and
6157// enable_if is order-sensitive. As a result, we need to reverse things
6158// sometimes. Size of 4 elements is arbitrary.
6159static SmallVector<EnableIfAttr *, 4>
6160getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6161 SmallVector<EnableIfAttr *, 4> Result;
6162 if (!Function->hasAttrs())
6163 return Result;
6164
6165 const auto &FuncAttrs = Function->getAttrs();
6166 for (Attr *Attr : FuncAttrs)
6167 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6168 Result.push_back(EnableIf);
6169
6170 std::reverse(Result.begin(), Result.end());
6171 return Result;
6172}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006173
George Burgess IV177399e2017-01-09 04:12:14 +00006174static bool
6175convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6176 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6177 bool MissingImplicitThis, Expr *&ConvertedThis,
6178 SmallVectorImpl<Expr *> &ConvertedArgs) {
6179 if (ThisArg) {
6180 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6181 assert(!isa<CXXConstructorDecl>(Method) &&
6182 "Shouldn't have `this` for ctors!");
6183 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6184 ExprResult R = S.PerformObjectArgumentInitialization(
6185 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6186 if (R.isInvalid())
6187 return false;
6188 ConvertedThis = R.get();
6189 } else {
6190 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6191 (void)MD;
6192 assert((MissingImplicitThis || MD->isStatic() ||
6193 isa<CXXConstructorDecl>(MD)) &&
6194 "Expected `this` for non-ctor instance methods");
6195 }
6196 ConvertedThis = nullptr;
6197 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006198
George Burgess IV458b3f32016-08-12 04:19:35 +00006199 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006200 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006201 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6202
Nick Lewyckye283c552015-08-25 22:33:16 +00006203 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006204 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006205 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006206 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6207 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006208 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006209
George Burgess IV177399e2017-01-09 04:12:14 +00006210 if (R.isInvalid())
6211 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006212
George Burgess IVe96abf72016-02-24 22:31:14 +00006213 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006214 }
6215
George Burgess IV177399e2017-01-09 04:12:14 +00006216 if (Trap.hasErrorOccurred())
6217 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006218
Nick Lewyckye283c552015-08-25 22:33:16 +00006219 // Push default arguments if needed.
6220 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6221 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6222 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006223 ExprResult R = S.PerformCopyInitialization(
6224 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006225 Function->getParamDecl(i)),
6226 SourceLocation(),
6227 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6228 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006229 if (R.isInvalid())
6230 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006231 ConvertedArgs.push_back(R.get());
6232 }
6233
George Burgess IV177399e2017-01-09 04:12:14 +00006234 if (Trap.hasErrorOccurred())
6235 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006236 }
George Burgess IV177399e2017-01-09 04:12:14 +00006237 return true;
6238}
6239
6240EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6241 bool MissingImplicitThis) {
6242 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6243 getOrderedEnableIfAttrs(Function);
6244 if (EnableIfAttrs.empty())
6245 return nullptr;
6246
6247 SFINAETrap Trap(*this);
6248 SmallVector<Expr *, 16> ConvertedArgs;
6249 // FIXME: We should look into making enable_if late-parsed.
6250 Expr *DiscardedThis;
6251 if (!convertArgsForAvailabilityChecks(
6252 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6253 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6254 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006255
George Burgess IV2a6150d2015-10-16 01:17:38 +00006256 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006257 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006258 // FIXME: This doesn't consider value-dependent cases, because doing so is
6259 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006260 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006261 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006262 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006263
6264 if (!Result.isInt() || !Result.getInt().getBoolValue())
6265 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006266 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006267 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006268}
6269
George Burgess IV177399e2017-01-09 04:12:14 +00006270template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006271static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006272 bool ArgDependent, SourceLocation Loc,
6273 CheckFn &&IsSuccessful) {
6274 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006275 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006276 if (ArgDependent == DIA->getArgDependent())
6277 Attrs.push_back(DIA);
6278 }
6279
6280 // Common case: No diagnose_if attributes, so we can quit early.
6281 if (Attrs.empty())
6282 return false;
6283
6284 auto WarningBegin = std::stable_partition(
6285 Attrs.begin(), Attrs.end(),
6286 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6287
George Burgess IV177399e2017-01-09 04:12:14 +00006288 // Note that diagnose_if attributes are late-parsed, so they appear in the
6289 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006290 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6291 IsSuccessful);
6292 if (ErrAttr != WarningBegin) {
6293 const DiagnoseIfAttr *DIA = *ErrAttr;
6294 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6295 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6296 << DIA->getParent() << DIA->getCond()->getSourceRange();
6297 return true;
6298 }
George Burgess IV177399e2017-01-09 04:12:14 +00006299
George Burgess IVce6284b2017-01-28 02:19:40 +00006300 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6301 if (IsSuccessful(DIA)) {
6302 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6303 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6304 << DIA->getParent() << DIA->getCond()->getSourceRange();
6305 }
6306
6307 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006308}
6309
George Burgess IVce6284b2017-01-28 02:19:40 +00006310bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6311 const Expr *ThisArg,
6312 ArrayRef<const Expr *> Args,
6313 SourceLocation Loc) {
6314 return diagnoseDiagnoseIfAttrsWith(
6315 *this, Function, /*ArgDependent=*/true, Loc,
6316 [&](const DiagnoseIfAttr *DIA) {
6317 APValue Result;
6318 // It's sane to use the same Args for any redecl of this function, since
6319 // EvaluateWithSubstitution only cares about the position of each
6320 // argument in the arg list, not the ParmVarDecl* it maps to.
6321 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006322 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006323 return false;
6324 return Result.isInt() && Result.getInt().getBoolValue();
6325 });
George Burgess IV177399e2017-01-09 04:12:14 +00006326}
6327
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006328bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006329 SourceLocation Loc) {
6330 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006331 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006332 [&](const DiagnoseIfAttr *DIA) {
6333 bool Result;
6334 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6335 Result;
6336 });
George Burgess IV177399e2017-01-09 04:12:14 +00006337}
6338
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006339/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006340/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006341void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006342 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006343 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006344 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006345 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006346 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006347 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006348 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006350 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6351 QualType ObjectType;
6352 Expr::Classification ObjectClassification;
6353 if (Expr *E = Args[0]) {
6354 // Use the explit base to restrict the lookup:
6355 ObjectType = E->getType();
6356 ObjectClassification = E->Classify(Context);
6357 } // .. else there is an implit base.
John McCalla0296f72010-03-19 07:35:19 +00006358 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006359 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6360 ObjectClassification, Args.slice(1), CandidateSet,
6361 SuppressUserConversions, PartialOverloading);
6362 } else {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006363 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006364 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006365 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006366 } else {
John McCalla0296f72010-03-19 07:35:19 +00006367 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006368 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006369 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6370 QualType ObjectType;
6371 Expr::Classification ObjectClassification;
6372 if (Expr *E = Args[0]) {
6373 // Use the explit base to restrict the lookup:
6374 ObjectType = E->getType();
6375 ObjectClassification = E->Classify(Context);
6376 } // .. else there is an implit base.
George Burgess IV177399e2017-01-09 04:12:14 +00006377 AddMethodTemplateCandidate(
6378 FunTmpl, F.getPair(),
6379 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006380 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6381 Args.slice(1), CandidateSet, SuppressUserConversions,
6382 PartialOverloading);
6383 } else {
John McCalla0296f72010-03-19 07:35:19 +00006384 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006385 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006386 CandidateSet, SuppressUserConversions,
6387 PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006388 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006389 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006390 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006391}
6392
John McCallf0f1cf02009-11-17 07:50:12 +00006393/// AddMethodCandidate - Adds a named decl (which is some kind of
6394/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006395void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006396 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006397 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006398 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006399 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006400 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006401 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006402 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006403
6404 if (isa<UsingShadowDecl>(Decl))
6405 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006406
John McCallf0f1cf02009-11-17 07:50:12 +00006407 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6408 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6409 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006410 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006411 /*ExplicitArgs*/ nullptr, ObjectType,
6412 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006413 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006414 } else {
John McCalla0296f72010-03-19 07:35:19 +00006415 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006416 ObjectType, ObjectClassification, Args, CandidateSet,
6417 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006418 }
6419}
6420
Douglas Gregor436424c2008-11-18 23:14:02 +00006421/// AddMethodCandidate - Adds the given C++ member function to the set
6422/// of candidate functions, using the given function call arguments
6423/// and the object argument (@c Object). For example, in a call
6424/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6425/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6426/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006427/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006428void
John McCalla0296f72010-03-19 07:35:19 +00006429Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006430 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006431 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006432 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006433 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006434 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006435 bool PartialOverloading,
6436 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006437 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006438 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006439 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006440 assert(!isa<CXXConstructorDecl>(Method) &&
6441 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006442
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006443 if (!CandidateSet.isNewCandidate(Method))
6444 return;
6445
Richard Smith8b86f2d2013-11-04 01:48:18 +00006446 // C++11 [class.copy]p23: [DR1402]
6447 // A defaulted move assignment operator that is defined as deleted is
6448 // ignored by overload resolution.
6449 if (Method->isDefaulted() && Method->isDeleted() &&
6450 Method->isMoveAssignmentOperator())
6451 return;
6452
Douglas Gregor27381f32009-11-23 12:27:39 +00006453 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006454 EnterExpressionEvaluationContext Unevaluated(
6455 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006456
Douglas Gregor436424c2008-11-18 23:14:02 +00006457 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006458 OverloadCandidate &Candidate =
6459 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006460 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006461 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006462 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006463 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006464 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006465
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006466 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006467
6468 // (C++ 13.3.2p2): A candidate function having fewer than m
6469 // parameters is viable only if it has an ellipsis in its parameter
6470 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006471 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6472 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006473 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006474 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006475 return;
6476 }
6477
6478 // (C++ 13.3.2p2): A candidate function having more than m parameters
6479 // is viable only if the (m+1)st parameter has a default argument
6480 // (8.3.6). For the purposes of overload resolution, the
6481 // parameter list is truncated on the right, so that there are
6482 // exactly m parameters.
6483 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006484 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006485 // Not enough arguments.
6486 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006487 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006488 return;
6489 }
6490
6491 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006492
John McCall6e9f8f62009-12-03 04:06:58 +00006493 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006494 // The implicit object argument is ignored.
6495 Candidate.IgnoreObjectArgument = true;
6496 else {
6497 // Determine the implicit conversion sequence for the object
6498 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006499 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6500 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6501 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006502 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006503 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006504 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006505 return;
6506 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006507 }
6508
Eli Bendersky291a57e2014-09-25 23:59:08 +00006509 // (CUDA B.1): Check for invalid calls between targets.
6510 if (getLangOpts().CUDA)
6511 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006512 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006513 Candidate.Viable = false;
6514 Candidate.FailureKind = ovl_fail_bad_target;
6515 return;
6516 }
6517
Douglas Gregor436424c2008-11-18 23:14:02 +00006518 // Determine the implicit conversion sequences for each of the
6519 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006520 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006521 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6522 // We already formed a conversion sequence for this parameter during
6523 // template argument deduction.
6524 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006525 // (C++ 13.3.2p3): for F to be a viable function, there shall
6526 // exist for each argument an implicit conversion sequence
6527 // (13.3.3.1) that converts that argument to the corresponding
6528 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006529 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006530 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006531 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006533 /*InOverloadResolution=*/true,
6534 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006535 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006536 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006537 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006538 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006539 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006540 }
6541 } else {
6542 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6543 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006544 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006545 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006546 }
6547 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006548
6549 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6550 Candidate.Viable = false;
6551 Candidate.FailureKind = ovl_fail_enable_if;
6552 Candidate.DeductionFailure.Data = FailedAttr;
6553 return;
6554 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006555}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006556
Douglas Gregor97628d62009-08-21 00:16:32 +00006557/// \brief Add a C++ member function template as a candidate to the candidate
6558/// set, using template argument deduction to produce an appropriate member
6559/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006560void
Douglas Gregor97628d62009-08-21 00:16:32 +00006561Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006562 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006563 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006564 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006565 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006566 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006567 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006568 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006569 bool SuppressUserConversions,
6570 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006571 if (!CandidateSet.isNewCandidate(MethodTmpl))
6572 return;
6573
Douglas Gregor97628d62009-08-21 00:16:32 +00006574 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006575 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006576 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006577 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006578 // candidate functions in the usual way.113) A given name can refer to one
6579 // or more function templates and also to a set of overloaded non-template
6580 // functions. In such a case, the candidate functions generated from each
6581 // function template are combined with the set of non-template candidate
6582 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006583 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006584 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006585 ConversionSequenceList Conversions;
6586 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6587 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6588 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6589 return CheckNonDependentConversions(
6590 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6591 SuppressUserConversions, ActingContext, ObjectType,
6592 ObjectClassification);
6593 })) {
6594 OverloadCandidate &Candidate =
6595 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006596 Candidate.FoundDecl = FoundDecl;
6597 Candidate.Function = MethodTmpl->getTemplatedDecl();
6598 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006599 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006600 Candidate.IgnoreObjectArgument =
6601 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6602 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006603 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006604 if (Result == TDK_NonDependentConversionFailure)
6605 Candidate.FailureKind = ovl_fail_bad_conversion;
6606 else {
6607 Candidate.FailureKind = ovl_fail_bad_deduction;
6608 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6609 Info);
6610 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006611 return;
6612 }
Mike Stump11289f42009-09-09 15:08:12 +00006613
Douglas Gregor97628d62009-08-21 00:16:32 +00006614 // Add the function template specialization produced by template argument
6615 // deduction as a candidate.
6616 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006617 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006618 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006619 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006620 ActingContext, ObjectType, ObjectClassification, Args,
6621 CandidateSet, SuppressUserConversions, PartialOverloading,
6622 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006623}
6624
Douglas Gregor05155d82009-08-21 23:19:43 +00006625/// \brief Add a C++ function template specialization as a candidate
6626/// in the candidate set, using template argument deduction to produce
6627/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006628void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006629Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006630 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006631 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006632 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006633 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006634 bool SuppressUserConversions,
6635 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006636 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6637 return;
6638
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006639 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006640 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006641 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006642 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006643 // candidate functions in the usual way.113) A given name can refer to one
6644 // or more function templates and also to a set of overloaded non-template
6645 // functions. In such a case, the candidate functions generated from each
6646 // function template are combined with the set of non-template candidate
6647 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006648 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006649 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006650 ConversionSequenceList Conversions;
6651 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6652 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6653 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6654 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6655 Args, CandidateSet, Conversions,
6656 SuppressUserConversions);
6657 })) {
6658 OverloadCandidate &Candidate =
6659 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006660 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006661 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6662 Candidate.Viable = false;
6663 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006664 // Ignore the object argument if there is one, since we don't have an object
6665 // type.
6666 Candidate.IgnoreObjectArgument =
6667 isa<CXXMethodDecl>(Candidate.Function) &&
6668 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006669 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006670 if (Result == TDK_NonDependentConversionFailure)
6671 Candidate.FailureKind = ovl_fail_bad_conversion;
6672 else {
6673 Candidate.FailureKind = ovl_fail_bad_deduction;
6674 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6675 Info);
6676 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006677 return;
6678 }
Mike Stump11289f42009-09-09 15:08:12 +00006679
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006680 // Add the function template specialization produced by template argument
6681 // deduction as a candidate.
6682 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006683 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006684 SuppressUserConversions, PartialOverloading,
6685 /*AllowExplicit*/false, Conversions);
6686}
6687
6688/// Check that implicit conversion sequences can be formed for each argument
6689/// whose corresponding parameter has a non-dependent type, per DR1391's
6690/// [temp.deduct.call]p10.
6691bool Sema::CheckNonDependentConversions(
6692 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6693 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6694 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6695 CXXRecordDecl *ActingContext, QualType ObjectType,
6696 Expr::Classification ObjectClassification) {
6697 // FIXME: The cases in which we allow explicit conversions for constructor
6698 // arguments never consider calling a constructor template. It's not clear
6699 // that is correct.
6700 const bool AllowExplicit = false;
6701
6702 auto *FD = FunctionTemplate->getTemplatedDecl();
6703 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6704 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6705 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6706
6707 Conversions =
6708 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6709
6710 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006711 EnterExpressionEvaluationContext Unevaluated(
6712 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006713
6714 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6715 // require that, but this check should never result in a hard error, and
6716 // overload resolution is permitted to sidestep instantiations.
6717 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6718 !ObjectType.isNull()) {
6719 Conversions[0] = TryObjectArgumentInitialization(
6720 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6721 Method, ActingContext);
6722 if (Conversions[0].isBad())
6723 return true;
6724 }
6725
6726 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6727 ++I) {
6728 QualType ParamType = ParamTypes[I];
6729 if (!ParamType->isDependentType()) {
6730 Conversions[ThisConversions + I]
6731 = TryCopyInitialization(*this, Args[I], ParamType,
6732 SuppressUserConversions,
6733 /*InOverloadResolution=*/true,
6734 /*AllowObjCWritebackConversion=*/
6735 getLangOpts().ObjCAutoRefCount,
6736 AllowExplicit);
6737 if (Conversions[ThisConversions + I].isBad())
6738 return true;
6739 }
6740 }
6741
6742 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006743}
Mike Stump11289f42009-09-09 15:08:12 +00006744
Douglas Gregor4b60a152013-11-07 22:34:54 +00006745/// Determine whether this is an allowable conversion from the result
6746/// of an explicit conversion operator to the expected type, per C++
6747/// [over.match.conv]p1 and [over.match.ref]p1.
6748///
6749/// \param ConvType The return type of the conversion function.
6750///
6751/// \param ToType The type we are converting to.
6752///
6753/// \param AllowObjCPointerConversion Allow a conversion from one
6754/// Objective-C pointer to another.
6755///
6756/// \returns true if the conversion is allowable, false otherwise.
6757static bool isAllowableExplicitConversion(Sema &S,
6758 QualType ConvType, QualType ToType,
6759 bool AllowObjCPointerConversion) {
6760 QualType ToNonRefType = ToType.getNonReferenceType();
6761
6762 // Easy case: the types are the same.
6763 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6764 return true;
6765
6766 // Allow qualification conversions.
6767 bool ObjCLifetimeConversion;
6768 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6769 ObjCLifetimeConversion))
6770 return true;
6771
6772 // If we're not allowed to consider Objective-C pointer conversions,
6773 // we're done.
6774 if (!AllowObjCPointerConversion)
6775 return false;
6776
6777 // Is this an Objective-C pointer conversion?
6778 bool IncompatibleObjC = false;
6779 QualType ConvertedType;
6780 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6781 IncompatibleObjC);
6782}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006783
Douglas Gregora1f013e2008-11-07 22:36:19 +00006784/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006785/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006786/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006787/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006788/// (which may or may not be the same type as the type that the
6789/// conversion function produces).
6790void
6791Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006792 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006793 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006794 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006795 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006796 bool AllowObjCConversionOnExplicit,
6797 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006798 assert(!Conversion->getDescribedFunctionTemplate() &&
6799 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006800 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006801 if (!CandidateSet.isNewCandidate(Conversion))
6802 return;
6803
Richard Smith2a7d4812013-05-04 07:00:32 +00006804 // If the conversion function has an undeduced return type, trigger its
6805 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006806 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006807 if (DeduceReturnType(Conversion, From->getExprLoc()))
6808 return;
6809 ConvType = Conversion->getConversionType().getNonReferenceType();
6810 }
6811
Richard Smith67ef14f2017-09-26 18:37:55 +00006812 // If we don't allow any conversion of the result type, ignore conversion
6813 // functions that don't convert to exactly (possibly cv-qualified) T.
6814 if (!AllowResultConversion &&
6815 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6816 return;
6817
Richard Smith089c3162013-09-21 21:55:46 +00006818 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6819 // operator is only a candidate if its return type is the target type or
6820 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006821 if (Conversion->isExplicit() &&
6822 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006823 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006824 return;
6825
Douglas Gregor27381f32009-11-23 12:27:39 +00006826 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006827 EnterExpressionEvaluationContext Unevaluated(
6828 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006829
Douglas Gregora1f013e2008-11-07 22:36:19 +00006830 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006831 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006832 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006833 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006834 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006835 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006836 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006837 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006838 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006839 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006840 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006841
Douglas Gregor6affc782010-08-19 15:37:02 +00006842 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843 // For conversion functions, the function is considered to be a member of
6844 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006845 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006846 //
6847 // Determine the implicit conversion sequence for the implicit
6848 // object parameter.
6849 QualType ImplicitParamType = From->getType();
6850 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6851 ImplicitParamType = FromPtrType->getPointeeType();
6852 CXXRecordDecl *ConversionContext
6853 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Richard Smith0f59cb32015-12-18 21:45:41 +00006855 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6856 *this, CandidateSet.getLocation(), From->getType(),
6857 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
John McCall0d1da222010-01-12 00:44:57 +00006859 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006860 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006861 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006862 return;
6863 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006864
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006865 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006866 // derived to base as such conversions are given Conversion Rank. They only
6867 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6868 QualType FromCanon
6869 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6870 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006871 if (FromCanon == ToCanon ||
6872 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006873 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006874 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006875 return;
6876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Douglas Gregora1f013e2008-11-07 22:36:19 +00006878 // To determine what the conversion from the result of calling the
6879 // conversion function to the type we're eventually trying to
6880 // convert to (ToType), we need to synthesize a call to the
6881 // conversion function and attempt copy initialization from it. This
6882 // makes sure that we get the right semantics with respect to
6883 // lvalues/rvalues and the type. Fortunately, we can allocate this
6884 // call on the stack and we don't need its arguments to be
6885 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006886 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006887 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006888 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6889 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006890 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006891 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006892
Richard Smith48d24642011-07-13 22:53:21 +00006893 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006894 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006895 Candidate.Viable = false;
6896 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6897 return;
6898 }
6899
Richard Smith48d24642011-07-13 22:53:21 +00006900 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006901
Mike Stump11289f42009-09-09 15:08:12 +00006902 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006903 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6904 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006905 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006906 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006907 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006908 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006909 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006910 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006911 /*InOverloadResolution=*/false,
6912 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006913
John McCall0d1da222010-01-12 00:44:57 +00006914 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006915 case ImplicitConversionSequence::StandardConversion:
6916 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006917
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006918 // C++ [over.ics.user]p3:
6919 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006921 // shall have exact match rank.
6922 if (Conversion->getPrimaryTemplate() &&
6923 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6924 Candidate.Viable = false;
6925 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006926 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006928
Douglas Gregorcba72b12011-01-21 05:18:22 +00006929 // C++0x [dcl.init.ref]p5:
6930 // In the second case, if the reference is an rvalue reference and
6931 // the second standard conversion sequence of the user-defined
6932 // conversion sequence includes an lvalue-to-rvalue conversion, the
6933 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006935 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6936 Candidate.Viable = false;
6937 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006938 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006939 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006940 break;
6941
6942 case ImplicitConversionSequence::BadConversion:
6943 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006944 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006945 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006946
6947 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006948 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006949 "Can only end up with a standard conversion sequence or failure");
6950 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006951
Craig Topper5fc8fc22014-08-27 06:28:36 +00006952 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006953 Candidate.Viable = false;
6954 Candidate.FailureKind = ovl_fail_enable_if;
6955 Candidate.DeductionFailure.Data = FailedAttr;
6956 return;
6957 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006958}
6959
Douglas Gregor05155d82009-08-21 23:19:43 +00006960/// \brief Adds a conversion function template specialization
6961/// candidate to the overload set, using template argument deduction
6962/// to deduce the template arguments of the conversion function
6963/// template from the type that we are converting to (C++
6964/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006965void
Douglas Gregor05155d82009-08-21 23:19:43 +00006966Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006967 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006968 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006969 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006970 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006971 bool AllowObjCConversionOnExplicit,
6972 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006973 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6974 "Only conversion function templates permitted here");
6975
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006976 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6977 return;
6978
Craig Toppere6706e42012-09-19 02:26:47 +00006979 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006980 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006981 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006982 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006983 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006984 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006985 Candidate.FoundDecl = FoundDecl;
6986 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6987 Candidate.Viable = false;
6988 Candidate.FailureKind = ovl_fail_bad_deduction;
6989 Candidate.IsSurrogate = false;
6990 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006991 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006993 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006994 return;
6995 }
Mike Stump11289f42009-09-09 15:08:12 +00006996
Douglas Gregor05155d82009-08-21 23:19:43 +00006997 // Add the conversion function template specialization produced by
6998 // template argument deduction as a candidate.
6999 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007000 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007001 CandidateSet, AllowObjCConversionOnExplicit,
7002 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007003}
7004
Douglas Gregorab7897a2008-11-19 22:57:39 +00007005/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7006/// converts the given @c Object to a function pointer via the
7007/// conversion function @c Conversion, and then attempts to call it
7008/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7009/// the type of function that we'll eventually be calling.
7010void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007011 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007012 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007013 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007014 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007015 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007016 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007017 if (!CandidateSet.isNewCandidate(Conversion))
7018 return;
7019
Douglas Gregor27381f32009-11-23 12:27:39 +00007020 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007021 EnterExpressionEvaluationContext Unevaluated(
7022 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007023
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007024 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007025 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007026 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007027 Candidate.Surrogate = Conversion;
7028 Candidate.Viable = true;
7029 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007030 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007031 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007032
7033 // Determine the implicit conversion sequence for the implicit
7034 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007035 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7036 *this, CandidateSet.getLocation(), Object->getType(),
7037 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007038 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007039 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007040 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007041 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007042 return;
7043 }
7044
7045 // The first conversion is actually a user-defined conversion whose
7046 // first conversion is ObjectInit's standard conversion (which is
7047 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007048 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007049 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007050 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007051 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007052 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007053 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007054 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007055 = Candidate.Conversions[0].UserDefined.Before;
7056 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7057
Mike Stump11289f42009-09-09 15:08:12 +00007058 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007059 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007060
7061 // (C++ 13.3.2p2): A candidate function having fewer than m
7062 // parameters is viable only if it has an ellipsis in its parameter
7063 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007064 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007065 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007066 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007067 return;
7068 }
7069
7070 // Function types don't have any default arguments, so just check if
7071 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007072 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007073 // Not enough arguments.
7074 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007075 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007076 return;
7077 }
7078
7079 // Determine the implicit conversion sequences for each of the
7080 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007081 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007082 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007083 // (C++ 13.3.2p3): for F to be a viable function, there shall
7084 // exist for each argument an implicit conversion sequence
7085 // (13.3.3.1) that converts that argument to the corresponding
7086 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007087 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007088 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007089 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007090 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007091 /*InOverloadResolution=*/false,
7092 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007093 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007094 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007095 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007096 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007097 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007098 }
7099 } else {
7100 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7101 // argument for which there is no corresponding parameter is
7102 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007103 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007104 }
7105 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007106
Craig Topper5fc8fc22014-08-27 06:28:36 +00007107 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007108 Candidate.Viable = false;
7109 Candidate.FailureKind = ovl_fail_enable_if;
7110 Candidate.DeductionFailure.Data = FailedAttr;
7111 return;
7112 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007113}
7114
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007115/// \brief Add overload candidates for overloaded operators that are
7116/// member functions.
7117///
7118/// Add the overloaded operator candidates that are member functions
7119/// for the operator Op that was used in an operator expression such
7120/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7121/// CandidateSet will store the added overload candidates. (C++
7122/// [over.match.oper]).
7123void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7124 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007125 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007126 OverloadCandidateSet& CandidateSet,
7127 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007128 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7129
7130 // C++ [over.match.oper]p3:
7131 // For a unary operator @ with an operand of a type whose
7132 // cv-unqualified version is T1, and for a binary operator @ with
7133 // a left operand of a type whose cv-unqualified version is T1 and
7134 // a right operand of a type whose cv-unqualified version is T2,
7135 // three sets of candidate functions, designated member
7136 // candidates, non-member candidates and built-in candidates, are
7137 // constructed as follows:
7138 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007139
Richard Smith0feaf0c2013-04-20 12:41:22 +00007140 // -- If T1 is a complete class type or a class currently being
7141 // defined, the set of member candidates is the result of the
7142 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7143 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007144 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007145 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007146 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007147 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007148 // If the type is neither complete nor being defined, bail out now.
7149 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007150 return;
Mike Stump11289f42009-09-09 15:08:12 +00007151
John McCall27b18f82009-11-17 02:14:36 +00007152 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7153 LookupQualifiedName(Operators, T1Rec->getDecl());
7154 Operators.suppressDiagnostics();
7155
Mike Stump11289f42009-09-09 15:08:12 +00007156 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007157 OperEnd = Operators.end();
7158 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007159 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007160 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007161 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007162 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007163 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007164}
7165
Douglas Gregora11693b2008-11-12 17:17:38 +00007166/// AddBuiltinCandidate - Add a candidate for a built-in
7167/// operator. ResultTy and ParamTys are the result and parameter types
7168/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007169/// arguments being passed to the candidate. IsAssignmentOperator
7170/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007171/// operator. NumContextualBoolArguments is the number of arguments
7172/// (at the beginning of the argument list) that will be contextually
7173/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007174void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007175 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007176 bool IsAssignmentOperator,
7177 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007178 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007179 EnterExpressionEvaluationContext Unevaluated(
7180 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007181
Douglas Gregora11693b2008-11-12 17:17:38 +00007182 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007183 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007184 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7185 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007186 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007187 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007188 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007189
7190 // Determine the implicit conversion sequences for each of the
7191 // arguments.
7192 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007193 Candidate.ExplicitCallArguments = Args.size();
7194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007195 // C++ [over.match.oper]p4:
7196 // For the built-in assignment operators, conversions of the
7197 // left operand are restricted as follows:
7198 // -- no temporaries are introduced to hold the left operand, and
7199 // -- no user-defined conversions are applied to the left
7200 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007201 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007202 //
7203 // We block these conversions by turning off user-defined
7204 // conversions, since that is the only way that initialization of
7205 // a reference to a non-class type can occur from something that
7206 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007207 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007208 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007209 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007210 Candidate.Conversions[ArgIdx]
7211 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007212 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007213 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007214 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007215 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007216 /*InOverloadResolution=*/false,
7217 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007218 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007219 }
John McCall0d1da222010-01-12 00:44:57 +00007220 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007221 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007222 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007223 break;
7224 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007225 }
7226}
7227
Craig Toppercd7b0332013-07-01 06:29:40 +00007228namespace {
7229
Douglas Gregora11693b2008-11-12 17:17:38 +00007230/// BuiltinCandidateTypeSet - A set of types that will be used for the
7231/// candidate operator functions for built-in operators (C++
7232/// [over.built]). The types are separated into pointer types and
7233/// enumeration types.
7234class BuiltinCandidateTypeSet {
7235 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007236 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7237 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007238
7239 /// PointerTypes - The set of pointer types that will be used in the
7240 /// built-in candidates.
7241 TypeSet PointerTypes;
7242
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007243 /// MemberPointerTypes - The set of member pointer types that will be
7244 /// used in the built-in candidates.
7245 TypeSet MemberPointerTypes;
7246
Douglas Gregora11693b2008-11-12 17:17:38 +00007247 /// EnumerationTypes - The set of enumeration types that will be
7248 /// used in the built-in candidates.
7249 TypeSet EnumerationTypes;
7250
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007251 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007252 /// candidates.
7253 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007254
7255 /// \brief A flag indicating non-record types are viable candidates
7256 bool HasNonRecordTypes;
7257
7258 /// \brief A flag indicating whether either arithmetic or enumeration types
7259 /// were present in the candidate set.
7260 bool HasArithmeticOrEnumeralTypes;
7261
Douglas Gregor80af3132011-05-21 23:15:46 +00007262 /// \brief A flag indicating whether the nullptr type was present in the
7263 /// candidate set.
7264 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007265
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007266 /// Sema - The semantic analysis instance where we are building the
7267 /// candidate type set.
7268 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007269
Douglas Gregora11693b2008-11-12 17:17:38 +00007270 /// Context - The AST context in which we will build the type sets.
7271 ASTContext &Context;
7272
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007273 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7274 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007275 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007276
7277public:
7278 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007279 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007280
Mike Stump11289f42009-09-09 15:08:12 +00007281 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007282 : HasNonRecordTypes(false),
7283 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007284 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007285 SemaRef(SemaRef),
7286 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007287
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007289 SourceLocation Loc,
7290 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007291 bool AllowExplicitConversions,
7292 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007293
7294 /// pointer_begin - First pointer type found;
7295 iterator pointer_begin() { return PointerTypes.begin(); }
7296
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007297 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007298 iterator pointer_end() { return PointerTypes.end(); }
7299
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007300 /// member_pointer_begin - First member pointer type found;
7301 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7302
7303 /// member_pointer_end - Past the last member pointer type found;
7304 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7305
Douglas Gregora11693b2008-11-12 17:17:38 +00007306 /// enumeration_begin - First enumeration type found;
7307 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7308
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007309 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007310 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007312 iterator vector_begin() { return VectorTypes.begin(); }
7313 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007314
7315 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7316 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007317 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007318};
7319
Craig Toppercd7b0332013-07-01 06:29:40 +00007320} // end anonymous namespace
7321
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007322/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007323/// the set of pointer types along with any more-qualified variants of
7324/// that type. For example, if @p Ty is "int const *", this routine
7325/// will add "int const *", "int const volatile *", "int const
7326/// restrict *", and "int const volatile restrict *" to the set of
7327/// pointer types. Returns true if the add of @p Ty itself succeeded,
7328/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007329///
7330/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007331bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007332BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7333 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007334
Douglas Gregora11693b2008-11-12 17:17:38 +00007335 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007336 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007337 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007338
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007339 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007340 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007341 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007342 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007343 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7344 PointeeTy = PTy->getPointeeType();
7345 buildObjCPtr = true;
7346 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007347 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007348 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007349
Sebastian Redl4990a632009-11-18 20:39:26 +00007350 // Don't add qualified variants of arrays. For one, they're not allowed
7351 // (the qualifier would sink to the element type), and for another, the
7352 // only overload situation where it matters is subscript or pointer +- int,
7353 // and those shouldn't have qualifier variants anyway.
7354 if (PointeeTy->isArrayType())
7355 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007356
John McCall8ccfcb52009-09-24 19:53:00 +00007357 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007358 bool hasVolatile = VisibleQuals.hasVolatile();
7359 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007360
John McCall8ccfcb52009-09-24 19:53:00 +00007361 // Iterate through all strict supersets of BaseCVR.
7362 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7363 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007364 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007365 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007366
Douglas Gregor5bee2582012-06-04 00:15:09 +00007367 // Skip over restrict if no restrict found anywhere in the types, or if
7368 // the type cannot be restrict-qualified.
7369 if ((CVR & Qualifiers::Restrict) &&
7370 (!hasRestrict ||
7371 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7372 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007373
Douglas Gregor5bee2582012-06-04 00:15:09 +00007374 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007375 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007376
Douglas Gregor5bee2582012-06-04 00:15:09 +00007377 // Build qualified pointer type.
7378 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007379 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007380 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007381 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007382 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007383
Douglas Gregor5bee2582012-06-04 00:15:09 +00007384 // Insert qualified pointer type.
7385 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007386 }
7387
7388 return true;
7389}
7390
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007391/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7392/// to the set of pointer types along with any more-qualified variants of
7393/// that type. For example, if @p Ty is "int const *", this routine
7394/// will add "int const *", "int const volatile *", "int const
7395/// restrict *", and "int const volatile restrict *" to the set of
7396/// pointer types. Returns true if the add of @p Ty itself succeeded,
7397/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007398///
7399/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007400bool
7401BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7402 QualType Ty) {
7403 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007404 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007405 return false;
7406
John McCall8ccfcb52009-09-24 19:53:00 +00007407 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7408 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007409
John McCall8ccfcb52009-09-24 19:53:00 +00007410 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007411 // Don't add qualified variants of arrays. For one, they're not allowed
7412 // (the qualifier would sink to the element type), and for another, the
7413 // only overload situation where it matters is subscript or pointer +- int,
7414 // and those shouldn't have qualifier variants anyway.
7415 if (PointeeTy->isArrayType())
7416 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007417 const Type *ClassTy = PointerTy->getClass();
7418
7419 // Iterate through all strict supersets of the pointee type's CVR
7420 // qualifiers.
7421 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7422 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7423 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007424
John McCall8ccfcb52009-09-24 19:53:00 +00007425 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007426 MemberPointerTypes.insert(
7427 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007428 }
7429
7430 return true;
7431}
7432
Douglas Gregora11693b2008-11-12 17:17:38 +00007433/// AddTypesConvertedFrom - Add each of the types to which the type @p
7434/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007435/// primarily interested in pointer types and enumeration types. We also
7436/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007437/// AllowUserConversions is true if we should look at the conversion
7438/// functions of a class type, and AllowExplicitConversions if we
7439/// should also include the explicit conversion functions of a class
7440/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007441void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007442BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007443 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007444 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007445 bool AllowExplicitConversions,
7446 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007447 // Only deal with canonical types.
7448 Ty = Context.getCanonicalType(Ty);
7449
7450 // Look through reference types; they aren't part of the type of an
7451 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007452 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007453 Ty = RefTy->getPointeeType();
7454
John McCall33ddac02011-01-19 10:06:00 +00007455 // If we're dealing with an array type, decay to the pointer.
7456 if (Ty->isArrayType())
7457 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7458
7459 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007460 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007461
Chandler Carruth00a38332010-12-13 01:44:01 +00007462 // Flag if we ever add a non-record type.
7463 const RecordType *TyRec = Ty->getAs<RecordType>();
7464 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7465
Chandler Carruth00a38332010-12-13 01:44:01 +00007466 // Flag if we encounter an arithmetic type.
7467 HasArithmeticOrEnumeralTypes =
7468 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7469
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007470 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7471 PointerTypes.insert(Ty);
7472 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007473 // Insert our type, and its more-qualified variants, into the set
7474 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007475 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007476 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007477 } else if (Ty->isMemberPointerType()) {
7478 // Member pointers are far easier, since the pointee can't be converted.
7479 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7480 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007481 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007482 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007483 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007484 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007485 // We treat vector types as arithmetic types in many contexts as an
7486 // extension.
7487 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007488 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007489 } else if (Ty->isNullPtrType()) {
7490 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007491 } else if (AllowUserConversions && TyRec) {
7492 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007493 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007494 return;
Mike Stump11289f42009-09-09 15:08:12 +00007495
Chandler Carruth00a38332010-12-13 01:44:01 +00007496 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007497 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007498 if (isa<UsingShadowDecl>(D))
7499 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007500
Chandler Carruth00a38332010-12-13 01:44:01 +00007501 // Skip conversion function templates; they don't tell us anything
7502 // about which builtin types we can convert to.
7503 if (isa<FunctionTemplateDecl>(D))
7504 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007505
Chandler Carruth00a38332010-12-13 01:44:01 +00007506 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7507 if (AllowExplicitConversions || !Conv->isExplicit()) {
7508 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7509 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007510 }
7511 }
7512 }
7513}
7514
Douglas Gregor84605ae2009-08-24 13:43:27 +00007515/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7516/// the volatile- and non-volatile-qualified assignment operators for the
7517/// given type to the candidate set.
7518static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7519 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007520 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007521 OverloadCandidateSet &CandidateSet) {
7522 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007523
Douglas Gregor84605ae2009-08-24 13:43:27 +00007524 // T& operator=(T&, T)
7525 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7526 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007527 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007528 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007529
Douglas Gregor84605ae2009-08-24 13:43:27 +00007530 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7531 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007532 ParamTypes[0]
7533 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007534 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007535 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007536 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007537 }
7538}
Mike Stump11289f42009-09-09 15:08:12 +00007539
Sebastian Redl1054fae2009-10-25 17:03:50 +00007540/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7541/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007542static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7543 Qualifiers VRQuals;
7544 const RecordType *TyRec;
7545 if (const MemberPointerType *RHSMPType =
7546 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007547 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007548 else
7549 TyRec = ArgExpr->getType()->getAs<RecordType>();
7550 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007551 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007552 VRQuals.addVolatile();
7553 VRQuals.addRestrict();
7554 return VRQuals;
7555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007557 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007558 if (!ClassDecl->hasDefinition())
7559 return VRQuals;
7560
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007561 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007562 if (isa<UsingShadowDecl>(D))
7563 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7564 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007565 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7566 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7567 CanTy = ResTypeRef->getPointeeType();
7568 // Need to go down the pointer/mempointer chain and add qualifiers
7569 // as see them.
7570 bool done = false;
7571 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007572 if (CanTy.isRestrictQualified())
7573 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007574 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7575 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007576 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007577 CanTy->getAs<MemberPointerType>())
7578 CanTy = ResTypeMPtr->getPointeeType();
7579 else
7580 done = true;
7581 if (CanTy.isVolatileQualified())
7582 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007583 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7584 return VRQuals;
7585 }
7586 }
7587 }
7588 return VRQuals;
7589}
John McCall52872982010-11-13 05:51:15 +00007590
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007591namespace {
John McCall52872982010-11-13 05:51:15 +00007592
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007593/// \brief Helper class to manage the addition of builtin operator overload
7594/// candidates. It provides shared state and utility methods used throughout
7595/// the process, as well as a helper method to add each group of builtin
7596/// operator overloads from the standard to a candidate set.
7597class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007598 // Common instance state available to all overload candidate addition methods.
7599 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007600 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007601 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007602 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007603 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007604 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007605
Chandler Carruthc6586e52010-12-12 10:35:00 +00007606 // Define some constants used to index and iterate over the arithemetic types
7607 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007608 // The "promoted arithmetic types" are the arithmetic
7609 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007610 static const unsigned FirstIntegralType = 4;
7611 static const unsigned LastIntegralType = 21;
7612 static const unsigned FirstPromotedIntegralType = 4,
7613 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007614 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007615 LastPromotedArithmeticType = 12;
7616 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007617
Chandler Carruthc6586e52010-12-12 10:35:00 +00007618 /// \brief Get the canonical type for a given arithmetic type index.
7619 CanQualType getArithmeticType(unsigned index) {
7620 assert(index < NumArithmeticTypes);
7621 static CanQualType ASTContext::* const
7622 ArithmeticTypes[NumArithmeticTypes] = {
7623 // Start of promoted types.
7624 &ASTContext::FloatTy,
7625 &ASTContext::DoubleTy,
7626 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007627 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007628
Chandler Carruthc6586e52010-12-12 10:35:00 +00007629 // Start of integral types.
7630 &ASTContext::IntTy,
7631 &ASTContext::LongTy,
7632 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007633 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007634 &ASTContext::UnsignedIntTy,
7635 &ASTContext::UnsignedLongTy,
7636 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007637 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007638 // End of promoted types.
7639
7640 &ASTContext::BoolTy,
7641 &ASTContext::CharTy,
7642 &ASTContext::WCharTy,
7643 &ASTContext::Char16Ty,
7644 &ASTContext::Char32Ty,
7645 &ASTContext::SignedCharTy,
7646 &ASTContext::ShortTy,
7647 &ASTContext::UnsignedCharTy,
7648 &ASTContext::UnsignedShortTy,
7649 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007650 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007651 };
7652 return S.Context.*ArithmeticTypes[index];
7653 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007655 /// \brief Helper method to factor out the common pattern of adding overloads
7656 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007657 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007658 bool HasVolatile,
7659 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660 QualType ParamTypes[2] = {
7661 S.Context.getLValueReferenceType(CandidateTy),
7662 S.Context.IntTy
7663 };
7664
7665 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667
7668 // Use a heuristic to reduce number of builtin candidates in the set:
7669 // add volatile version only if there are conversions to a volatile type.
7670 if (HasVolatile) {
7671 ParamTypes[0] =
7672 S.Context.getLValueReferenceType(
7673 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007674 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007675 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007676
Douglas Gregor5bee2582012-06-04 00:15:09 +00007677 // Add restrict version only if there are conversions to a restrict type
7678 // and our candidate type is a non-restrict-qualified pointer.
7679 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7680 !CandidateTy.isRestrictQualified()) {
7681 ParamTypes[0]
7682 = S.Context.getLValueReferenceType(
7683 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007684 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007685
Douglas Gregor5bee2582012-06-04 00:15:09 +00007686 if (HasVolatile) {
7687 ParamTypes[0]
7688 = S.Context.getLValueReferenceType(
7689 S.Context.getCVRQualifiedType(CandidateTy,
7690 (Qualifiers::Volatile |
7691 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007692 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007693 }
7694 }
7695
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696 }
7697
7698public:
7699 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007700 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007701 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007702 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007703 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007704 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007705 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007707 HasArithmeticOrEnumeralCandidateType(
7708 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 CandidateTypes(CandidateTypes),
7710 CandidateSet(CandidateSet) {
7711 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007712 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007714 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007715 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007716 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007717 assert(getArithmeticType(FirstPromotedArithmeticType)
7718 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007719 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007720 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007721 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007722 "Invalid last promoted arithmetic type");
7723 }
7724
7725 // C++ [over.built]p3:
7726 //
7727 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7728 // is either volatile or empty, there exist candidate operator
7729 // functions of the form
7730 //
7731 // VQ T& operator++(VQ T&);
7732 // T operator++(VQ T&, int);
7733 //
7734 // C++ [over.built]p4:
7735 //
7736 // For every pair (T, VQ), where T is an arithmetic type other
7737 // than bool, and VQ is either volatile or empty, there exist
7738 // candidate operator functions of the form
7739 //
7740 // VQ T& operator--(VQ T&);
7741 // T operator--(VQ T&, int);
7742 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007743 if (!HasArithmeticOrEnumeralCandidateType)
7744 return;
7745
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7747 Arith < NumArithmeticTypes; ++Arith) {
7748 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007749 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007750 VisibleTypeConversionsQuals.hasVolatile(),
7751 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007752 }
7753 }
7754
7755 // C++ [over.built]p5:
7756 //
7757 // For every pair (T, VQ), where T is a cv-qualified or
7758 // cv-unqualified object type, and VQ is either volatile or
7759 // empty, there exist candidate operator functions of the form
7760 //
7761 // T*VQ& operator++(T*VQ&);
7762 // T*VQ& operator--(T*VQ&);
7763 // T* operator++(T*VQ&, int);
7764 // T* operator--(T*VQ&, int);
7765 void addPlusPlusMinusMinusPointerOverloads() {
7766 for (BuiltinCandidateTypeSet::iterator
7767 Ptr = CandidateTypes[0].pointer_begin(),
7768 PtrEnd = CandidateTypes[0].pointer_end();
7769 Ptr != PtrEnd; ++Ptr) {
7770 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007771 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007772 continue;
7773
7774 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007775 (!(*Ptr).isVolatileQualified() &&
7776 VisibleTypeConversionsQuals.hasVolatile()),
7777 (!(*Ptr).isRestrictQualified() &&
7778 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007779 }
7780 }
7781
7782 // C++ [over.built]p6:
7783 // For every cv-qualified or cv-unqualified object type T, there
7784 // exist candidate operator functions of the form
7785 //
7786 // T& operator*(T*);
7787 //
7788 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007790 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007791 // T& operator*(T*);
7792 void addUnaryStarPointerOverloads() {
7793 for (BuiltinCandidateTypeSet::iterator
7794 Ptr = CandidateTypes[0].pointer_begin(),
7795 PtrEnd = CandidateTypes[0].pointer_end();
7796 Ptr != PtrEnd; ++Ptr) {
7797 QualType ParamTy = *Ptr;
7798 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007799 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7800 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007801
Douglas Gregor02824322011-01-26 19:30:28 +00007802 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7803 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7804 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805
George Burgess IVc07c3892017-06-08 18:19:25 +00007806 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007807 }
7808 }
7809
7810 // C++ [over.built]p9:
7811 // For every promoted arithmetic type T, there exist candidate
7812 // operator functions of the form
7813 //
7814 // T operator+(T);
7815 // T operator-(T);
7816 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007817 if (!HasArithmeticOrEnumeralCandidateType)
7818 return;
7819
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007820 for (unsigned Arith = FirstPromotedArithmeticType;
7821 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007822 QualType ArithTy = getArithmeticType(Arith);
George Burgess IVc07c3892017-06-08 18:19:25 +00007823 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007824 }
7825
7826 // Extension: We also add these operators for vector types.
7827 for (BuiltinCandidateTypeSet::iterator
7828 Vec = CandidateTypes[0].vector_begin(),
7829 VecEnd = CandidateTypes[0].vector_end();
7830 Vec != VecEnd; ++Vec) {
7831 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007832 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833 }
7834 }
7835
7836 // C++ [over.built]p8:
7837 // For every type T, there exist candidate operator functions of
7838 // the form
7839 //
7840 // T* operator+(T*);
7841 void addUnaryPlusPointerOverloads() {
7842 for (BuiltinCandidateTypeSet::iterator
7843 Ptr = CandidateTypes[0].pointer_begin(),
7844 PtrEnd = CandidateTypes[0].pointer_end();
7845 Ptr != PtrEnd; ++Ptr) {
7846 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007847 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 }
7849 }
7850
7851 // C++ [over.built]p10:
7852 // For every promoted integral type T, there exist candidate
7853 // operator functions of the form
7854 //
7855 // T operator~(T);
7856 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007857 if (!HasArithmeticOrEnumeralCandidateType)
7858 return;
7859
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007860 for (unsigned Int = FirstPromotedIntegralType;
7861 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007862 QualType IntTy = getArithmeticType(Int);
George Burgess IVc07c3892017-06-08 18:19:25 +00007863 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007864 }
7865
7866 // Extension: We also add this operator for vector types.
7867 for (BuiltinCandidateTypeSet::iterator
7868 Vec = CandidateTypes[0].vector_begin(),
7869 VecEnd = CandidateTypes[0].vector_end();
7870 Vec != VecEnd; ++Vec) {
7871 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007872 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007873 }
7874 }
7875
7876 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007877 // For every pointer to member type T or type std::nullptr_t, there
7878 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 //
7880 // bool operator==(T,T);
7881 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007882 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007883 /// Set of (canonical) types that we've already handled.
7884 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7885
Richard Smithe54c3072013-05-05 15:51:06 +00007886 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887 for (BuiltinCandidateTypeSet::iterator
7888 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7889 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7890 MemPtr != MemPtrEnd;
7891 ++MemPtr) {
7892 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007893 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007894 continue;
7895
7896 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007897 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007898 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007899
7900 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7901 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7902 if (AddedTypes.insert(NullPtrTy).second) {
7903 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007904 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007905 }
7906 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007907 }
7908 }
7909
7910 // C++ [over.built]p15:
7911 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007912 // For every T, where T is an enumeration type or a pointer type,
7913 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007914 //
7915 // bool operator<(T, T);
7916 // bool operator>(T, T);
7917 // bool operator<=(T, T);
7918 // bool operator>=(T, T);
7919 // bool operator==(T, T);
7920 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007921 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007922 // C++ [over.match.oper]p3:
7923 // [...]the built-in candidates include all of the candidate operator
7924 // functions defined in 13.6 that, compared to the given operator, [...]
7925 // do not have the same parameter-type-list as any non-template non-member
7926 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007927 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007928 // Note that in practice, this only affects enumeration types because there
7929 // aren't any built-in candidates of record type, and a user-defined operator
7930 // must have an operand of record or enumeration type. Also, the only other
7931 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007932 // cannot be overloaded for enumeration types, so this is the only place
7933 // where we must suppress candidates like this.
7934 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7935 UserDefinedBinaryOperators;
7936
Richard Smithe54c3072013-05-05 15:51:06 +00007937 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007938 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7939 CandidateTypes[ArgIdx].enumeration_end()) {
7940 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7941 CEnd = CandidateSet.end();
7942 C != CEnd; ++C) {
7943 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7944 continue;
7945
Eli Friedman14f082b2012-09-18 21:52:24 +00007946 if (C->Function->isFunctionTemplateSpecialization())
7947 continue;
7948
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007949 QualType FirstParamType =
7950 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7951 QualType SecondParamType =
7952 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7953
7954 // Skip if either parameter isn't of enumeral type.
7955 if (!FirstParamType->isEnumeralType() ||
7956 !SecondParamType->isEnumeralType())
7957 continue;
7958
7959 // Add this operator to the set of known user-defined operators.
7960 UserDefinedBinaryOperators.insert(
7961 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7962 S.Context.getCanonicalType(SecondParamType)));
7963 }
7964 }
7965 }
7966
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007967 /// Set of (canonical) types that we've already handled.
7968 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7969
Richard Smithe54c3072013-05-05 15:51:06 +00007970 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007971 for (BuiltinCandidateTypeSet::iterator
7972 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7973 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7974 Ptr != PtrEnd; ++Ptr) {
7975 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007976 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 continue;
7978
7979 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007980 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007981 }
7982 for (BuiltinCandidateTypeSet::iterator
7983 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7984 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7985 Enum != EnumEnd; ++Enum) {
7986 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7987
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007988 // Don't add the same builtin candidate twice, or if a user defined
7989 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007990 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007991 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7992 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 continue;
7994
7995 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00007996 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007997 }
7998 }
7999 }
8000
8001 // C++ [over.built]p13:
8002 //
8003 // For every cv-qualified or cv-unqualified object type T
8004 // there exist candidate operator functions of the form
8005 //
8006 // T* operator+(T*, ptrdiff_t);
8007 // T& operator[](T*, ptrdiff_t); [BELOW]
8008 // T* operator-(T*, ptrdiff_t);
8009 // T* operator+(ptrdiff_t, T*);
8010 // T& operator[](ptrdiff_t, T*); [BELOW]
8011 //
8012 // C++ [over.built]p14:
8013 //
8014 // For every T, where T is a pointer to object type, there
8015 // exist candidate operator functions of the form
8016 //
8017 // ptrdiff_t operator-(T, T);
8018 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8019 /// Set of (canonical) types that we've already handled.
8020 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8021
8022 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008023 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008024 S.Context.getPointerDiffType(),
8025 S.Context.getPointerDiffType(),
8026 };
8027 for (BuiltinCandidateTypeSet::iterator
8028 Ptr = CandidateTypes[Arg].pointer_begin(),
8029 PtrEnd = CandidateTypes[Arg].pointer_end();
8030 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008031 QualType PointeeTy = (*Ptr)->getPointeeType();
8032 if (!PointeeTy->isObjectType())
8033 continue;
8034
Eric Christopher9207a522015-08-21 16:24:01 +00008035 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008036 if (Arg == 0 || Op == OO_Plus) {
8037 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8038 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008039 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 }
8041 if (Op == OO_Minus) {
8042 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008043 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008044 continue;
8045
8046 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008047 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008048 }
8049 }
8050 }
8051 }
8052
8053 // C++ [over.built]p12:
8054 //
8055 // For every pair of promoted arithmetic types L and R, there
8056 // exist candidate operator functions of the form
8057 //
8058 // LR operator*(L, R);
8059 // LR operator/(L, R);
8060 // LR operator+(L, R);
8061 // LR operator-(L, R);
8062 // bool operator<(L, R);
8063 // bool operator>(L, R);
8064 // bool operator<=(L, R);
8065 // bool operator>=(L, R);
8066 // bool operator==(L, R);
8067 // bool operator!=(L, R);
8068 //
8069 // where LR is the result of the usual arithmetic conversions
8070 // between types L and R.
8071 //
8072 // C++ [over.built]p24:
8073 //
8074 // For every pair of promoted arithmetic types L and R, there exist
8075 // candidate operator functions of the form
8076 //
8077 // LR operator?(bool, L, R);
8078 //
8079 // where LR is the result of the usual arithmetic conversions
8080 // between types L and R.
8081 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008082 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008083 if (!HasArithmeticOrEnumeralCandidateType)
8084 return;
8085
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 for (unsigned Left = FirstPromotedArithmeticType;
8087 Left < LastPromotedArithmeticType; ++Left) {
8088 for (unsigned Right = FirstPromotedArithmeticType;
8089 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008090 QualType LandR[2] = { getArithmeticType(Left),
8091 getArithmeticType(Right) };
George Burgess IVc07c3892017-06-08 18:19:25 +00008092 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008093 }
8094 }
8095
8096 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8097 // conditional operator for vector types.
8098 for (BuiltinCandidateTypeSet::iterator
8099 Vec1 = CandidateTypes[0].vector_begin(),
8100 Vec1End = CandidateTypes[0].vector_end();
8101 Vec1 != Vec1End; ++Vec1) {
8102 for (BuiltinCandidateTypeSet::iterator
8103 Vec2 = CandidateTypes[1].vector_begin(),
8104 Vec2End = CandidateTypes[1].vector_end();
8105 Vec2 != Vec2End; ++Vec2) {
8106 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008107 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008108 }
8109 }
8110 }
8111
8112 // C++ [over.built]p17:
8113 //
8114 // For every pair of promoted integral types L and R, there
8115 // exist candidate operator functions of the form
8116 //
8117 // LR operator%(L, R);
8118 // LR operator&(L, R);
8119 // LR operator^(L, R);
8120 // LR operator|(L, R);
8121 // L operator<<(L, R);
8122 // L operator>>(L, R);
8123 //
8124 // where LR is the result of the usual arithmetic conversions
8125 // between types L and R.
8126 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008127 if (!HasArithmeticOrEnumeralCandidateType)
8128 return;
8129
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008130 for (unsigned Left = FirstPromotedIntegralType;
8131 Left < LastPromotedIntegralType; ++Left) {
8132 for (unsigned Right = FirstPromotedIntegralType;
8133 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008134 QualType LandR[2] = { getArithmeticType(Left),
8135 getArithmeticType(Right) };
George Burgess IVc07c3892017-06-08 18:19:25 +00008136 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 }
8138 }
8139 }
8140
8141 // C++ [over.built]p20:
8142 //
8143 // For every pair (T, VQ), where T is an enumeration or
8144 // pointer to member type and VQ is either volatile or
8145 // empty, there exist candidate operator functions of the form
8146 //
8147 // VQ T& operator=(VQ T&, T);
8148 void addAssignmentMemberPointerOrEnumeralOverloads() {
8149 /// Set of (canonical) types that we've already handled.
8150 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8151
8152 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8153 for (BuiltinCandidateTypeSet::iterator
8154 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8155 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8156 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008157 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008158 continue;
8159
Richard Smithe54c3072013-05-05 15:51:06 +00008160 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008161 }
8162
8163 for (BuiltinCandidateTypeSet::iterator
8164 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8165 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8166 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008167 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008168 continue;
8169
Richard Smithe54c3072013-05-05 15:51:06 +00008170 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008171 }
8172 }
8173 }
8174
8175 // C++ [over.built]p19:
8176 //
8177 // For every pair (T, VQ), where T is any type and VQ is either
8178 // volatile or empty, there exist candidate operator functions
8179 // of the form
8180 //
8181 // T*VQ& operator=(T*VQ&, T*);
8182 //
8183 // C++ [over.built]p21:
8184 //
8185 // For every pair (T, VQ), where T is a cv-qualified or
8186 // cv-unqualified object type and VQ is either volatile or
8187 // empty, there exist candidate operator functions of the form
8188 //
8189 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8190 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8191 void addAssignmentPointerOverloads(bool isEqualOp) {
8192 /// Set of (canonical) types that we've already handled.
8193 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8194
8195 for (BuiltinCandidateTypeSet::iterator
8196 Ptr = CandidateTypes[0].pointer_begin(),
8197 PtrEnd = CandidateTypes[0].pointer_end();
8198 Ptr != PtrEnd; ++Ptr) {
8199 // If this is operator=, keep track of the builtin candidates we added.
8200 if (isEqualOp)
8201 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008202 else if (!(*Ptr)->getPointeeType()->isObjectType())
8203 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008204
8205 // non-volatile version
8206 QualType ParamTypes[2] = {
8207 S.Context.getLValueReferenceType(*Ptr),
8208 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8209 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008210 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 /*IsAssigmentOperator=*/ isEqualOp);
8212
Douglas Gregor5bee2582012-06-04 00:15:09 +00008213 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8214 VisibleTypeConversionsQuals.hasVolatile();
8215 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 // volatile version
8217 ParamTypes[0] =
8218 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008219 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008220 /*IsAssigmentOperator=*/isEqualOp);
8221 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008222
Douglas Gregor5bee2582012-06-04 00:15:09 +00008223 if (!(*Ptr).isRestrictQualified() &&
8224 VisibleTypeConversionsQuals.hasRestrict()) {
8225 // restrict version
8226 ParamTypes[0]
8227 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008228 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008229 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008230
Douglas Gregor5bee2582012-06-04 00:15:09 +00008231 if (NeedVolatile) {
8232 // volatile restrict version
8233 ParamTypes[0]
8234 = S.Context.getLValueReferenceType(
8235 S.Context.getCVRQualifiedType(*Ptr,
8236 (Qualifiers::Volatile |
8237 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008238 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008239 /*IsAssigmentOperator=*/isEqualOp);
8240 }
8241 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008242 }
8243
8244 if (isEqualOp) {
8245 for (BuiltinCandidateTypeSet::iterator
8246 Ptr = CandidateTypes[1].pointer_begin(),
8247 PtrEnd = CandidateTypes[1].pointer_end();
8248 Ptr != PtrEnd; ++Ptr) {
8249 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008250 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251 continue;
8252
Chandler Carruth8e543b32010-12-12 08:17:55 +00008253 QualType ParamTypes[2] = {
8254 S.Context.getLValueReferenceType(*Ptr),
8255 *Ptr,
8256 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008257
8258 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008259 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008260 /*IsAssigmentOperator=*/true);
8261
Douglas Gregor5bee2582012-06-04 00:15:09 +00008262 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8263 VisibleTypeConversionsQuals.hasVolatile();
8264 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008265 // volatile version
8266 ParamTypes[0] =
8267 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008268 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008269 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008270 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008271
Douglas Gregor5bee2582012-06-04 00:15:09 +00008272 if (!(*Ptr).isRestrictQualified() &&
8273 VisibleTypeConversionsQuals.hasRestrict()) {
8274 // restrict version
8275 ParamTypes[0]
8276 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008277 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008278 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008279
Douglas Gregor5bee2582012-06-04 00:15:09 +00008280 if (NeedVolatile) {
8281 // volatile restrict version
8282 ParamTypes[0]
8283 = S.Context.getLValueReferenceType(
8284 S.Context.getCVRQualifiedType(*Ptr,
8285 (Qualifiers::Volatile |
8286 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008287 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008288 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008289 }
8290 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008291 }
8292 }
8293 }
8294
8295 // C++ [over.built]p18:
8296 //
8297 // For every triple (L, VQ, R), where L is an arithmetic type,
8298 // VQ is either volatile or empty, and R is a promoted
8299 // arithmetic type, there exist candidate operator functions of
8300 // the form
8301 //
8302 // VQ L& operator=(VQ L&, R);
8303 // VQ L& operator*=(VQ L&, R);
8304 // VQ L& operator/=(VQ L&, R);
8305 // VQ L& operator+=(VQ L&, R);
8306 // VQ L& operator-=(VQ L&, R);
8307 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008308 if (!HasArithmeticOrEnumeralCandidateType)
8309 return;
8310
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008311 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8312 for (unsigned Right = FirstPromotedArithmeticType;
8313 Right < LastPromotedArithmeticType; ++Right) {
8314 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008315 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008316
8317 // Add this built-in operator as a candidate (VQ is empty).
8318 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008319 S.Context.getLValueReferenceType(getArithmeticType(Left));
George Burgess IVc07c3892017-06-08 18:19:25 +00008320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008321 /*IsAssigmentOperator=*/isEqualOp);
8322
8323 // Add this built-in operator as a candidate (VQ is 'volatile').
8324 if (VisibleTypeConversionsQuals.hasVolatile()) {
8325 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008326 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008327 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008328 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008329 /*IsAssigmentOperator=*/isEqualOp);
8330 }
8331 }
8332 }
8333
8334 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8335 for (BuiltinCandidateTypeSet::iterator
8336 Vec1 = CandidateTypes[0].vector_begin(),
8337 Vec1End = CandidateTypes[0].vector_end();
8338 Vec1 != Vec1End; ++Vec1) {
8339 for (BuiltinCandidateTypeSet::iterator
8340 Vec2 = CandidateTypes[1].vector_begin(),
8341 Vec2End = CandidateTypes[1].vector_end();
8342 Vec2 != Vec2End; ++Vec2) {
8343 QualType ParamTypes[2];
8344 ParamTypes[1] = *Vec2;
8345 // Add this built-in operator as a candidate (VQ is empty).
8346 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008347 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008348 /*IsAssigmentOperator=*/isEqualOp);
8349
8350 // Add this built-in operator as a candidate (VQ is 'volatile').
8351 if (VisibleTypeConversionsQuals.hasVolatile()) {
8352 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8353 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008355 /*IsAssigmentOperator=*/isEqualOp);
8356 }
8357 }
8358 }
8359 }
8360
8361 // C++ [over.built]p22:
8362 //
8363 // For every triple (L, VQ, R), where L is an integral type, VQ
8364 // is either volatile or empty, and R is a promoted integral
8365 // type, there exist candidate operator functions of the form
8366 //
8367 // VQ L& operator%=(VQ L&, R);
8368 // VQ L& operator<<=(VQ L&, R);
8369 // VQ L& operator>>=(VQ L&, R);
8370 // VQ L& operator&=(VQ L&, R);
8371 // VQ L& operator^=(VQ L&, R);
8372 // VQ L& operator|=(VQ L&, R);
8373 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008374 if (!HasArithmeticOrEnumeralCandidateType)
8375 return;
8376
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008377 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8378 for (unsigned Right = FirstPromotedIntegralType;
8379 Right < LastPromotedIntegralType; ++Right) {
8380 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008381 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382
8383 // Add this built-in operator as a candidate (VQ is empty).
8384 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008385 S.Context.getLValueReferenceType(getArithmeticType(Left));
George Burgess IVc07c3892017-06-08 18:19:25 +00008386 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008387 if (VisibleTypeConversionsQuals.hasVolatile()) {
8388 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008389 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008390 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8391 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008392 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008393 }
8394 }
8395 }
8396 }
8397
8398 // C++ [over.operator]p23:
8399 //
8400 // There also exist candidate operator functions of the form
8401 //
8402 // bool operator!(bool);
8403 // bool operator&&(bool, bool);
8404 // bool operator||(bool, bool);
8405 void addExclaimOverload() {
8406 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008407 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008408 /*IsAssignmentOperator=*/false,
8409 /*NumContextualBoolArguments=*/1);
8410 }
8411 void addAmpAmpOrPipePipeOverload() {
8412 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008414 /*IsAssignmentOperator=*/false,
8415 /*NumContextualBoolArguments=*/2);
8416 }
8417
8418 // C++ [over.built]p13:
8419 //
8420 // For every cv-qualified or cv-unqualified object type T there
8421 // exist candidate operator functions of the form
8422 //
8423 // T* operator+(T*, ptrdiff_t); [ABOVE]
8424 // T& operator[](T*, ptrdiff_t);
8425 // T* operator-(T*, ptrdiff_t); [ABOVE]
8426 // T* operator+(ptrdiff_t, T*); [ABOVE]
8427 // T& operator[](ptrdiff_t, T*);
8428 void addSubscriptOverloads() {
8429 for (BuiltinCandidateTypeSet::iterator
8430 Ptr = CandidateTypes[0].pointer_begin(),
8431 PtrEnd = CandidateTypes[0].pointer_end();
8432 Ptr != PtrEnd; ++Ptr) {
8433 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8434 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008435 if (!PointeeType->isObjectType())
8436 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008438 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008439 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008440 }
8441
8442 for (BuiltinCandidateTypeSet::iterator
8443 Ptr = CandidateTypes[1].pointer_begin(),
8444 PtrEnd = CandidateTypes[1].pointer_end();
8445 Ptr != PtrEnd; ++Ptr) {
8446 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8447 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008448 if (!PointeeType->isObjectType())
8449 continue;
8450
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008451 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008452 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008453 }
8454 }
8455
8456 // C++ [over.built]p11:
8457 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8458 // C1 is the same type as C2 or is a derived class of C2, T is an object
8459 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8460 // there exist candidate operator functions of the form
8461 //
8462 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8463 //
8464 // where CV12 is the union of CV1 and CV2.
8465 void addArrowStarOverloads() {
8466 for (BuiltinCandidateTypeSet::iterator
8467 Ptr = CandidateTypes[0].pointer_begin(),
8468 PtrEnd = CandidateTypes[0].pointer_end();
8469 Ptr != PtrEnd; ++Ptr) {
8470 QualType C1Ty = (*Ptr);
8471 QualType C1;
8472 QualifierCollector Q1;
8473 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8474 if (!isa<RecordType>(C1))
8475 continue;
8476 // heuristic to reduce number of builtin candidates in the set.
8477 // Add volatile/restrict version only if there are conversions to a
8478 // volatile/restrict type.
8479 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8480 continue;
8481 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8482 continue;
8483 for (BuiltinCandidateTypeSet::iterator
8484 MemPtr = CandidateTypes[1].member_pointer_begin(),
8485 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8486 MemPtr != MemPtrEnd; ++MemPtr) {
8487 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8488 QualType C2 = QualType(mptr->getClass(), 0);
8489 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008490 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008491 break;
8492 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8493 // build CV12 T&
8494 QualType T = mptr->getPointeeType();
8495 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8496 T.isVolatileQualified())
8497 continue;
8498 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8499 T.isRestrictQualified())
8500 continue;
8501 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008503 }
8504 }
8505 }
8506
8507 // Note that we don't consider the first argument, since it has been
8508 // contextually converted to bool long ago. The candidates below are
8509 // therefore added as binary.
8510 //
8511 // C++ [over.built]p25:
8512 // For every type T, where T is a pointer, pointer-to-member, or scoped
8513 // enumeration type, there exist candidate operator functions of the form
8514 //
8515 // T operator?(bool, T, T);
8516 //
8517 void addConditionalOperatorOverloads() {
8518 /// Set of (canonical) types that we've already handled.
8519 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8520
8521 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8522 for (BuiltinCandidateTypeSet::iterator
8523 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8524 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8525 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008526 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008527 continue;
8528
8529 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008530 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008531 }
8532
8533 for (BuiltinCandidateTypeSet::iterator
8534 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8535 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8536 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008537 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008538 continue;
8539
8540 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008541 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008542 }
8543
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008544 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008545 for (BuiltinCandidateTypeSet::iterator
8546 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8547 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8548 Enum != EnumEnd; ++Enum) {
8549 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8550 continue;
8551
David Blaikie82e95a32014-11-19 07:49:47 +00008552 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008553 continue;
8554
8555 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008556 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008557 }
8558 }
8559 }
8560 }
8561};
8562
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008563} // end anonymous namespace
8564
8565/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8566/// operator overloads to the candidate set (C++ [over.built]), based
8567/// on the operator @p Op and the arguments given. For example, if the
8568/// operator is a binary '+', this routine might add "int
8569/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008570void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8571 SourceLocation OpLoc,
8572 ArrayRef<Expr *> Args,
8573 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008574 // Find all of the types that the arguments can convert to, but only
8575 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008576 // that make use of these types. Also record whether we encounter non-record
8577 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008578 Qualifiers VisibleTypeConversionsQuals;
8579 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008580 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008581 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008582
8583 bool HasNonRecordCandidateType = false;
8584 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008585 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008586 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008587 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008588 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8589 OpLoc,
8590 true,
8591 (Op == OO_Exclaim ||
8592 Op == OO_AmpAmp ||
8593 Op == OO_PipePipe),
8594 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008595 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8596 CandidateTypes[ArgIdx].hasNonRecordTypes();
8597 HasArithmeticOrEnumeralCandidateType =
8598 HasArithmeticOrEnumeralCandidateType ||
8599 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008600 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008601
Chandler Carruth00a38332010-12-13 01:44:01 +00008602 // Exit early when no non-record types have been added to the candidate set
8603 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008604 //
8605 // We can't exit early for !, ||, or &&, since there we have always have
8606 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008607 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008608 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008609 return;
8610
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008611 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008612 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008613 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008614 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008615 CandidateTypes, CandidateSet);
8616
8617 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008618 switch (Op) {
8619 case OO_None:
8620 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008621 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008622
Chandler Carruth5184de02010-12-12 08:51:33 +00008623 case OO_New:
8624 case OO_Delete:
8625 case OO_Array_New:
8626 case OO_Array_Delete:
8627 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008628 llvm_unreachable(
8629 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008630
8631 case OO_Comma:
8632 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008633 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008634 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008635 // -- For the operator ',', the unary operator '&', the
8636 // operator '->', or the operator 'co_await', the
8637 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008638 break;
8639
8640 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008641 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008642 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008643 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008644
8645 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008646 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008647 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008648 } else {
8649 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008650 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008651 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008652 break;
8653
Chandler Carruth5184de02010-12-12 08:51:33 +00008654 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008655 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008656 OpBuilder.addUnaryStarPointerOverloads();
8657 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008658 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008659 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008660
Chandler Carruth5184de02010-12-12 08:51:33 +00008661 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008662 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008663 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008664
8665 case OO_PlusPlus:
8666 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008667 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8668 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008669 break;
8670
Douglas Gregor84605ae2009-08-24 13:43:27 +00008671 case OO_EqualEqual:
8672 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008673 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008674 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008675
Douglas Gregora11693b2008-11-12 17:17:38 +00008676 case OO_Less:
8677 case OO_Greater:
8678 case OO_LessEqual:
8679 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008680 OpBuilder.addRelationalPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008681 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008682 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008683
Douglas Gregora11693b2008-11-12 17:17:38 +00008684 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008685 case OO_Caret:
8686 case OO_Pipe:
8687 case OO_LessLess:
8688 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008689 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008690 break;
8691
Chandler Carruth5184de02010-12-12 08:51:33 +00008692 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008693 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008694 // C++ [over.match.oper]p3:
8695 // -- For the operator ',', the unary operator '&', or the
8696 // operator '->', the built-in candidates set is empty.
8697 break;
8698
8699 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8700 break;
8701
8702 case OO_Tilde:
8703 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8704 break;
8705
Douglas Gregora11693b2008-11-12 17:17:38 +00008706 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008707 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008708 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008709
8710 case OO_PlusEqual:
8711 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008712 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008713 // Fall through.
8714
8715 case OO_StarEqual:
8716 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008717 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008718 break;
8719
8720 case OO_PercentEqual:
8721 case OO_LessLessEqual:
8722 case OO_GreaterGreaterEqual:
8723 case OO_AmpEqual:
8724 case OO_CaretEqual:
8725 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008726 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008727 break;
8728
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008729 case OO_Exclaim:
8730 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008731 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008732
Douglas Gregora11693b2008-11-12 17:17:38 +00008733 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008734 case OO_PipePipe:
8735 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008736 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008737
8738 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008739 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008740 break;
8741
8742 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008743 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008744 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008745
8746 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008747 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008748 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008749 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008750 }
8751}
8752
Douglas Gregore254f902009-02-04 00:32:51 +00008753/// \brief Add function candidates found via argument-dependent lookup
8754/// to the set of overloading candidates.
8755///
8756/// This routine performs argument-dependent name lookup based on the
8757/// given function name (which may also be an operator name) and adds
8758/// all of the overload candidates found by ADL to the overload
8759/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008760void
Douglas Gregore254f902009-02-04 00:32:51 +00008761Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008762 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008763 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008764 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008765 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008766 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008767 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008768
John McCall91f61fc2010-01-26 06:04:06 +00008769 // FIXME: This approach for uniquing ADL results (and removing
8770 // redundant candidates from the set) relies on pointer-equality,
8771 // which means we need to key off the canonical decl. However,
8772 // always going back to the canonical decl might not get us the
8773 // right set of default arguments. What default arguments are
8774 // we supposed to consider on ADL candidates, anyway?
8775
Douglas Gregorcabea402009-09-22 15:41:20 +00008776 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008777 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008778
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008779 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008780 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8781 CandEnd = CandidateSet.end();
8782 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008783 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008784 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008785 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008786 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008787 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008788
8789 // For each of the ADL candidates we found, add it to the overload
8790 // set.
John McCall8fe68082010-01-26 07:16:45 +00008791 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008792 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008793 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008794 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008795 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008797 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8798 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008799 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008800 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008801 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008802 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008803 }
Douglas Gregore254f902009-02-04 00:32:51 +00008804}
8805
George Burgess IV3dc166912016-05-10 01:59:34 +00008806namespace {
8807enum class Comparison { Equal, Better, Worse };
8808}
8809
8810/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8811/// overload resolution.
8812///
8813/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8814/// Cand1's first N enable_if attributes have precisely the same conditions as
8815/// Cand2's first N enable_if attributes (where N = the number of enable_if
8816/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8817///
8818/// Note that you can have a pair of candidates such that Cand1's enable_if
8819/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8820/// worse than Cand1's.
8821static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8822 const FunctionDecl *Cand2) {
8823 // Common case: One (or both) decls don't have enable_if attrs.
8824 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8825 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8826 if (!Cand1Attr || !Cand2Attr) {
8827 if (Cand1Attr == Cand2Attr)
8828 return Comparison::Equal;
8829 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8830 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008831
8832 // FIXME: The next several lines are just
8833 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8834 // instead of reverse order which is how they're stored in the AST.
8835 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8836 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8837
George Burgess IV3dc166912016-05-10 01:59:34 +00008838 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8839 // has fewer enable_if attributes than Cand2.
8840 if (Cand1Attrs.size() < Cand2Attrs.size())
8841 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008842
8843 auto Cand1I = Cand1Attrs.begin();
8844 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8845 for (auto &Cand2A : Cand2Attrs) {
8846 Cand1ID.clear();
8847 Cand2ID.clear();
8848
8849 auto &Cand1A = *Cand1I++;
8850 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8851 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8852 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008853 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008854 }
8855
George Burgess IV3dc166912016-05-10 01:59:34 +00008856 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008857}
8858
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008859/// isBetterOverloadCandidate - Determines whether the first overload
8860/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00008861bool clang::isBetterOverloadCandidate(
8862 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8863 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008864 // Define viable functions to be better candidates than non-viable
8865 // functions.
8866 if (!Cand2.Viable)
8867 return Cand1.Viable;
8868 else if (!Cand1.Viable)
8869 return false;
8870
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008871 // C++ [over.match.best]p1:
8872 //
8873 // -- if F is a static member function, ICS1(F) is defined such
8874 // that ICS1(F) is neither better nor worse than ICS1(G) for
8875 // any function G, and, symmetrically, ICS1(G) is neither
8876 // better nor worse than ICS1(F).
8877 unsigned StartArg = 0;
8878 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8879 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008880
George Burgess IVfbad5b22016-09-07 20:03:19 +00008881 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8882 // We don't allow incompatible pointer conversions in C++.
8883 if (!S.getLangOpts().CPlusPlus)
8884 return ICS.isStandard() &&
8885 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8886
8887 // The only ill-formed conversion we allow in C++ is the string literal to
8888 // char* conversion, which is only considered ill-formed after C++11.
8889 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8890 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8891 };
8892
8893 // Define functions that don't require ill-formed conversions for a given
8894 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008895 unsigned NumArgs = Cand1.Conversions.size();
8896 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008897 bool HasBetterConversion = false;
8898 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8899 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8900 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8901 if (Cand1Bad != Cand2Bad) {
8902 if (Cand1Bad)
8903 return false;
8904 HasBetterConversion = true;
8905 }
8906 }
8907
8908 if (HasBetterConversion)
8909 return true;
8910
Douglas Gregord3cb3562009-07-07 23:38:56 +00008911 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008912 // A viable function F1 is defined to be a better function than another
8913 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008914 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008915 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008916 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008917 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008918 Cand2.Conversions[ArgIdx])) {
8919 case ImplicitConversionSequence::Better:
8920 // Cand1 has a better conversion sequence.
8921 HasBetterConversion = true;
8922 break;
8923
8924 case ImplicitConversionSequence::Worse:
8925 // Cand1 can't be better than Cand2.
8926 return false;
8927
8928 case ImplicitConversionSequence::Indistinguishable:
8929 // Do nothing.
8930 break;
8931 }
8932 }
8933
Mike Stump11289f42009-09-09 15:08:12 +00008934 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008935 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008936 if (HasBetterConversion)
8937 return true;
8938
Douglas Gregora1f013e2008-11-07 22:36:19 +00008939 // -- the context is an initialization by user-defined conversion
8940 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8941 // from the return type of F1 to the destination type (i.e.,
8942 // the type of the entity being initialized) is a better
8943 // conversion sequence than the standard conversion sequence
8944 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00008945 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8946 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008947 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008948 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008949 // First check whether we prefer one of the conversion functions over the
8950 // other. This only distinguishes the results in non-standard, extension
8951 // cases such as the conversion from a lambda closure type to a function
8952 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008953 ImplicitConversionSequence::CompareKind Result =
8954 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8955 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008956 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008957 Cand1.FinalConversion,
8958 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008959
Richard Smithec2748a2014-05-17 04:36:39 +00008960 if (Result != ImplicitConversionSequence::Indistinguishable)
8961 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008962
8963 // FIXME: Compare kind of reference binding if conversion functions
8964 // convert to a reference type used in direct reference binding, per
8965 // C++14 [over.match.best]p1 section 2 bullet 3.
8966 }
8967
Richard Smith32918772017-02-14 00:25:28 +00008968 // -- F1 is generated from a deduction-guide and F2 is not
Richard Smithbc491202017-02-17 20:05:37 +00008969 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
8970 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
8971 if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
8972 return Guide2->isImplicit();
Richard Smith32918772017-02-14 00:25:28 +00008973
Richard Smith6fdeaab2014-05-17 01:58:45 +00008974 // -- F1 is a non-template function and F2 is a function template
8975 // specialization, or, if not that,
8976 bool Cand1IsSpecialization = Cand1.Function &&
8977 Cand1.Function->getPrimaryTemplate();
8978 bool Cand2IsSpecialization = Cand2.Function &&
8979 Cand2.Function->getPrimaryTemplate();
8980 if (Cand1IsSpecialization != Cand2IsSpecialization)
8981 return Cand2IsSpecialization;
8982
8983 // -- F1 and F2 are function template specializations, and the function
8984 // template for F1 is more specialized than the template for F2
8985 // according to the partial ordering rules described in 14.5.5.2, or,
8986 // if not that,
8987 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8988 if (FunctionTemplateDecl *BetterTemplate
8989 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8990 Cand2.Function->getPrimaryTemplate(),
8991 Loc,
8992 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8993 : TPOC_Call,
8994 Cand1.ExplicitCallArguments,
8995 Cand2.ExplicitCallArguments))
8996 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008997 }
8998
Richard Smith5179eb72016-06-28 19:03:57 +00008999 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9000 // A derived-class constructor beats an (inherited) base class constructor.
9001 bool Cand1IsInherited =
9002 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9003 bool Cand2IsInherited =
9004 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9005 if (Cand1IsInherited != Cand2IsInherited)
9006 return Cand2IsInherited;
9007 else if (Cand1IsInherited) {
9008 assert(Cand2IsInherited);
9009 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9010 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9011 if (Cand1Class->isDerivedFrom(Cand2Class))
9012 return true;
9013 if (Cand2Class->isDerivedFrom(Cand1Class))
9014 return false;
9015 // Inherited from sibling base classes: still ambiguous.
9016 }
9017
Richard Smith67ef14f2017-09-26 18:37:55 +00009018 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9019 // as combined with the resolution to CWG issue 243.
9020 //
9021 // When the context is initialization by constructor ([over.match.ctor] or
9022 // either phase of [over.match.list]), a constructor is preferred over
9023 // a conversion function.
9024 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9025 Cand1.Function && Cand2.Function &&
9026 isa<CXXConstructorDecl>(Cand1.Function) !=
9027 isa<CXXConstructorDecl>(Cand2.Function))
9028 return isa<CXXConstructorDecl>(Cand1.Function);
9029
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009030 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009031 if (Cand1.Function && Cand2.Function) {
9032 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9033 if (Cmp != Comparison::Equal)
9034 return Cmp == Comparison::Better;
9035 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009036
Justin Lebar25c4a812016-03-29 16:24:16 +00009037 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009038 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9039 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9040 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9041 }
9042
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009043 bool HasPS1 = Cand1.Function != nullptr &&
9044 functionHasPassObjectSizeParams(Cand1.Function);
9045 bool HasPS2 = Cand2.Function != nullptr &&
9046 functionHasPassObjectSizeParams(Cand2.Function);
9047 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009048}
9049
Richard Smith2dbe4042015-11-04 19:26:32 +00009050/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009051/// name lookup and overload resolution. This applies when the same internal/no
9052/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009053/// the same header). In such a case, we don't consider the declarations to
9054/// declare the same entity, but we also don't want lookups with both
9055/// declarations visible to be ambiguous in some cases (this happens when using
9056/// a modularized libstdc++).
9057bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9058 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009059 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9060 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9061 if (!VA || !VB)
9062 return false;
9063
9064 // The declarations must be declaring the same name as an internal linkage
9065 // entity in different modules.
9066 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9067 VB->getDeclContext()->getRedeclContext()) ||
9068 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9069 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9070 VA->isExternallyVisible() || VB->isExternallyVisible())
9071 return false;
9072
9073 // Check that the declarations appear to be equivalent.
9074 //
9075 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9076 // For constants and functions, we should check the initializer or body is
9077 // the same. For non-constant variables, we shouldn't allow it at all.
9078 if (Context.hasSameType(VA->getType(), VB->getType()))
9079 return true;
9080
9081 // Enum constants within unnamed enumerations will have different types, but
9082 // may still be similar enough to be interchangeable for our purposes.
9083 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9084 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9085 // Only handle anonymous enums. If the enumerations were named and
9086 // equivalent, they would have been merged to the same type.
9087 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9088 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9089 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9090 !Context.hasSameType(EnumA->getIntegerType(),
9091 EnumB->getIntegerType()))
9092 return false;
9093 // Allow this only if the value is the same for both enumerators.
9094 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9095 }
9096 }
9097
9098 // Nothing else is sufficiently similar.
9099 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009100}
9101
9102void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9103 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9104 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9105
9106 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9107 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9108 << !M << (M ? M->getFullModuleName() : "");
9109
9110 for (auto *E : Equiv) {
9111 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9112 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9113 << !M << (M ? M->getFullModuleName() : "");
9114 }
Richard Smith896c66e2015-10-21 07:13:52 +00009115}
9116
Mike Stump11289f42009-09-09 15:08:12 +00009117/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009118/// within an overload candidate set.
9119///
James Dennettffad8b72012-06-22 08:10:18 +00009120/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009121/// which overload resolution occurs.
9122///
James Dennettffad8b72012-06-22 08:10:18 +00009123/// \param Best If overload resolution was successful or found a deleted
9124/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009125///
9126/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009127OverloadingResult
9128OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009129 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009130 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9131 std::transform(begin(), end(), std::back_inserter(Candidates),
9132 [](OverloadCandidate &Cand) { return &Cand; });
9133
Justin Lebar66a2ab92016-08-10 00:40:43 +00009134 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9135 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009136 // compilation mode only one call variant is viable. We need to
9137 // exclude non-viable overload candidates from consideration based
9138 // only on their host/device attributes. Specifically, if one
9139 // candidate call is WrongSide and the other is SameSide, we ignore
9140 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009141 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009142 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9143 bool ContainsSameSideCandidate =
9144 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9145 return Cand->Function &&
9146 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9147 Sema::CFP_SameSide;
9148 });
9149 if (ContainsSameSideCandidate) {
9150 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9151 return Cand->Function &&
9152 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9153 Sema::CFP_WrongSide;
9154 };
George Burgess IV8684b032017-01-04 19:16:29 +00009155 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009156 }
9157 }
9158
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009159 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009160 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009161 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009162 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009163 if (Best == end() ||
9164 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009165 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009166
9167 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009168 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009169 return OR_No_Viable_Function;
9170
Richard Smith2dbe4042015-11-04 19:26:32 +00009171 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009173 // Make sure that this function is better than every other viable
9174 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009175 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009176 if (Cand->Viable && Cand != Best &&
9177 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009178 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9179 Cand->Function)) {
9180 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009181 continue;
9182 }
9183
John McCall5c32be02010-08-24 20:38:10 +00009184 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009185 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009186 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009187 }
Mike Stump11289f42009-09-09 15:08:12 +00009188
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009189 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009190 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009191 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009192 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009193 return OR_Deleted;
9194
Richard Smith2dbe4042015-11-04 19:26:32 +00009195 if (!EquivalentCands.empty())
9196 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9197 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009198
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009199 return OR_Success;
9200}
9201
John McCall53262c92010-01-12 02:15:36 +00009202namespace {
9203
9204enum OverloadCandidateKind {
9205 oc_function,
9206 oc_method,
9207 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009208 oc_function_template,
9209 oc_method_template,
9210 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009211 oc_implicit_default_constructor,
9212 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009213 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009214 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009215 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009216 oc_inherited_constructor,
9217 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009218};
9219
George Burgess IVd66d37c2016-10-28 21:42:06 +00009220static OverloadCandidateKind
9221ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9222 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009223 bool isTemplate = false;
9224
9225 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9226 isTemplate = true;
9227 Description = S.getTemplateArgumentBindingsText(
9228 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9229 }
John McCallfd0b2f82010-01-06 09:43:14 +00009230
9231 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009232 if (!Ctor->isImplicit()) {
9233 if (isa<ConstructorUsingShadowDecl>(Found))
9234 return isTemplate ? oc_inherited_constructor_template
9235 : oc_inherited_constructor;
9236 else
9237 return isTemplate ? oc_constructor_template : oc_constructor;
9238 }
Sebastian Redl08905022011-02-05 19:23:19 +00009239
Alexis Hunt119c10e2011-05-25 23:16:36 +00009240 if (Ctor->isDefaultConstructor())
9241 return oc_implicit_default_constructor;
9242
9243 if (Ctor->isMoveConstructor())
9244 return oc_implicit_move_constructor;
9245
9246 assert(Ctor->isCopyConstructor() &&
9247 "unexpected sort of implicit constructor");
9248 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009249 }
9250
9251 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9252 // This actually gets spelled 'candidate function' for now, but
9253 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009254 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009255 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009256
Alexis Hunt119c10e2011-05-25 23:16:36 +00009257 if (Meth->isMoveAssignmentOperator())
9258 return oc_implicit_move_assignment;
9259
Douglas Gregor12695102012-02-10 08:36:38 +00009260 if (Meth->isCopyAssignmentOperator())
9261 return oc_implicit_copy_assignment;
9262
9263 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9264 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009265 }
9266
John McCalle1ac8d12010-01-13 00:25:19 +00009267 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009268}
9269
Richard Smith5179eb72016-06-28 19:03:57 +00009270void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9271 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9272 // set.
9273 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9274 S.Diag(FoundDecl->getLocation(),
9275 diag::note_ovl_candidate_inherited_constructor)
9276 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009277}
9278
John McCall53262c92010-01-12 02:15:36 +00009279} // end anonymous namespace
9280
George Burgess IV5f21c712015-10-12 19:57:04 +00009281static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9282 const FunctionDecl *FD) {
9283 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9284 bool AlwaysTrue;
9285 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9286 return false;
9287 if (!AlwaysTrue)
9288 return false;
9289 }
9290 return true;
9291}
9292
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009293/// \brief Returns true if we can take the address of the function.
9294///
9295/// \param Complain - If true, we'll emit a diagnostic
9296/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9297/// we in overload resolution?
9298/// \param Loc - The location of the statement we're complaining about. Ignored
9299/// if we're not complaining, or if we're in overload resolution.
9300static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9301 bool Complain,
9302 bool InOverloadResolution,
9303 SourceLocation Loc) {
9304 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9305 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009306 if (InOverloadResolution)
9307 S.Diag(FD->getLocStart(),
9308 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9309 else
9310 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9311 }
9312 return false;
9313 }
9314
George Burgess IV21081362016-07-24 23:12:40 +00009315 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9316 return P->hasAttr<PassObjectSizeAttr>();
9317 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009318 if (I == FD->param_end())
9319 return true;
9320
9321 if (Complain) {
9322 // Add one to ParamNo because it's user-facing
9323 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9324 if (InOverloadResolution)
9325 S.Diag(FD->getLocation(),
9326 diag::note_ovl_candidate_has_pass_object_size_params)
9327 << ParamNo;
9328 else
9329 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9330 << FD << ParamNo;
9331 }
9332 return false;
9333}
9334
9335static bool checkAddressOfCandidateIsAvailable(Sema &S,
9336 const FunctionDecl *FD) {
9337 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9338 /*InOverloadResolution=*/true,
9339 /*Loc=*/SourceLocation());
9340}
9341
9342bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9343 bool Complain,
9344 SourceLocation Loc) {
9345 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9346 /*InOverloadResolution=*/false,
9347 Loc);
9348}
9349
John McCall53262c92010-01-12 02:15:36 +00009350// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009351void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9352 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009353 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9354 return;
9355
John McCalle1ac8d12010-01-13 00:25:19 +00009356 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009357 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009358 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009359 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009360
9361 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009362 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009363 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009364}
9365
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009366// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009367// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009368void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9369 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009370 assert(OverloadedExpr->getType() == Context.OverloadTy);
9371
9372 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9373 OverloadExpr *OvlExpr = Ovl.Expression;
9374
9375 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009376 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009377 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009378 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009379 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009380 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009381 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009382 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009383 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009384 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009385 }
9386 }
9387}
9388
John McCall0d1da222010-01-12 00:44:57 +00009389/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9390/// "lead" diagnostic; it will be given two arguments, the source and
9391/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009392void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9393 Sema &S,
9394 SourceLocation CaretLoc,
9395 const PartialDiagnostic &PDiag) const {
9396 S.Diag(CaretLoc, PDiag)
9397 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009398 // FIXME: The note limiting machinery is borrowed from
9399 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9400 // refactoring here.
9401 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9402 unsigned CandsShown = 0;
9403 AmbiguousConversionSequence::const_iterator I, E;
9404 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9405 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9406 break;
9407 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009408 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009409 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009410 if (I != E)
9411 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009412}
9413
Richard Smith17c00b42014-11-12 01:24:00 +00009414static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009415 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009416 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9417 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009418 assert(Cand->Function && "for now, candidate must be a function");
9419 FunctionDecl *Fn = Cand->Function;
9420
9421 // There's a conversion slot for the object argument if this is a
9422 // non-constructor method. Note that 'I' corresponds the
9423 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009424 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009425 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009426 if (I == 0)
9427 isObjectArgument = true;
9428 else
9429 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009430 }
9431
John McCalle1ac8d12010-01-13 00:25:19 +00009432 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009433 OverloadCandidateKind FnKind =
9434 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009435
John McCall6a61b522010-01-13 09:16:55 +00009436 Expr *FromExpr = Conv.Bad.FromExpr;
9437 QualType FromTy = Conv.Bad.getFromType();
9438 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009439
John McCallfb7ad0f2010-02-02 02:42:52 +00009440 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009441 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009442 Expr *E = FromExpr->IgnoreParens();
9443 if (isa<UnaryOperator>(E))
9444 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009445 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009446
9447 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9448 << (unsigned) FnKind << FnDesc
9449 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9450 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009451 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009452 return;
9453 }
9454
John McCall6d174642010-01-23 08:10:49 +00009455 // Do some hand-waving analysis to see if the non-viability is due
9456 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009457 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9458 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9459 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9460 CToTy = RT->getPointeeType();
9461 else {
9462 // TODO: detect and diagnose the full richness of const mismatches.
9463 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009464 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9465 CFromTy = FromPT->getPointeeType();
9466 CToTy = ToPT->getPointeeType();
9467 }
John McCall47000992010-01-14 03:28:57 +00009468 }
9469
9470 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9471 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009472 Qualifiers FromQs = CFromTy.getQualifiers();
9473 Qualifiers ToQs = CToTy.getQualifiers();
9474
9475 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9477 << (unsigned) FnKind << FnDesc
9478 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9479 << FromTy
Yaxun Liub34ec822017-04-11 17:24:23 +00009480 << FromQs.getAddressSpaceAttributePrintValue()
9481 << ToQs.getAddressSpaceAttributePrintValue()
John McCall47000992010-01-14 03:28:57 +00009482 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009483 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009484 return;
9485 }
9486
John McCall31168b02011-06-15 23:02:42 +00009487 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009489 << (unsigned) FnKind << FnDesc
9490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9491 << FromTy
9492 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9493 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009494 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009495 return;
9496 }
9497
Douglas Gregoraec25842011-04-26 23:16:46 +00009498 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9500 << (unsigned) FnKind << FnDesc
9501 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9502 << FromTy
9503 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9504 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009505 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009506 return;
9507 }
9508
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009509 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9510 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9511 << (unsigned) FnKind << FnDesc
9512 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9513 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009514 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009515 return;
9516 }
9517
John McCall47000992010-01-14 03:28:57 +00009518 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9519 assert(CVR && "unexpected qualifiers mismatch");
9520
9521 if (isObjectArgument) {
9522 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9523 << (unsigned) FnKind << FnDesc
9524 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9525 << FromTy << (CVR - 1);
9526 } else {
9527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9528 << (unsigned) FnKind << FnDesc
9529 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9530 << FromTy << (CVR - 1) << I+1;
9531 }
Richard Smith5179eb72016-06-28 19:03:57 +00009532 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009533 return;
9534 }
9535
Sebastian Redla72462c2011-09-24 17:48:32 +00009536 // Special diagnostic for failure to convert an initializer list, since
9537 // telling the user that it has type void is not useful.
9538 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9540 << (unsigned) FnKind << FnDesc
9541 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9542 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009543 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009544 return;
9545 }
9546
John McCall6d174642010-01-23 08:10:49 +00009547 // Diagnose references or pointers to incomplete types differently,
9548 // since it's far from impossible that the incompleteness triggered
9549 // the failure.
9550 QualType TempFromTy = FromTy.getNonReferenceType();
9551 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9552 TempFromTy = PTy->getPointeeType();
9553 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009554 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9556 << (unsigned) FnKind << FnDesc
9557 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009558 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9559 << (unsigned) (Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009560
Richard Smith5179eb72016-06-28 19:03:57 +00009561 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009562 return;
9563 }
9564
Douglas Gregor56f2e342010-06-30 23:01:39 +00009565 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009566 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009567 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9568 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9569 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9570 FromPtrTy->getPointeeType()) &&
9571 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9572 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009573 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009574 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009575 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009576 }
9577 } else if (const ObjCObjectPointerType *FromPtrTy
9578 = FromTy->getAs<ObjCObjectPointerType>()) {
9579 if (const ObjCObjectPointerType *ToPtrTy
9580 = ToTy->getAs<ObjCObjectPointerType>())
9581 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9582 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9583 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9584 FromPtrTy->getPointeeType()) &&
9585 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009586 BaseToDerivedConversion = 2;
9587 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009588 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9589 !FromTy->isIncompleteType() &&
9590 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009591 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009592 BaseToDerivedConversion = 3;
9593 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9594 ToTy.getNonReferenceType().getCanonicalType() ==
9595 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9597 << (unsigned) FnKind << FnDesc
9598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9599 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009600 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009601 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009602 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009604
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009605 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009606 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009607 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009608 << (unsigned) FnKind << FnDesc
9609 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009610 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009611 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009612 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009613 return;
9614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009615
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009616 if (isa<ObjCObjectPointerType>(CFromTy) &&
9617 isa<PointerType>(CToTy)) {
9618 Qualifiers FromQs = CFromTy.getQualifiers();
9619 Qualifiers ToQs = CToTy.getQualifiers();
9620 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9621 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9622 << (unsigned) FnKind << FnDesc
9623 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9624 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009625 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009626 return;
9627 }
9628 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009629
9630 if (TakingCandidateAddress &&
9631 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9632 return;
9633
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009634 // Emit the generic diagnostic and, optionally, add the hints to it.
9635 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9636 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009637 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009638 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9639 << (unsigned) (Cand->Fix.Kind);
9640
9641 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009642 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9643 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009644 FDiag << *HI;
9645 S.Diag(Fn->getLocation(), FDiag);
9646
Richard Smith5179eb72016-06-28 19:03:57 +00009647 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009648}
9649
Larisse Voufo98b20f12013-07-19 23:00:19 +00009650/// Additional arity mismatch diagnosis specific to a function overload
9651/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9652/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009653static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9654 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009655 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009656 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009657
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009658 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009659 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009660 // right number of arguments, because only overloaded operators have
9661 // the weird behavior of overloading member and non-member functions.
9662 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009663 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009664 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009665 return true;
9666
9667 if (NumArgs < MinParams) {
9668 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9669 (Cand->FailureKind == ovl_fail_bad_deduction &&
9670 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9671 } else {
9672 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9673 (Cand->FailureKind == ovl_fail_bad_deduction &&
9674 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9675 }
9676
9677 return false;
9678}
9679
9680/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009681static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9682 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009683 assert(isa<FunctionDecl>(D) &&
9684 "The templated declaration should at least be a function"
9685 " when diagnosing bad template argument deduction due to too many"
9686 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009687
Larisse Voufo98b20f12013-07-19 23:00:19 +00009688 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009689
Larisse Voufo98b20f12013-07-19 23:00:19 +00009690 // TODO: treat calls to a missing default constructor as a special case
9691 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9692 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009693
John McCall6a61b522010-01-13 09:16:55 +00009694 // at least / at most / exactly
9695 unsigned mode, modeCount;
9696 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009697 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9698 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009699 mode = 0; // "at least"
9700 else
9701 mode = 2; // "exactly"
9702 modeCount = MinParams;
9703 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009704 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009705 mode = 1; // "at most"
9706 else
9707 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009708 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009709 }
9710
9711 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009712 OverloadCandidateKind FnKind =
9713 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009714
Richard Smith10ff50d2012-05-11 05:16:41 +00009715 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009717 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9718 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009719 else
9720 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009721 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9722 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009723 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009724}
9725
Larisse Voufo98b20f12013-07-19 23:00:19 +00009726/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009727static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9728 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009729 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009730 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009731}
Larisse Voufo47c08452013-07-19 22:53:23 +00009732
Richard Smith17c00b42014-11-12 01:24:00 +00009733static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009734 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9735 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009736 llvm_unreachable("Unsupported: Getting the described template declaration"
9737 " for bad deduction diagnosis");
9738}
9739
9740/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009741static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009742 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009743 unsigned NumArgs,
9744 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009745 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009746 NamedDecl *ParamD;
9747 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9748 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9749 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009750 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009751 case Sema::TDK_Success:
9752 llvm_unreachable("TDK_success while diagnosing bad deduction");
9753
9754 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009755 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009756 S.Diag(Templated->getLocation(),
9757 diag::note_ovl_candidate_incomplete_deduction)
9758 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009759 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009760 return;
9761 }
9762
John McCall42d7d192010-08-05 09:05:08 +00009763 case Sema::TDK_Underqualified: {
9764 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9765 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9766
Larisse Voufo98b20f12013-07-19 23:00:19 +00009767 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009768
9769 // Param will have been canonicalized, but it should just be a
9770 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009771 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009772 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009773 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009774 assert(S.Context.hasSameType(Param, NonCanonParam));
9775
9776 // Arg has also been canonicalized, but there's nothing we can do
9777 // about that. It also doesn't matter as much, because it won't
9778 // have any template parameters in it (because deduction isn't
9779 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009780 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009781
Larisse Voufo98b20f12013-07-19 23:00:19 +00009782 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9783 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009784 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009785 return;
9786 }
9787
9788 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009789 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009790 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009791 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009792 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009793 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9794 // Deduction might have failed because we deduced arguments of two
9795 // different types for a non-type template parameter.
9796 // FIXME: Use a different TDK value for this.
9797 QualType T1 =
9798 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9799 QualType T2 =
9800 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9801 if (!S.Context.hasSameType(T1, T2)) {
9802 S.Diag(Templated->getLocation(),
9803 diag::note_ovl_candidate_inconsistent_deduction_types)
9804 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9805 << *DeductionFailure.getSecondArg() << T2;
9806 MaybeEmitInheritedConstructorNote(S, Found);
9807 return;
9808 }
9809
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009810 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009811 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009812 which = 2;
9813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009814
Larisse Voufo98b20f12013-07-19 23:00:19 +00009815 S.Diag(Templated->getLocation(),
9816 diag::note_ovl_candidate_inconsistent_deduction)
9817 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9818 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009819 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009820 return;
9821 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009822
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009823 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009824 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009825 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009826 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009827 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009828 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009829 else {
9830 int index = 0;
9831 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9832 index = TTP->getIndex();
9833 else if (NonTypeTemplateParmDecl *NTTP
9834 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9835 index = NTTP->getIndex();
9836 else
9837 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009838 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009839 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009840 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009841 }
Richard Smith5179eb72016-06-28 19:03:57 +00009842 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009843 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009844
Douglas Gregor02eb4832010-05-08 18:13:28 +00009845 case Sema::TDK_TooManyArguments:
9846 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009847 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009848 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009849
9850 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009851 S.Diag(Templated->getLocation(),
9852 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009853 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009854 return;
9855
9856 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009857 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009858 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009859 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009860 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009861 TemplateArgString = " ";
9862 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009863 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009864 }
9865
Richard Smith6f8d2c62012-05-09 05:17:00 +00009866 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009867 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009868 if (PDiag && PDiag->second.getDiagID() ==
9869 diag::err_typename_nested_not_found_enable_if) {
9870 // FIXME: Use the source range of the condition, and the fully-qualified
9871 // name of the enable_if template. These are both present in PDiag.
9872 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9873 << "'enable_if'" << TemplateArgString;
9874 return;
9875 }
9876
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009877 // We found a specific requirement that disabled the enable_if.
9878 if (PDiag && PDiag->second.getDiagID() ==
9879 diag::err_typename_nested_not_found_requirement) {
9880 S.Diag(Templated->getLocation(),
9881 diag::note_ovl_candidate_disabled_by_requirement)
9882 << PDiag->second.getStringArg(0) << TemplateArgString;
9883 return;
9884 }
9885
Richard Smith9ca64612012-05-07 09:03:25 +00009886 // Format the SFINAE diagnostic into the argument string.
9887 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9888 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009889 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009890 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009891 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009892 SFINAEArgString = ": ";
9893 R = SourceRange(PDiag->first, PDiag->first);
9894 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9895 }
9896
Larisse Voufo98b20f12013-07-19 23:00:19 +00009897 S.Diag(Templated->getLocation(),
9898 diag::note_ovl_candidate_substitution_failure)
9899 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009900 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009901 return;
9902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009903
Richard Smithc92d2062017-01-05 23:02:44 +00009904 case Sema::TDK_DeducedMismatch:
9905 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009906 // Format the template argument list into the argument string.
9907 SmallString<128> TemplateArgString;
9908 if (TemplateArgumentList *Args =
9909 DeductionFailure.getTemplateArgumentList()) {
9910 TemplateArgString = " ";
9911 TemplateArgString += S.getTemplateArgumentBindingsText(
9912 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9913 }
9914
9915 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9916 << (*DeductionFailure.getCallArgIndex() + 1)
9917 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009918 << TemplateArgString
9919 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009920 break;
9921 }
9922
Richard Trieue3732352013-04-08 21:11:40 +00009923 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009924 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009925 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9926 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009927 if (FirstTA.getKind() == TemplateArgument::Template &&
9928 SecondTA.getKind() == TemplateArgument::Template) {
9929 TemplateName FirstTN = FirstTA.getAsTemplate();
9930 TemplateName SecondTN = SecondTA.getAsTemplate();
9931 if (FirstTN.getKind() == TemplateName::Template &&
9932 SecondTN.getKind() == TemplateName::Template) {
9933 if (FirstTN.getAsTemplateDecl()->getName() ==
9934 SecondTN.getAsTemplateDecl()->getName()) {
9935 // FIXME: This fixes a bad diagnostic where both templates are named
9936 // the same. This particular case is a bit difficult since:
9937 // 1) It is passed as a string to the diagnostic printer.
9938 // 2) The diagnostic printer only attempts to find a better
9939 // name for types, not decls.
9940 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009941 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009942 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9943 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9944 return;
9945 }
9946 }
9947 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009948
9949 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9950 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9951 return;
9952
Faisal Vali2b391ab2013-09-26 19:54:12 +00009953 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009954 // call operator, and if so, emit a prettier and more informative
9955 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +00009956 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009957 S.Diag(Templated->getLocation(),
9958 diag::note_ovl_candidate_non_deduced_mismatch)
9959 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009960 return;
Richard Trieue3732352013-04-08 21:11:40 +00009961 }
John McCall8b9ed552010-02-01 18:53:26 +00009962 // TODO: diagnose these individually, then kill off
9963 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009964 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009965 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009966 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009967 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009968 case Sema::TDK_CUDATargetMismatch:
9969 S.Diag(Templated->getLocation(),
9970 diag::note_cuda_ovl_candidate_target_mismatch);
9971 return;
John McCall8b9ed552010-02-01 18:53:26 +00009972 }
9973}
9974
Larisse Voufo98b20f12013-07-19 23:00:19 +00009975/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009976static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009977 unsigned NumArgs,
9978 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009979 unsigned TDK = Cand->DeductionFailure.Result;
9980 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9981 if (CheckArityMismatch(S, Cand, NumArgs))
9982 return;
9983 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009984 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009985 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009986}
9987
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009988/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009989static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009990 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9991 FunctionDecl *Callee = Cand->Function;
9992
9993 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9994 CalleeTarget = S.IdentifyCUDATarget(Callee);
9995
9996 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009997 OverloadCandidateKind FnKind =
9998 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009999
10000 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010001 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10002
10003 // This could be an implicit constructor for which we could not infer the
10004 // target due to a collsion. Diagnose that case.
10005 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10006 if (Meth != nullptr && Meth->isImplicit()) {
10007 CXXRecordDecl *ParentClass = Meth->getParent();
10008 Sema::CXXSpecialMember CSM;
10009
10010 switch (FnKind) {
10011 default:
10012 return;
10013 case oc_implicit_default_constructor:
10014 CSM = Sema::CXXDefaultConstructor;
10015 break;
10016 case oc_implicit_copy_constructor:
10017 CSM = Sema::CXXCopyConstructor;
10018 break;
10019 case oc_implicit_move_constructor:
10020 CSM = Sema::CXXMoveConstructor;
10021 break;
10022 case oc_implicit_copy_assignment:
10023 CSM = Sema::CXXCopyAssignment;
10024 break;
10025 case oc_implicit_move_assignment:
10026 CSM = Sema::CXXMoveAssignment;
10027 break;
10028 };
10029
10030 bool ConstRHS = false;
10031 if (Meth->getNumParams()) {
10032 if (const ReferenceType *RT =
10033 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10034 ConstRHS = RT->getPointeeType().isConstQualified();
10035 }
10036 }
10037
10038 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10039 /* ConstRHS */ ConstRHS,
10040 /* Diagnose */ true);
10041 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010042}
10043
Richard Smith17c00b42014-11-12 01:24:00 +000010044static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010045 FunctionDecl *Callee = Cand->Function;
10046 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10047
10048 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010049 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010050 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10051}
10052
Yaxun Liu5b746652016-12-18 05:18:55 +000010053static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10054 FunctionDecl *Callee = Cand->Function;
10055
10056 S.Diag(Callee->getLocation(),
10057 diag::note_ovl_candidate_disabled_by_extension);
10058}
10059
John McCall8b9ed552010-02-01 18:53:26 +000010060/// Generates a 'note' diagnostic for an overload candidate. We've
10061/// already generated a primary error at the call site.
10062///
10063/// It really does need to be a single diagnostic with its caret
10064/// pointed at the candidate declaration. Yes, this creates some
10065/// major challenges of technical writing. Yes, this makes pointing
10066/// out problems with specific arguments quite awkward. It's still
10067/// better than generating twenty screens of text for every failed
10068/// overload.
10069///
10070/// It would be great to be able to express per-candidate problems
10071/// more richly for those diagnostic clients that cared, but we'd
10072/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010073static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010074 unsigned NumArgs,
10075 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010076 FunctionDecl *Fn = Cand->Function;
10077
John McCall12f97bc2010-01-08 04:41:39 +000010078 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010079 if (Cand->Viable) {
10080 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10081 std::string FnDesc;
10082 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010083 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010084
George Burgess IV177399e2017-01-09 04:12:14 +000010085 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10086 << FnKind << FnDesc
10087 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10088 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10089 return;
10090 }
John McCall12f97bc2010-01-08 04:41:39 +000010091
George Burgess IV177399e2017-01-09 04:12:14 +000010092 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010093 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010094 return;
10095 }
John McCall0d1da222010-01-12 00:44:57 +000010096
John McCall6a61b522010-01-13 09:16:55 +000010097 switch (Cand->FailureKind) {
10098 case ovl_fail_too_many_arguments:
10099 case ovl_fail_too_few_arguments:
10100 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010101
John McCall6a61b522010-01-13 09:16:55 +000010102 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010103 return DiagnoseBadDeduction(S, Cand, NumArgs,
10104 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010105
John McCall578a1f82014-12-14 01:46:53 +000010106 case ovl_fail_illegal_constructor: {
10107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10108 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010109 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010110 return;
10111 }
10112
John McCallfe796dd2010-01-23 05:17:32 +000010113 case ovl_fail_trivial_conversion:
10114 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010115 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010116 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010117
John McCall65eb8792010-02-25 01:37:24 +000010118 case ovl_fail_bad_conversion: {
10119 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010120 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010121 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010122 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010123
John McCall6a61b522010-01-13 09:16:55 +000010124 // FIXME: this currently happens when we're called from SemaInit
10125 // when user-conversion overload fails. Figure out how to handle
10126 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010127 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010128 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010129
10130 case ovl_fail_bad_target:
10131 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010132
10133 case ovl_fail_enable_if:
10134 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010135
Yaxun Liu5b746652016-12-18 05:18:55 +000010136 case ovl_fail_ext_disabled:
10137 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10138
Richard Smithf9c59b72017-01-08 21:45:44 +000010139 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010140 // It's generally not interesting to note copy/move constructors here.
10141 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10142 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010143 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010144 diag::note_ovl_candidate_inherited_constructor_slice)
10145 << (Fn->getPrimaryTemplate() ? 1 : 0)
10146 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010147 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10148 return;
10149
George Burgess IV7204ed92016-01-07 02:26:57 +000010150 case ovl_fail_addr_not_available: {
10151 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10152 (void)Available;
10153 assert(!Available);
10154 break;
10155 }
John McCall65eb8792010-02-25 01:37:24 +000010156 }
John McCalld3224162010-01-08 00:58:21 +000010157}
10158
Richard Smith17c00b42014-11-12 01:24:00 +000010159static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010160 // Desugar the type of the surrogate down to a function type,
10161 // retaining as many typedefs as possible while still showing
10162 // the function type (and, therefore, its parameter types).
10163 QualType FnType = Cand->Surrogate->getConversionType();
10164 bool isLValueReference = false;
10165 bool isRValueReference = false;
10166 bool isPointer = false;
10167 if (const LValueReferenceType *FnTypeRef =
10168 FnType->getAs<LValueReferenceType>()) {
10169 FnType = FnTypeRef->getPointeeType();
10170 isLValueReference = true;
10171 } else if (const RValueReferenceType *FnTypeRef =
10172 FnType->getAs<RValueReferenceType>()) {
10173 FnType = FnTypeRef->getPointeeType();
10174 isRValueReference = true;
10175 }
10176 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10177 FnType = FnTypePtr->getPointeeType();
10178 isPointer = true;
10179 }
10180 // Desugar down to a function type.
10181 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10182 // Reconstruct the pointer/reference as appropriate.
10183 if (isPointer) FnType = S.Context.getPointerType(FnType);
10184 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10185 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10186
10187 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10188 << FnType;
10189}
10190
Richard Smith17c00b42014-11-12 01:24:00 +000010191static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10192 SourceLocation OpLoc,
10193 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010194 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010195 std::string TypeStr("operator");
10196 TypeStr += Opc;
10197 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010198 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010199 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010200 TypeStr += ")";
10201 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10202 } else {
10203 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010204 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010205 TypeStr += ")";
10206 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10207 }
10208}
10209
Richard Smith17c00b42014-11-12 01:24:00 +000010210static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10211 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010212 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010213 if (ICS.isBad()) break; // all meaningless after first invalid
10214 if (!ICS.isAmbiguous()) continue;
10215
Richard Smithc2bebe92016-05-11 20:37:46 +000010216 ICS.DiagnoseAmbiguousConversion(
10217 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010218 }
10219}
10220
Larisse Voufo98b20f12013-07-19 23:00:19 +000010221static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010222 if (Cand->Function)
10223 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010224 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010225 return Cand->Surrogate->getLocation();
10226 return SourceLocation();
10227}
10228
Larisse Voufo98b20f12013-07-19 23:00:19 +000010229static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010230 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010231 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010232 case Sema::TDK_NonDependentConversionFailure:
10233 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010234
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010235 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010236 case Sema::TDK_Incomplete:
10237 return 1;
10238
10239 case Sema::TDK_Underqualified:
10240 case Sema::TDK_Inconsistent:
10241 return 2;
10242
10243 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010244 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010245 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010246 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010247 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010248 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010249 return 3;
10250
10251 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010252 return 4;
10253
10254 case Sema::TDK_InvalidExplicitArguments:
10255 return 5;
10256
10257 case Sema::TDK_TooManyArguments:
10258 case Sema::TDK_TooFewArguments:
10259 return 6;
10260 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010261 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010262}
10263
Richard Smith17c00b42014-11-12 01:24:00 +000010264namespace {
John McCallad2587a2010-01-12 00:48:53 +000010265struct CompareOverloadCandidatesForDisplay {
10266 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010267 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010268 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010269 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010270
Richard Smith67ef14f2017-09-26 18:37:55 +000010271 CompareOverloadCandidatesForDisplay(
10272 Sema &S, SourceLocation Loc, size_t NArgs,
10273 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010274 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010275
10276 bool operator()(const OverloadCandidate *L,
10277 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010278 // Fast-path this check.
10279 if (L == R) return false;
10280
John McCall12f97bc2010-01-08 04:41:39 +000010281 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010282 if (L->Viable) {
10283 if (!R->Viable) return true;
10284
10285 // TODO: introduce a tri-valued comparison for overload
10286 // candidates. Would be more worthwhile if we had a sort
10287 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010288 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10289 return true;
10290 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10291 return false;
John McCallad2587a2010-01-12 00:48:53 +000010292 } else if (R->Viable)
10293 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010294
John McCall3712d9e2010-01-15 23:32:50 +000010295 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010296
John McCall3712d9e2010-01-15 23:32:50 +000010297 // Criteria by which we can sort non-viable candidates:
10298 if (!L->Viable) {
10299 // 1. Arity mismatches come after other candidates.
10300 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010301 L->FailureKind == ovl_fail_too_few_arguments) {
10302 if (R->FailureKind == ovl_fail_too_many_arguments ||
10303 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010304 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10305 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10306 if (LDist == RDist) {
10307 if (L->FailureKind == R->FailureKind)
10308 // Sort non-surrogates before surrogates.
10309 return !L->IsSurrogate && R->IsSurrogate;
10310 // Sort candidates requiring fewer parameters than there were
10311 // arguments given after candidates requiring more parameters
10312 // than there were arguments given.
10313 return L->FailureKind == ovl_fail_too_many_arguments;
10314 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010315 return LDist < RDist;
10316 }
John McCall3712d9e2010-01-15 23:32:50 +000010317 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010318 }
John McCall3712d9e2010-01-15 23:32:50 +000010319 if (R->FailureKind == ovl_fail_too_many_arguments ||
10320 R->FailureKind == ovl_fail_too_few_arguments)
10321 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010322
John McCallfe796dd2010-01-23 05:17:32 +000010323 // 2. Bad conversions come first and are ordered by the number
10324 // of bad conversions and quality of good conversions.
10325 if (L->FailureKind == ovl_fail_bad_conversion) {
10326 if (R->FailureKind != ovl_fail_bad_conversion)
10327 return true;
10328
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010329 // The conversion that can be fixed with a smaller number of changes,
10330 // comes first.
10331 unsigned numLFixes = L->Fix.NumConversionsFixed;
10332 unsigned numRFixes = R->Fix.NumConversionsFixed;
10333 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10334 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010335 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010336 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010337 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010338
John McCallfe796dd2010-01-23 05:17:32 +000010339 // If there's any ordering between the defined conversions...
10340 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010341 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010342
10343 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010344 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010345 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010346 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010347 L->Conversions[I],
10348 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010349 case ImplicitConversionSequence::Better:
10350 leftBetter++;
10351 break;
10352
10353 case ImplicitConversionSequence::Worse:
10354 leftBetter--;
10355 break;
10356
10357 case ImplicitConversionSequence::Indistinguishable:
10358 break;
10359 }
10360 }
10361 if (leftBetter > 0) return true;
10362 if (leftBetter < 0) return false;
10363
10364 } else if (R->FailureKind == ovl_fail_bad_conversion)
10365 return false;
10366
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010367 if (L->FailureKind == ovl_fail_bad_deduction) {
10368 if (R->FailureKind != ovl_fail_bad_deduction)
10369 return true;
10370
10371 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10372 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010373 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010374 } else if (R->FailureKind == ovl_fail_bad_deduction)
10375 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010376
John McCall3712d9e2010-01-15 23:32:50 +000010377 // TODO: others?
10378 }
10379
10380 // Sort everything else by location.
10381 SourceLocation LLoc = GetLocationForCandidate(L);
10382 SourceLocation RLoc = GetLocationForCandidate(R);
10383
10384 // Put candidates without locations (e.g. builtins) at the end.
10385 if (LLoc.isInvalid()) return false;
10386 if (RLoc.isInvalid()) return true;
10387
10388 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010389 }
10390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010391}
John McCall12f97bc2010-01-08 04:41:39 +000010392
John McCallfe796dd2010-01-23 05:17:32 +000010393/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010394/// computes up to the first bad conversion. Produces the FixIt set if
10395/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010396static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10397 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010398 assert(!Cand->Viable);
10399
10400 // Don't do anything on failures other than bad conversion.
10401 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10402
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010403 // We only want the FixIts if all the arguments can be corrected.
10404 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010405 // Use a implicit copy initialization to check conversion fixes.
10406 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010407
Richard Smith6eedfe72017-01-09 08:01:21 +000010408 // Attempt to fix the bad conversion.
10409 unsigned ConvCount = Cand->Conversions.size();
10410 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10411 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010412 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010413 if (Cand->Conversions[ConvIdx].isInitialized() &&
10414 Cand->Conversions[ConvIdx].isBad()) {
10415 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010416 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010417 }
John McCallfe796dd2010-01-23 05:17:32 +000010418 }
10419
Douglas Gregoradc7a702010-04-16 17:45:54 +000010420 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010421 // operation somehow.
10422 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010423
Richard Smith14ead302017-01-10 20:19:21 +000010424 unsigned ConvIdx = 0;
10425 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010426
10427 if (Cand->IsSurrogate) {
10428 QualType ConvType
10429 = Cand->Surrogate->getConversionType().getNonReferenceType();
10430 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10431 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010432 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10433 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10434 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010435 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010436 ParamTypes =
10437 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010438 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010439 !isa<CXXConstructorDecl>(Cand->Function)) {
10440 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10441 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010442 }
Richard Smith14ead302017-01-10 20:19:21 +000010443 } else {
10444 // Builtin operator.
10445 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010446 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010447 }
10448
10449 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010450 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010451 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010452 // We've already checked this conversion.
10453 } else if (ArgIdx < ParamTypes.size()) {
10454 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010455 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10456 Args[ArgIdx]->getType());
10457 else {
10458 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010459 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010460 SuppressUserConversions,
10461 /*InOverloadResolution=*/true,
10462 /*AllowObjCWritebackConversion=*/
10463 S.getLangOpts().ObjCAutoRefCount);
10464 // Store the FixIt in the candidate if it exists.
10465 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10466 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10467 }
10468 } else
John McCallfe796dd2010-01-23 05:17:32 +000010469 Cand->Conversions[ConvIdx].setEllipsis();
10470 }
10471}
10472
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010473/// PrintOverloadCandidates - When overload resolution fails, prints
10474/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010475/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010476void OverloadCandidateSet::NoteCandidates(
10477 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10478 StringRef Opc, SourceLocation OpLoc,
10479 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010480 // Sort the candidates by viability and position. Sorting directly would
10481 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010482 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010483 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10484 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010485 if (!Filter(*Cand))
10486 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010487 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010488 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010489 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010490 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010491 if (Cand->Function || Cand->IsSurrogate)
10492 Cands.push_back(Cand);
10493 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10494 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010495 }
10496 }
10497
John McCallad2587a2010-01-12 00:48:53 +000010498 std::sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010499 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010500
John McCall0d1da222010-01-12 00:44:57 +000010501 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010502
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010503 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010504 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010505 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010506 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10507 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010508
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010509 // Set an arbitrary limit on the number of candidate functions we'll spam
10510 // the user with. FIXME: This limit should depend on details of the
10511 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010512 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010513 break;
10514 }
10515 ++CandsShown;
10516
John McCalld3224162010-01-08 00:58:21 +000010517 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010518 NoteFunctionCandidate(S, Cand, Args.size(),
10519 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010520 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010521 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010522 else {
10523 assert(Cand->Viable &&
10524 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010525 // Generally we only see ambiguities including viable builtin
10526 // operators if overload resolution got screwed up by an
10527 // ambiguous user-defined conversion.
10528 //
10529 // FIXME: It's quite possible for different conversions to see
10530 // different ambiguities, though.
10531 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010532 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010533 ReportedAmbiguousConversions = true;
10534 }
John McCalld3224162010-01-08 00:58:21 +000010535
John McCall0d1da222010-01-12 00:44:57 +000010536 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010537 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010538 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010539 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010540
10541 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010542 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010543}
10544
Larisse Voufo98b20f12013-07-19 23:00:19 +000010545static SourceLocation
10546GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10547 return Cand->Specialization ? Cand->Specialization->getLocation()
10548 : SourceLocation();
10549}
10550
Richard Smith17c00b42014-11-12 01:24:00 +000010551namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010552struct CompareTemplateSpecCandidatesForDisplay {
10553 Sema &S;
10554 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10555
10556 bool operator()(const TemplateSpecCandidate *L,
10557 const TemplateSpecCandidate *R) {
10558 // Fast-path this check.
10559 if (L == R)
10560 return false;
10561
10562 // Assuming that both candidates are not matches...
10563
10564 // Sort by the ranking of deduction failures.
10565 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10566 return RankDeductionFailure(L->DeductionFailure) <
10567 RankDeductionFailure(R->DeductionFailure);
10568
10569 // Sort everything else by location.
10570 SourceLocation LLoc = GetLocationForCandidate(L);
10571 SourceLocation RLoc = GetLocationForCandidate(R);
10572
10573 // Put candidates without locations (e.g. builtins) at the end.
10574 if (LLoc.isInvalid())
10575 return false;
10576 if (RLoc.isInvalid())
10577 return true;
10578
10579 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10580 }
10581};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010582}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010583
10584/// Diagnose a template argument deduction failure.
10585/// We are treating these failures as overload failures due to bad
10586/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010587void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10588 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010589 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010590 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010591}
10592
10593void TemplateSpecCandidateSet::destroyCandidates() {
10594 for (iterator i = begin(), e = end(); i != e; ++i) {
10595 i->DeductionFailure.Destroy();
10596 }
10597}
10598
10599void TemplateSpecCandidateSet::clear() {
10600 destroyCandidates();
10601 Candidates.clear();
10602}
10603
10604/// NoteCandidates - When no template specialization match is found, prints
10605/// diagnostic messages containing the non-matching specializations that form
10606/// the candidate set.
10607/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10608/// OCD == OCD_AllCandidates and Cand->Viable == false.
10609void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10610 // Sort the candidates by position (assuming no candidate is a match).
10611 // Sorting directly would be prohibitive, so we make a set of pointers
10612 // and sort those.
10613 SmallVector<TemplateSpecCandidate *, 32> Cands;
10614 Cands.reserve(size());
10615 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10616 if (Cand->Specialization)
10617 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010618 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010619 // in general, want to list every possible builtin candidate.
10620 }
10621
10622 std::sort(Cands.begin(), Cands.end(),
10623 CompareTemplateSpecCandidatesForDisplay(S));
10624
10625 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10626 // for generalization purposes (?).
10627 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10628
10629 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10630 unsigned CandsShown = 0;
10631 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10632 TemplateSpecCandidate *Cand = *I;
10633
10634 // Set an arbitrary limit on the number of candidates we'll spam
10635 // the user with. FIXME: This limit should depend on details of the
10636 // candidate list.
10637 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10638 break;
10639 ++CandsShown;
10640
10641 assert(Cand->Specialization &&
10642 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010643 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010644 }
10645
10646 if (I != E)
10647 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10648}
10649
Douglas Gregorb491ed32011-02-19 21:32:49 +000010650// [PossiblyAFunctionType] --> [Return]
10651// NonFunctionType --> NonFunctionType
10652// R (A) --> R(A)
10653// R (*)(A) --> R (A)
10654// R (&)(A) --> R (A)
10655// R (S::*)(A) --> R (A)
10656QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10657 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010658 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010659 PossiblyAFunctionType->getAs<PointerType>())
10660 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010661 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010662 PossiblyAFunctionType->getAs<ReferenceType>())
10663 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010664 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010665 PossiblyAFunctionType->getAs<MemberPointerType>())
10666 Ret = MemTypePtr->getPointeeType();
10667 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010668 Context.getCanonicalType(Ret).getUnqualifiedType();
10669 return Ret;
10670}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010671
Richard Smith9095e5b2016-11-01 01:31:23 +000010672static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10673 bool Complain = true) {
10674 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10675 S.DeduceReturnType(FD, Loc, Complain))
10676 return true;
10677
10678 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10679 if (S.getLangOpts().CPlusPlus1z &&
10680 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10681 !S.ResolveExceptionSpec(Loc, FPT))
10682 return true;
10683
10684 return false;
10685}
10686
Richard Smith17c00b42014-11-12 01:24:00 +000010687namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010688// A helper class to help with address of function resolution
10689// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010690class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010691 Sema& S;
10692 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010693 const QualType& TargetType;
10694 QualType TargetFunctionType; // Extracted function type from target type
10695
Douglas Gregorb491ed32011-02-19 21:32:49 +000010696 bool Complain;
10697 //DeclAccessPair& ResultFunctionAccessPair;
10698 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010699
Douglas Gregorb491ed32011-02-19 21:32:49 +000010700 bool TargetTypeIsNonStaticMemberFunction;
10701 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010702 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010703 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010704
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010705 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010706 OverloadExpr *OvlExpr;
10707 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010708 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010709 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010710
Douglas Gregorb491ed32011-02-19 21:32:49 +000010711public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010712 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10713 const QualType &TargetType, bool Complain)
10714 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10715 Complain(Complain), Context(S.getASTContext()),
10716 TargetTypeIsNonStaticMemberFunction(
10717 !!TargetType->getAs<MemberPointerType>()),
10718 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010719 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010720 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010721 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10722 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010723 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010724 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010725
David Majnemera4f7c7a2013-08-01 06:13:59 +000010726 if (TargetFunctionType->isFunctionType()) {
10727 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10728 if (!UME->isImplicitAccess() &&
10729 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10730 StaticMemberFunctionFromBoundPointer = true;
10731 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10732 DeclAccessPair dap;
10733 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10734 OvlExpr, false, &dap)) {
10735 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10736 if (!Method->isStatic()) {
10737 // If the target type is a non-function type and the function found
10738 // is a non-static member function, pretend as if that was the
10739 // target, it's the only possible type to end up with.
10740 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010741
David Majnemera4f7c7a2013-08-01 06:13:59 +000010742 // And skip adding the function if its not in the proper form.
10743 // We'll diagnose this due to an empty set of functions.
10744 if (!OvlExprInfo.HasFormOfMemberPointer)
10745 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010746 }
10747
David Majnemera4f7c7a2013-08-01 06:13:59 +000010748 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010749 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010750 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010751 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010752
Douglas Gregorb491ed32011-02-19 21:32:49 +000010753 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010754 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010755
Douglas Gregorb491ed32011-02-19 21:32:49 +000010756 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10757 // C++ [over.over]p4:
10758 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010759 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010760 if (FoundNonTemplateFunction)
10761 EliminateAllTemplateMatches();
10762 else
10763 EliminateAllExceptMostSpecializedTemplate();
10764 }
10765 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010766
Justin Lebar25c4a812016-03-29 16:24:16 +000010767 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010768 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010769 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010770
10771 bool hasComplained() const { return HasComplained; }
10772
Douglas Gregorb491ed32011-02-19 21:32:49 +000010773private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010774 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10775 QualType Discard;
10776 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010777 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010778 }
10779
George Burgess IV6da4c202016-03-23 02:33:58 +000010780 /// \return true if A is considered a better overload candidate for the
10781 /// desired type than B.
10782 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10783 // If A doesn't have exactly the correct type, we don't want to classify it
10784 // as "better" than anything else. This way, the user is required to
10785 // disambiguate for us if there are multiple candidates and no exact match.
10786 return candidateHasExactlyCorrectType(A) &&
10787 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010788 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010789 }
10790
10791 /// \return true if we were able to eliminate all but one overload candidate,
10792 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010793 bool eliminiateSuboptimalOverloadCandidates() {
10794 // Same algorithm as overload resolution -- one pass to pick the "best",
10795 // another pass to be sure that nothing is better than the best.
10796 auto Best = Matches.begin();
10797 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10798 if (isBetterCandidate(I->second, Best->second))
10799 Best = I;
10800
10801 const FunctionDecl *BestFn = Best->second;
10802 auto IsBestOrInferiorToBest = [this, BestFn](
10803 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10804 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10805 };
10806
10807 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10808 // option, so we can potentially give the user a better error
10809 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10810 return false;
10811 Matches[0] = *Best;
10812 Matches.resize(1);
10813 return true;
10814 }
10815
Douglas Gregorb491ed32011-02-19 21:32:49 +000010816 bool isTargetTypeAFunction() const {
10817 return TargetFunctionType->isFunctionType();
10818 }
10819
10820 // [ToType] [Return]
10821
10822 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10823 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10824 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10825 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10826 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10827 }
10828
10829 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010830 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010831 const DeclAccessPair& CurAccessFunPair) {
10832 if (CXXMethodDecl *Method
10833 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10834 // Skip non-static function templates when converting to pointer, and
10835 // static when converting to member pointer.
10836 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10837 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010838 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010839 else if (TargetTypeIsNonStaticMemberFunction)
10840 return false;
10841
10842 // C++ [over.over]p2:
10843 // If the name is a function template, template argument deduction is
10844 // done (14.8.2.2), and if the argument deduction succeeds, the
10845 // resulting template argument list is used to generate a single
10846 // function template specialization, which is added to the set of
10847 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010848 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010849 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010850 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010851 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010852 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010853 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010854 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010855 // Make a note of the failed deduction for diagnostics.
10856 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010857 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010858 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010859 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010860 }
10861
Douglas Gregor19a41f12013-04-17 08:45:07 +000010862 // Template argument deduction ensures that we have an exact match or
10863 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010864 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010865 assert(S.isSameOrCompatibleFunctionType(
10866 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010867 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010868
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010869 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010870 return false;
10871
Douglas Gregorb491ed32011-02-19 21:32:49 +000010872 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10873 return true;
10874 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010875
10876 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010877 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010879 // Skip non-static functions when converting to pointer, and static
10880 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010881 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10882 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010883 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010884 else if (TargetTypeIsNonStaticMemberFunction)
10885 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010886
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010887 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010888 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010889 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010890 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010891 return false;
10892
Richard Smith2a7d4812013-05-04 07:00:32 +000010893 // If any candidate has a placeholder return type, trigger its deduction
10894 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010895 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10896 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010897 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010898 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010899 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010900
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010901 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010902 return false;
10903
George Burgess IV6da4c202016-03-23 02:33:58 +000010904 // If we're in C, we need to support types that aren't exactly identical.
10905 if (!S.getLangOpts().CPlusPlus ||
10906 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010907 Matches.push_back(std::make_pair(
10908 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010909 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010910 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010911 }
Mike Stump11289f42009-09-09 15:08:12 +000010912 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010913
Douglas Gregorb491ed32011-02-19 21:32:49 +000010914 return false;
10915 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010916
Douglas Gregorb491ed32011-02-19 21:32:49 +000010917 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10918 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010919
Douglas Gregorb491ed32011-02-19 21:32:49 +000010920 // If the overload expression doesn't have the form of a pointer to
10921 // member, don't try to convert it to a pointer-to-member type.
10922 if (IsInvalidFormOfPointerToMemberFunction())
10923 return false;
10924
10925 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010926 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010927 I != E; ++I) {
10928 // Look through any using declarations to find the underlying function.
10929 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10930
10931 // C++ [over.over]p3:
10932 // Non-member functions and static member functions match
10933 // targets of type "pointer-to-function" or "reference-to-function."
10934 // Nonstatic member functions match targets of
10935 // type "pointer-to-member-function."
10936 // Note that according to DR 247, the containing class does not matter.
10937 if (FunctionTemplateDecl *FunctionTemplate
10938 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10939 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10940 Ret = true;
10941 }
10942 // If we have explicit template arguments supplied, skip non-templates.
10943 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10944 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10945 Ret = true;
10946 }
10947 assert(Ret || Matches.empty());
10948 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010949 }
10950
Douglas Gregorb491ed32011-02-19 21:32:49 +000010951 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010952 // [...] and any given function template specialization F1 is
10953 // eliminated if the set contains a second function template
10954 // specialization whose function template is more specialized
10955 // than the function template of F1 according to the partial
10956 // ordering rules of 14.5.5.2.
10957
10958 // The algorithm specified above is quadratic. We instead use a
10959 // two-pass algorithm (similar to the one used to identify the
10960 // best viable function in an overload set) that identifies the
10961 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010962
10963 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10964 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10965 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010966
Larisse Voufo98b20f12013-07-19 23:00:19 +000010967 // TODO: It looks like FailedCandidates does not serve much purpose
10968 // here, since the no_viable diagnostic has index 0.
10969 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010970 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010971 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010972 S.PDiag(diag::err_addr_ovl_ambiguous)
10973 << Matches[0].second->getDeclName(),
10974 S.PDiag(diag::note_ovl_candidate)
10975 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010976 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010977
Douglas Gregorb491ed32011-02-19 21:32:49 +000010978 if (Result != MatchesCopy.end()) {
10979 // Make it the first and only element
10980 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10981 Matches[0].second = cast<FunctionDecl>(*Result);
10982 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010983 } else
10984 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010986
Douglas Gregorb491ed32011-02-19 21:32:49 +000010987 void EliminateAllTemplateMatches() {
10988 // [...] any function template specializations in the set are
10989 // eliminated if the set also contains a non-template function, [...]
10990 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010991 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010992 ++I;
10993 else {
10994 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010995 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010996 }
10997 }
10998 }
10999
Artem Belevich94a55e82015-09-22 17:22:59 +000011000 void EliminateSuboptimalCudaMatches() {
11001 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11002 }
11003
Douglas Gregorb491ed32011-02-19 21:32:49 +000011004public:
11005 void ComplainNoMatchesFound() const {
11006 assert(Matches.empty());
11007 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11008 << OvlExpr->getName() << TargetFunctionType
11009 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011010 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011011 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11012 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011013 else {
11014 // We have some deduction failure messages. Use them to diagnose
11015 // the function templates, and diagnose the non-template candidates
11016 // normally.
11017 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11018 IEnd = OvlExpr->decls_end();
11019 I != IEnd; ++I)
11020 if (FunctionDecl *Fun =
11021 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011022 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011023 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011024 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011025 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11026 }
11027 }
11028
Douglas Gregorb491ed32011-02-19 21:32:49 +000011029 bool IsInvalidFormOfPointerToMemberFunction() const {
11030 return TargetTypeIsNonStaticMemberFunction &&
11031 !OvlExprInfo.HasFormOfMemberPointer;
11032 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011033
Douglas Gregorb491ed32011-02-19 21:32:49 +000011034 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11035 // TODO: Should we condition this on whether any functions might
11036 // have matched, or is it more appropriate to do that in callers?
11037 // TODO: a fixit wouldn't hurt.
11038 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11039 << TargetType << OvlExpr->getSourceRange();
11040 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011041
11042 bool IsStaticMemberFunctionFromBoundPointer() const {
11043 return StaticMemberFunctionFromBoundPointer;
11044 }
11045
11046 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11047 S.Diag(OvlExpr->getLocStart(),
11048 diag::err_invalid_form_pointer_member_function)
11049 << OvlExpr->getSourceRange();
11050 }
11051
Douglas Gregorb491ed32011-02-19 21:32:49 +000011052 void ComplainOfInvalidConversion() const {
11053 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11054 << OvlExpr->getName() << TargetType;
11055 }
11056
11057 void ComplainMultipleMatchesFound() const {
11058 assert(Matches.size() > 1);
11059 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11060 << OvlExpr->getName()
11061 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011062 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11063 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011064 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011065
11066 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11067
Douglas Gregorb491ed32011-02-19 21:32:49 +000011068 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011069
Douglas Gregorb491ed32011-02-19 21:32:49 +000011070 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011071 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011072 return Matches[0].second;
11073 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011074
Douglas Gregorb491ed32011-02-19 21:32:49 +000011075 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011076 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011077 return &Matches[0].first;
11078 }
11079};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011080}
Richard Smith17c00b42014-11-12 01:24:00 +000011081
Douglas Gregorb491ed32011-02-19 21:32:49 +000011082/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11083/// an overloaded function (C++ [over.over]), where @p From is an
11084/// expression with overloaded function type and @p ToType is the type
11085/// we're trying to resolve to. For example:
11086///
11087/// @code
11088/// int f(double);
11089/// int f(int);
11090///
11091/// int (*pfd)(double) = f; // selects f(double)
11092/// @endcode
11093///
11094/// This routine returns the resulting FunctionDecl if it could be
11095/// resolved, and NULL otherwise. When @p Complain is true, this
11096/// routine will emit diagnostics if there is an error.
11097FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011098Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11099 QualType TargetType,
11100 bool Complain,
11101 DeclAccessPair &FoundResult,
11102 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011103 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011104
11105 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11106 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011107 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011108 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011109 bool ShouldComplain = Complain && !Resolver.hasComplained();
11110 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011111 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11112 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11113 else
11114 Resolver.ComplainNoMatchesFound();
11115 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011116 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011117 Resolver.ComplainMultipleMatchesFound();
11118 else if (NumMatches == 1) {
11119 Fn = Resolver.getMatchingFunctionDecl();
11120 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011121 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11122 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011123 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011124 if (Complain) {
11125 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11126 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11127 else
11128 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11129 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011130 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011131
11132 if (pHadMultipleCandidates)
11133 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011134 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011135}
11136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011137/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011138/// resolve that function to a single function that can have its address taken.
11139/// This will modify `Pair` iff it returns non-null.
11140///
11141/// This routine can only realistically succeed if all but one candidates in the
11142/// overload set for SrcExpr cannot have their addresses taken.
11143FunctionDecl *
11144Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11145 DeclAccessPair &Pair) {
11146 OverloadExpr::FindResult R = OverloadExpr::find(E);
11147 OverloadExpr *Ovl = R.Expression;
11148 FunctionDecl *Result = nullptr;
11149 DeclAccessPair DAP;
11150 // Don't use the AddressOfResolver because we're specifically looking for
11151 // cases where we have one overload candidate that lacks
11152 // enable_if/pass_object_size/...
11153 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11154 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11155 if (!FD)
11156 return nullptr;
11157
11158 if (!checkAddressOfFunctionIsAvailable(FD))
11159 continue;
11160
11161 // We have more than one result; quit.
11162 if (Result)
11163 return nullptr;
11164 DAP = I.getPair();
11165 Result = FD;
11166 }
11167
11168 if (Result)
11169 Pair = DAP;
11170 return Result;
11171}
11172
George Burgess IVbeca4a32016-06-08 00:34:22 +000011173/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11174/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11175/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011176/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011177///
11178/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11179/// Otherwise, returns true. This may emit diagnostics and return true.
11180bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011181 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011182 Expr *E = SrcExpr.get();
11183 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11184
11185 DeclAccessPair DAP;
11186 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11187 if (!Found)
11188 return false;
11189
11190 // Emitting multiple diagnostics for a function that is both inaccessible and
11191 // unavailable is consistent with our behavior elsewhere. So, always check
11192 // for both.
11193 DiagnoseUseOfDecl(Found, E->getExprLoc());
11194 CheckAddressOfMemberAccess(E, DAP);
11195 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011196 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011197 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11198 else
11199 SrcExpr = Fixed;
11200 return true;
11201}
11202
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011203/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011204/// resolve that overloaded function expression down to a single function.
11205///
11206/// This routine can only resolve template-ids that refer to a single function
11207/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011208/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011209/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011210///
11211/// If no template-ids are found, no diagnostics are emitted and NULL is
11212/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011213FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011214Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011215 bool Complain,
11216 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011217 // C++ [over.over]p1:
11218 // [...] [Note: any redundant set of parentheses surrounding the
11219 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011220 // C++ [over.over]p1:
11221 // [...] The overloaded function name can be preceded by the &
11222 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011223
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011224 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011225 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011226 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011227
11228 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011229 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011230 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011231
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011232 // Look through all of the overloaded functions, searching for one
11233 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011234 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011235 for (UnresolvedSetIterator I = ovl->decls_begin(),
11236 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011237 // C++0x [temp.arg.explicit]p3:
11238 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011239 // where deduction is not done, if a template argument list is
11240 // specified and it, along with any default template arguments,
11241 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011242 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011243 FunctionTemplateDecl *FunctionTemplate
11244 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011245
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011246 // C++ [over.over]p2:
11247 // If the name is a function template, template argument deduction is
11248 // done (14.8.2.2), and if the argument deduction succeeds, the
11249 // resulting template argument list is used to generate a single
11250 // function template specialization, which is added to the set of
11251 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011252 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011253 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011254 if (TemplateDeductionResult Result
11255 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011256 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011257 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011258 // Make a note of the failed deduction for diagnostics.
11259 // TODO: Actually use the failed-deduction info?
11260 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011261 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011262 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011263 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011264 }
11265
John McCall0009fcc2011-04-26 20:42:42 +000011266 assert(Specialization && "no specialization and no error?");
11267
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011268 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011269 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011270 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011271 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11272 << ovl->getName();
11273 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011274 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011275 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011276 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011277
John McCall0009fcc2011-04-26 20:42:42 +000011278 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011279 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011281
Richard Smith9095e5b2016-11-01 01:31:23 +000011282 if (Matched &&
11283 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011284 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011285
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011286 return Matched;
11287}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011288
Douglas Gregor1beec452011-03-12 01:48:56 +000011289
11290
11291
John McCall50a2c2c2011-10-11 23:14:30 +000011292// Resolve and fix an overloaded expression that can be resolved
11293// because it identifies a single function template specialization.
11294//
Douglas Gregor1beec452011-03-12 01:48:56 +000011295// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011296//
11297// Return true if it was logically possible to so resolve the
11298// expression, regardless of whether or not it succeeded. Always
11299// returns true if 'complain' is set.
11300bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11301 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011302 bool complain, SourceRange OpRangeForComplaining,
11303 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011304 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011305 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011306
John McCall50a2c2c2011-10-11 23:14:30 +000011307 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011308
John McCall0009fcc2011-04-26 20:42:42 +000011309 DeclAccessPair found;
11310 ExprResult SingleFunctionExpression;
11311 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11312 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011313 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011314 SrcExpr = ExprError();
11315 return true;
11316 }
John McCall0009fcc2011-04-26 20:42:42 +000011317
11318 // It is only correct to resolve to an instance method if we're
11319 // resolving a form that's permitted to be a pointer to member.
11320 // Otherwise we'll end up making a bound member expression, which
11321 // is illegal in all the contexts we resolve like this.
11322 if (!ovl.HasFormOfMemberPointer &&
11323 isa<CXXMethodDecl>(fn) &&
11324 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011325 if (!complain) return false;
11326
11327 Diag(ovl.Expression->getExprLoc(),
11328 diag::err_bound_member_function)
11329 << 0 << ovl.Expression->getSourceRange();
11330
11331 // TODO: I believe we only end up here if there's a mix of
11332 // static and non-static candidates (otherwise the expression
11333 // would have 'bound member' type, not 'overload' type).
11334 // Ideally we would note which candidate was chosen and why
11335 // the static candidates were rejected.
11336 SrcExpr = ExprError();
11337 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011338 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011339
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011340 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011341 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011342 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011343
11344 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011345 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011346 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011347 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011348 if (SingleFunctionExpression.isInvalid()) {
11349 SrcExpr = ExprError();
11350 return true;
11351 }
11352 }
John McCall0009fcc2011-04-26 20:42:42 +000011353 }
11354
11355 if (!SingleFunctionExpression.isUsable()) {
11356 if (complain) {
11357 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11358 << ovl.Expression->getName()
11359 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011360 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011361 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011362 NoteAllOverloadCandidates(SrcExpr.get());
11363
11364 SrcExpr = ExprError();
11365 return true;
11366 }
11367
11368 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011369 }
11370
John McCall50a2c2c2011-10-11 23:14:30 +000011371 SrcExpr = SingleFunctionExpression;
11372 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011373}
11374
Douglas Gregorcabea402009-09-22 15:41:20 +000011375/// \brief Add a single candidate to the overload set.
11376static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011377 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011378 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011379 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011380 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011381 bool PartialOverloading,
11382 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011383 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011384 if (isa<UsingShadowDecl>(Callee))
11385 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11386
Douglas Gregorcabea402009-09-22 15:41:20 +000011387 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011388 if (ExplicitTemplateArgs) {
11389 assert(!KnownValid && "Explicit template arguments?");
11390 return;
11391 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011392 // Prevent ill-formed function decls to be added as overload candidates.
11393 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11394 return;
11395
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011396 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11397 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011398 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011399 return;
John McCalld14a8642009-11-21 08:51:07 +000011400 }
11401
11402 if (FunctionTemplateDecl *FuncTemplate
11403 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011404 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011405 ExplicitTemplateArgs, Args, CandidateSet,
11406 /*SuppressUsedConversions=*/false,
11407 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011408 return;
11409 }
11410
Richard Smith95ce4f62011-06-26 22:19:54 +000011411 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011413
Douglas Gregorcabea402009-09-22 15:41:20 +000011414/// \brief Add the overload candidates named by callee and/or found by argument
11415/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011416void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011417 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011418 OverloadCandidateSet &CandidateSet,
11419 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011420
11421#ifndef NDEBUG
11422 // Verify that ArgumentDependentLookup is consistent with the rules
11423 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011424 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011425 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11426 // and let Y be the lookup set produced by argument dependent
11427 // lookup (defined as follows). If X contains
11428 //
11429 // -- a declaration of a class member, or
11430 //
11431 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011432 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011433 //
11434 // -- a declaration that is neither a function or a function
11435 // template
11436 //
11437 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011438
John McCall57500772009-12-16 12:17:52 +000011439 if (ULE->requiresADL()) {
11440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11441 E = ULE->decls_end(); I != E; ++I) {
11442 assert(!(*I)->getDeclContext()->isRecord());
11443 assert(isa<UsingShadowDecl>(*I) ||
11444 !(*I)->getDeclContext()->isFunctionOrMethod());
11445 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011446 }
11447 }
11448#endif
11449
John McCall57500772009-12-16 12:17:52 +000011450 // It would be nice to avoid this copy.
11451 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011452 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011453 if (ULE->hasExplicitTemplateArgs()) {
11454 ULE->copyTemplateArgumentsInto(TABuffer);
11455 ExplicitTemplateArgs = &TABuffer;
11456 }
11457
11458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11459 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011460 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11461 CandidateSet, PartialOverloading,
11462 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011463
John McCall57500772009-12-16 12:17:52 +000011464 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011465 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011466 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011467 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011468}
John McCalld681c392009-12-16 08:11:27 +000011469
Richard Smith0603bbb2013-06-12 22:56:54 +000011470/// Determine whether a declaration with the specified name could be moved into
11471/// a different namespace.
11472static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11473 switch (Name.getCXXOverloadedOperator()) {
11474 case OO_New: case OO_Array_New:
11475 case OO_Delete: case OO_Array_Delete:
11476 return false;
11477
11478 default:
11479 return true;
11480 }
11481}
11482
Richard Smith998a5912011-06-05 22:42:48 +000011483/// Attempt to recover from an ill-formed use of a non-dependent name in a
11484/// template, where the non-dependent name was declared after the template
11485/// was defined. This is common in code written for a compilers which do not
11486/// correctly implement two-stage name lookup.
11487///
11488/// Returns true if a viable candidate was found and a diagnostic was issued.
11489static bool
11490DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11491 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011492 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011493 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011494 ArrayRef<Expr *> Args,
11495 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011496 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011497 return false;
11498
11499 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011500 if (DC->isTransparentContext())
11501 continue;
11502
Richard Smith998a5912011-06-05 22:42:48 +000011503 SemaRef.LookupQualifiedName(R, DC);
11504
11505 if (!R.empty()) {
11506 R.suppressDiagnostics();
11507
11508 if (isa<CXXRecordDecl>(DC)) {
11509 // Don't diagnose names we find in classes; we get much better
11510 // diagnostics for these from DiagnoseEmptyLookup.
11511 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011512 if (DoDiagnoseEmptyLookup)
11513 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011514 return false;
11515 }
11516
Richard Smith100b24a2014-04-17 01:52:14 +000011517 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11519 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011520 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011521 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011522
11523 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011525 // No viable functions. Don't bother the user with notes for functions
11526 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011527 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011528 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011529 }
Richard Smith998a5912011-06-05 22:42:48 +000011530
11531 // Find the namespaces where ADL would have looked, and suggest
11532 // declaring the function there instead.
11533 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11534 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011536 AssociatedNamespaces,
11537 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011538 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011539 if (canBeDeclaredInNamespace(R.getLookupName())) {
11540 DeclContext *Std = SemaRef.getStdNamespace();
11541 for (Sema::AssociatedNamespaceSet::iterator
11542 it = AssociatedNamespaces.begin(),
11543 end = AssociatedNamespaces.end(); it != end; ++it) {
11544 // Never suggest declaring a function within namespace 'std'.
11545 if (Std && Std->Encloses(*it))
11546 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011547
Richard Smith0603bbb2013-06-12 22:56:54 +000011548 // Never suggest declaring a function within a namespace with a
11549 // reserved name, like __gnu_cxx.
11550 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11551 if (NS &&
11552 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11553 continue;
11554
11555 SuggestedNamespaces.insert(*it);
11556 }
Richard Smith998a5912011-06-05 22:42:48 +000011557 }
11558
11559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11560 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011561 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011562 SemaRef.Diag(Best->Function->getLocation(),
11563 diag::note_not_found_by_two_phase_lookup)
11564 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011565 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011566 SemaRef.Diag(Best->Function->getLocation(),
11567 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011569 } else {
11570 // FIXME: It would be useful to list the associated namespaces here,
11571 // but the diagnostics infrastructure doesn't provide a way to produce
11572 // a localized representation of a list of items.
11573 SemaRef.Diag(Best->Function->getLocation(),
11574 diag::note_not_found_by_two_phase_lookup)
11575 << R.getLookupName() << 2;
11576 }
11577
11578 // Try to recover by calling this function.
11579 return true;
11580 }
11581
11582 R.clear();
11583 }
11584
11585 return false;
11586}
11587
11588/// Attempt to recover from ill-formed use of a non-dependent operator in a
11589/// template, where the non-dependent operator was declared after the template
11590/// was defined.
11591///
11592/// Returns true if a viable candidate was found and a diagnostic was issued.
11593static bool
11594DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11595 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011596 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011597 DeclarationName OpName =
11598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011601 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011602 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011603}
11604
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011605namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011606class BuildRecoveryCallExprRAII {
11607 Sema &SemaRef;
11608public:
11609 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11610 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11611 SemaRef.IsBuildingRecoveryCallExpr = true;
11612 }
11613
11614 ~BuildRecoveryCallExprRAII() {
11615 SemaRef.IsBuildingRecoveryCallExpr = false;
11616 }
11617};
11618
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011619}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011620
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011621static std::unique_ptr<CorrectionCandidateCallback>
11622MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11623 bool HasTemplateArgs, bool AllowTypoCorrection) {
11624 if (!AllowTypoCorrection)
11625 return llvm::make_unique<NoTypoCorrectionCCC>();
11626 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11627 HasTemplateArgs, ME);
11628}
11629
John McCalld681c392009-12-16 08:11:27 +000011630/// Attempts to recover from a call where no functions were found.
11631///
11632/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011633static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011634BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011635 UnresolvedLookupExpr *ULE,
11636 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011637 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011638 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011639 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011640 // Do not try to recover if it is already building a recovery call.
11641 // This stops infinite loops for template instantiations like
11642 //
11643 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11644 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11645 //
11646 if (SemaRef.IsBuildingRecoveryCallExpr)
11647 return ExprError();
11648 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011649
11650 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011651 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011653
John McCall57500772009-12-16 12:17:52 +000011654 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011656 if (ULE->hasExplicitTemplateArgs()) {
11657 ULE->copyTemplateArgumentsInto(TABuffer);
11658 ExplicitTemplateArgs = &TABuffer;
11659 }
11660
John McCalld681c392009-12-16 08:11:27 +000011661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11662 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011663 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011664 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011665 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011666 ExplicitTemplateArgs, Args,
11667 &DoDiagnoseEmptyLookup) &&
11668 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11669 S, SS, R,
11670 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11671 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11672 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011673 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011674
John McCall57500772009-12-16 12:17:52 +000011675 assert(!R.empty() && "lookup results empty despite recovery");
11676
Richard Smith151c4562016-12-20 21:35:28 +000011677 // If recovery created an ambiguity, just bail out.
11678 if (R.isAmbiguous()) {
11679 R.suppressDiagnostics();
11680 return ExprError();
11681 }
11682
John McCall57500772009-12-16 12:17:52 +000011683 // Build an implicit member call if appropriate. Just drop the
11684 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011685 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011686 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011687 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11688 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011689 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011690 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011691 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011692 else
11693 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11694
11695 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011696 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011697
11698 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011699 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011700 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011701 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011702 MultiExprArg(Args.data(), Args.size()),
11703 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011704}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011705
Sam Panzer0f384432012-08-21 00:52:01 +000011706/// \brief Constructs and populates an OverloadedCandidateSet from
11707/// the given function.
11708/// \returns true when an the ExprResult output parameter has been set.
11709bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11710 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011711 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011712 SourceLocation RParenLoc,
11713 OverloadCandidateSet *CandidateSet,
11714 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011715#ifndef NDEBUG
11716 if (ULE->requiresADL()) {
11717 // To do ADL, we must have found an unqualified name.
11718 assert(!ULE->getQualifier() && "qualified name with ADL");
11719
11720 // We don't perform ADL for implicit declarations of builtins.
11721 // Verify that this was correctly set up.
11722 FunctionDecl *F;
11723 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11724 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11725 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011726 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011727
John McCall57500772009-12-16 12:17:52 +000011728 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011729 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011730 }
John McCall57500772009-12-16 12:17:52 +000011731#endif
11732
John McCall4124c492011-10-17 18:40:02 +000011733 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011734 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011735 *Result = ExprError();
11736 return true;
11737 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011738
John McCall57500772009-12-16 12:17:52 +000011739 // Add the functions denoted by the callee to the set of candidate
11740 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011741 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011742
Hans Wennborgb2747382015-06-12 21:23:23 +000011743 if (getLangOpts().MSVCCompat &&
11744 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011745 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11746
11747 OverloadCandidateSet::iterator Best;
11748 if (CandidateSet->empty() ||
11749 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11750 OR_No_Viable_Function) {
11751 // In Microsoft mode, if we are inside a template class member function then
11752 // create a type dependent CallExpr. The goal is to postpone name lookup
11753 // to instantiation time to be able to search into type dependent base
11754 // classes.
11755 CallExpr *CE = new (Context) CallExpr(
11756 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011757 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011758 CE->setValueDependent(true);
11759 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011760 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011761 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011762 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011763 }
John McCalld681c392009-12-16 08:11:27 +000011764
Hans Wennborg64937c62015-06-11 21:21:57 +000011765 if (CandidateSet->empty())
11766 return false;
11767
John McCall4124c492011-10-17 18:40:02 +000011768 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011769 return false;
11770}
John McCall4124c492011-10-17 18:40:02 +000011771
Sam Panzer0f384432012-08-21 00:52:01 +000011772/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11773/// the completed call expression. If overload resolution fails, emits
11774/// diagnostics and returns ExprError()
11775static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11776 UnresolvedLookupExpr *ULE,
11777 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011778 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011779 SourceLocation RParenLoc,
11780 Expr *ExecConfig,
11781 OverloadCandidateSet *CandidateSet,
11782 OverloadCandidateSet::iterator *Best,
11783 OverloadingResult OverloadResult,
11784 bool AllowTypoCorrection) {
11785 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011786 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011787 RParenLoc, /*EmptyLookup=*/true,
11788 AllowTypoCorrection);
11789
11790 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011791 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011792 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011793 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011794 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11795 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011796 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011797 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11798 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011799 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011800
Richard Smith998a5912011-06-05 22:42:48 +000011801 case OR_No_Viable_Function: {
11802 // Try to recover by looking for viable functions which the user might
11803 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011804 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011805 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011806 /*EmptyLookup=*/false,
11807 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011808 if (!Recovery.isInvalid())
11809 return Recovery;
11810
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011811 // If the user passes in a function that we can't take the address of, we
11812 // generally end up emitting really bad error messages. Here, we attempt to
11813 // emit better ones.
11814 for (const Expr *Arg : Args) {
11815 if (!Arg->getType()->isFunctionType())
11816 continue;
11817 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11818 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11819 if (FD &&
11820 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11821 Arg->getExprLoc()))
11822 return ExprError();
11823 }
11824 }
11825
11826 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11827 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011828 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011829 break;
Richard Smith998a5912011-06-05 22:42:48 +000011830 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011831
11832 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011833 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011834 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011835 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011836 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011837
Sam Panzer0f384432012-08-21 00:52:01 +000011838 case OR_Deleted: {
11839 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11840 << (*Best)->Function->isDeleted()
11841 << ULE->getName()
11842 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11843 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011844 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011845
Sam Panzer0f384432012-08-21 00:52:01 +000011846 // We emitted an error for the unvailable/deleted function call but keep
11847 // the call in the AST.
11848 FunctionDecl *FDecl = (*Best)->Function;
11849 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011850 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11851 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011852 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011853 }
11854
Douglas Gregorb412e172010-07-25 18:17:45 +000011855 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011856 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011857}
11858
George Burgess IV7204ed92016-01-07 02:26:57 +000011859static void markUnaddressableCandidatesUnviable(Sema &S,
11860 OverloadCandidateSet &CS) {
11861 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11862 if (I->Viable &&
11863 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11864 I->Viable = false;
11865 I->FailureKind = ovl_fail_addr_not_available;
11866 }
11867 }
11868}
11869
Sam Panzer0f384432012-08-21 00:52:01 +000011870/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11871/// (which eventually refers to the declaration Func) and the call
11872/// arguments Args/NumArgs, attempt to resolve the function call down
11873/// to a specific function. If overload resolution succeeds, returns
11874/// the call expression produced by overload resolution.
11875/// Otherwise, emits diagnostics and returns ExprError.
11876ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11877 UnresolvedLookupExpr *ULE,
11878 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011879 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011880 SourceLocation RParenLoc,
11881 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011882 bool AllowTypoCorrection,
11883 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011884 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11885 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011886 ExprResult result;
11887
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011888 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11889 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011890 return result;
11891
George Burgess IV7204ed92016-01-07 02:26:57 +000011892 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11893 // functions that aren't addressible are considered unviable.
11894 if (CalleesAddressIsTaken)
11895 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11896
Sam Panzer0f384432012-08-21 00:52:01 +000011897 OverloadCandidateSet::iterator Best;
11898 OverloadingResult OverloadResult =
11899 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11900
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011901 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011902 RParenLoc, ExecConfig, &CandidateSet,
11903 &Best, OverloadResult,
11904 AllowTypoCorrection);
11905}
11906
John McCall4c4c1df2010-01-26 03:27:55 +000011907static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011908 return Functions.size() > 1 ||
11909 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11910}
11911
Douglas Gregor084d8552009-03-13 23:49:33 +000011912/// \brief Create a unary operation that may resolve to an overloaded
11913/// operator.
11914///
11915/// \param OpLoc The location of the operator itself (e.g., '*').
11916///
Craig Toppera92ffb02015-12-10 08:51:49 +000011917/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011918///
James Dennett18348b62012-06-22 08:52:37 +000011919/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011920/// considered by overload resolution. The caller needs to build this
11921/// set based on the context using, e.g.,
11922/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11923/// set should not contain any member functions; those will be added
11924/// by CreateOverloadedUnaryOp().
11925///
James Dennett91738ff2012-06-22 10:32:46 +000011926/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011927ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011928Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011929 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000011930 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011931 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11932 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11933 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011934 // TODO: provide better source location info.
11935 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011936
John McCall4124c492011-10-17 18:40:02 +000011937 if (checkPlaceholderForOverload(*this, Input))
11938 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011939
Craig Topperc3ec1492014-05-26 06:22:03 +000011940 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011941 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011942
Douglas Gregor084d8552009-03-13 23:49:33 +000011943 // For post-increment and post-decrement, add the implicit '0' as
11944 // the second argument, so that we know this is a post-increment or
11945 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011946 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011947 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011948 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11949 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011950 NumArgs = 2;
11951 }
11952
Richard Smithe54c3072013-05-05 15:51:06 +000011953 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11954
Douglas Gregor084d8552009-03-13 23:49:33 +000011955 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011956 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011957 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11958 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011959
Craig Topperc3ec1492014-05-26 06:22:03 +000011960 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011961 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011962 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011963 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011964 /*ADL*/ true, IsOverloaded(Fns),
11965 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011966 return new (Context)
11967 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000011968 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000011969 }
11970
11971 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011972 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011973
11974 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011975 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011976
11977 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011978 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011979
John McCall4c4c1df2010-01-26 03:27:55 +000011980 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000011981 if (PerformADL) {
11982 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11983 /*ExplicitTemplateArgs*/nullptr,
11984 CandidateSet);
11985 }
John McCall4c4c1df2010-01-26 03:27:55 +000011986
Douglas Gregor084d8552009-03-13 23:49:33 +000011987 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011988 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011989
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011990 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11991
Douglas Gregor084d8552009-03-13 23:49:33 +000011992 // Perform overload resolution.
11993 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011994 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011995 case OR_Success: {
11996 // We found a built-in operator or an overloaded operator.
11997 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011998
Douglas Gregor084d8552009-03-13 23:49:33 +000011999 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012000 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012001 // We matched an overloaded operator. Build a call to that
12002 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012003
Douglas Gregor084d8552009-03-13 23:49:33 +000012004 // Convert the arguments.
12005 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012006 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012007
John Wiegley01296292011-04-08 18:41:53 +000012008 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012009 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012010 Best->FoundDecl, Method);
12011 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012012 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012013 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012014 } else {
12015 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012016 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012017 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012018 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012019 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012020 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012021 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012022 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012023 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012024 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012025 }
12026
Douglas Gregor084d8552009-03-13 23:49:33 +000012027 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012028 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012029 Base, HadMultipleCandidates,
12030 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012031 if (FnExpr.isInvalid())
12032 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012033
Richard Smithc1564702013-11-15 02:58:23 +000012034 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012035 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012036 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12037 ResultTy = ResultTy.getNonLValueExprType(Context);
12038
Eli Friedman030eee42009-11-18 03:58:17 +000012039 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012040 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012041 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012042 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012043
Alp Toker314cc812014-01-25 16:55:45 +000012044 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012045 return ExprError();
12046
George Burgess IVce6284b2017-01-28 02:19:40 +000012047 if (CheckFunctionCall(FnDecl, TheCall,
12048 FnDecl->getType()->castAs<FunctionProtoType>()))
12049 return ExprError();
12050
John McCallb268a282010-08-23 23:25:46 +000012051 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012052 } else {
12053 // We matched a built-in operator. Convert the arguments, then
12054 // break out so that we will build the appropriate built-in
12055 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012056 ExprResult InputRes = PerformImplicitConversion(
12057 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012058 if (InputRes.isInvalid())
12059 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012060 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012061 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012062 }
John Wiegley01296292011-04-08 18:41:53 +000012063 }
12064
12065 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012066 // This is an erroneous use of an operator which can be overloaded by
12067 // a non-member function. Check for non-member operators which were
12068 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012069 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012070 // FIXME: Recover by calling the found function.
12071 return ExprError();
12072
John Wiegley01296292011-04-08 18:41:53 +000012073 // No viable function; fall through to handling this as a
12074 // built-in operator, which will produce an error message for us.
12075 break;
12076
12077 case OR_Ambiguous:
12078 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12079 << UnaryOperator::getOpcodeStr(Opc)
12080 << Input->getType()
12081 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012082 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012083 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12084 return ExprError();
12085
12086 case OR_Deleted:
12087 Diag(OpLoc, diag::err_ovl_deleted_oper)
12088 << Best->Function->isDeleted()
12089 << UnaryOperator::getOpcodeStr(Opc)
12090 << getDeletedOrUnavailableSuffix(Best->Function)
12091 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012092 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012093 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012094 return ExprError();
12095 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012096
12097 // Either we found no viable overloaded operator or we matched a
12098 // built-in operator. In either case, fall through to trying to
12099 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012100 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012101}
12102
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012103/// \brief Create a binary operation that may resolve to an overloaded
12104/// operator.
12105///
12106/// \param OpLoc The location of the operator itself (e.g., '+').
12107///
Craig Toppera92ffb02015-12-10 08:51:49 +000012108/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012109///
James Dennett18348b62012-06-22 08:52:37 +000012110/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012111/// considered by overload resolution. The caller needs to build this
12112/// set based on the context using, e.g.,
12113/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12114/// set should not contain any member functions; those will be added
12115/// by CreateOverloadedBinOp().
12116///
12117/// \param LHS Left-hand argument.
12118/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012119ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012120Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012121 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012122 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012123 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012124 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012125 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012126
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012127 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12128 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12129
12130 // If either side is type-dependent, create an appropriate dependent
12131 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012132 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012133 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012134 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012135 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012136 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012137 return new (Context) BinaryOperator(
12138 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012139 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012140
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012141 return new (Context) CompoundAssignOperator(
12142 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12143 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012144 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012145 }
John McCall4c4c1df2010-01-26 03:27:55 +000012146
12147 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012148 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012149 // TODO: provide better source location info in DNLoc component.
12150 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012151 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012152 = UnresolvedLookupExpr::Create(Context, NamingClass,
12153 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012154 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012155 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012156 return new (Context)
12157 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012158 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012159 }
12160
John McCall4124c492011-10-17 18:40:02 +000012161 // Always do placeholder-like conversions on the RHS.
12162 if (checkPlaceholderForOverload(*this, Args[1]))
12163 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012164
John McCall526ab472011-10-25 17:37:35 +000012165 // Do placeholder-like conversion on the LHS; note that we should
12166 // not get here with a PseudoObject LHS.
12167 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012168 if (checkPlaceholderForOverload(*this, Args[0]))
12169 return ExprError();
12170
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012171 // If this is the assignment operator, we only perform overload resolution
12172 // if the left-hand side is a class or enumeration type. This is actually
12173 // a hack. The standard requires that we do overload resolution between the
12174 // various built-in candidates, but as DR507 points out, this can lead to
12175 // problems. So we do it this way, which pretty much follows what GCC does.
12176 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012177 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012178 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012179
John McCalle26a8722010-12-04 08:14:53 +000012180 // If this is the .* operator, which is not overloadable, just
12181 // create a built-in binary operator.
12182 if (Opc == BO_PtrMemD)
12183 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12184
Douglas Gregor084d8552009-03-13 23:49:33 +000012185 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012186 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012187
12188 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012189 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012190
12191 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012192 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012193
Richard Smith0daabd72014-09-23 20:31:39 +000012194 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12195 // performed for an assignment operator (nor for operator[] nor operator->,
12196 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012197 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012198 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12199 /*ExplicitTemplateArgs*/ nullptr,
12200 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012201
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012202 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012203 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012204
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012205 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12206
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012207 // Perform overload resolution.
12208 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012209 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012210 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012211 // We found a built-in operator or an overloaded operator.
12212 FunctionDecl *FnDecl = Best->Function;
12213
12214 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012215 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012216 // We matched an overloaded operator. Build a call to that
12217 // operator.
12218
12219 // Convert the arguments.
12220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012221 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012222 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012223
Chandler Carruth8e543b32010-12-12 08:17:55 +000012224 ExprResult Arg1 =
12225 PerformCopyInitialization(
12226 InitializedEntity::InitializeParameter(Context,
12227 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012228 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012229 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012230 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012231
John Wiegley01296292011-04-08 18:41:53 +000012232 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012233 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012234 Best->FoundDecl, Method);
12235 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012236 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012237 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012238 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012239 } else {
12240 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012241 ExprResult Arg0 = PerformCopyInitialization(
12242 InitializedEntity::InitializeParameter(Context,
12243 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012244 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012245 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012246 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012247
Chandler Carruth8e543b32010-12-12 08:17:55 +000012248 ExprResult Arg1 =
12249 PerformCopyInitialization(
12250 InitializedEntity::InitializeParameter(Context,
12251 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012252 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012253 if (Arg1.isInvalid())
12254 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012255 Args[0] = LHS = Arg0.getAs<Expr>();
12256 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012257 }
12258
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012259 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012260 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012261 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012262 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012263 if (FnExpr.isInvalid())
12264 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012265
Richard Smithc1564702013-11-15 02:58:23 +000012266 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012267 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012268 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12269 ResultTy = ResultTy.getNonLValueExprType(Context);
12270
John McCallb268a282010-08-23 23:25:46 +000012271 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012272 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012273 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012274 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012275
Alp Toker314cc812014-01-25 16:55:45 +000012276 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012277 FnDecl))
12278 return ExprError();
12279
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012280 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012281 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012282 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012283 if (isa<CXXMethodDecl>(FnDecl)) {
12284 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012285 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012286 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012287
12288 // Check for a self move.
12289 if (Op == OO_Equal)
12290 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12291
George Burgess IVce6284b2017-01-28 02:19:40 +000012292 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12293 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12294 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012295
John McCallb268a282010-08-23 23:25:46 +000012296 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012297 } else {
12298 // We matched a built-in operator. Convert the arguments, then
12299 // break out so that we will build the appropriate built-in
12300 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012301 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012302 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12303 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012304 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012305 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012306 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012307
John Wiegley01296292011-04-08 18:41:53 +000012308 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012309 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12310 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012311 if (ArgsRes1.isInvalid())
12312 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012313 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012314 break;
12315 }
12316 }
12317
Douglas Gregor66950a32009-09-30 21:46:01 +000012318 case OR_No_Viable_Function: {
12319 // C++ [over.match.oper]p9:
12320 // If the operator is the operator , [...] and there are no
12321 // viable functions, then the operator is assumed to be the
12322 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012323 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012324 break;
12325
Chandler Carruth8e543b32010-12-12 08:17:55 +000012326 // For class as left operand for assignment or compound assigment
12327 // operator do not fall through to handling in built-in, but report that
12328 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012329 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012330 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012331 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012332 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12333 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012334 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012335 if (Args[0]->getType()->isIncompleteType()) {
12336 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12337 << Args[0]->getType()
12338 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12339 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012340 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012341 // This is an erroneous use of an operator which can be overloaded by
12342 // a non-member function. Check for non-member operators which were
12343 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012344 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012345 // FIXME: Recover by calling the found function.
12346 return ExprError();
12347
Douglas Gregor66950a32009-09-30 21:46:01 +000012348 // No viable function; try to create a built-in operation, which will
12349 // produce an error. Then, show the non-viable candidates.
12350 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012352 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012353 "C++ binary operator overloading is missing candidates!");
12354 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012356 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012357 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012358 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012359
12360 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012361 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012362 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012363 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012364 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012365 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012366 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012367 return ExprError();
12368
12369 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012370 if (isImplicitlyDeleted(Best->Function)) {
12371 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12372 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012373 << Context.getRecordType(Method->getParent())
12374 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012375
Richard Smithde1a4872012-12-28 12:23:24 +000012376 // The user probably meant to call this special member. Just
12377 // explain why it's deleted.
12378 NoteDeletedFunction(Method);
12379 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012380 } else {
12381 Diag(OpLoc, diag::err_ovl_deleted_oper)
12382 << Best->Function->isDeleted()
12383 << BinaryOperator::getOpcodeStr(Opc)
12384 << getDeletedOrUnavailableSuffix(Best->Function)
12385 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12386 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012387 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012388 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012389 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012390 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012391
Douglas Gregor66950a32009-09-30 21:46:01 +000012392 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012393 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012394}
12395
John McCalldadc5752010-08-24 06:29:42 +000012396ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012397Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12398 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012399 Expr *Base, Expr *Idx) {
12400 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012401 DeclarationName OpName =
12402 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12403
12404 // If either side is type-dependent, create an appropriate dependent
12405 // expression.
12406 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12407
Craig Topperc3ec1492014-05-26 06:22:03 +000012408 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012409 // CHECKME: no 'operator' keyword?
12410 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12411 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012412 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012413 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012414 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012415 /*ADL*/ true, /*Overloaded*/ false,
12416 UnresolvedSetIterator(),
12417 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012418 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012419
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012420 return new (Context)
12421 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012422 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012423 }
12424
John McCall4124c492011-10-17 18:40:02 +000012425 // Handle placeholders on both operands.
12426 if (checkPlaceholderForOverload(*this, Args[0]))
12427 return ExprError();
12428 if (checkPlaceholderForOverload(*this, Args[1]))
12429 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012430
Sebastian Redladba46e2009-10-29 20:17:01 +000012431 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012432 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012433
12434 // Subscript can only be overloaded as a member function.
12435
12436 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012437 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012438
12439 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012440 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012441
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012442 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12443
Sebastian Redladba46e2009-10-29 20:17:01 +000012444 // Perform overload resolution.
12445 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012446 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012447 case OR_Success: {
12448 // We found a built-in operator or an overloaded operator.
12449 FunctionDecl *FnDecl = Best->Function;
12450
12451 if (FnDecl) {
12452 // We matched an overloaded operator. Build a call to that
12453 // operator.
12454
John McCalla0296f72010-03-19 07:35:19 +000012455 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012456
Sebastian Redladba46e2009-10-29 20:17:01 +000012457 // Convert the arguments.
12458 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012459 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012460 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012461 Best->FoundDecl, Method);
12462 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012463 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012464 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012465
Anders Carlssona68e51e2010-01-29 18:37:50 +000012466 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012467 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012468 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012469 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012470 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012471 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012472 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012473 if (InputInit.isInvalid())
12474 return ExprError();
12475
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012476 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012477
Sebastian Redladba46e2009-10-29 20:17:01 +000012478 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012479 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12480 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012481 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012482 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012483 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012484 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012485 OpLocInfo.getLoc(),
12486 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012487 if (FnExpr.isInvalid())
12488 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012489
Richard Smithc1564702013-11-15 02:58:23 +000012490 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012491 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012492 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12493 ResultTy = ResultTy.getNonLValueExprType(Context);
12494
John McCallb268a282010-08-23 23:25:46 +000012495 CXXOperatorCallExpr *TheCall =
12496 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012497 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012498 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012499 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012500
Alp Toker314cc812014-01-25 16:55:45 +000012501 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012502 return ExprError();
12503
George Burgess IVce6284b2017-01-28 02:19:40 +000012504 if (CheckFunctionCall(Method, TheCall,
12505 Method->getType()->castAs<FunctionProtoType>()))
12506 return ExprError();
12507
John McCallb268a282010-08-23 23:25:46 +000012508 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012509 } else {
12510 // We matched a built-in operator. Convert the arguments, then
12511 // break out so that we will build the appropriate built-in
12512 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012513 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012514 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12515 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012516 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012517 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012518 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012519
12520 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012521 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12522 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012523 if (ArgsRes1.isInvalid())
12524 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012525 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012526
12527 break;
12528 }
12529 }
12530
12531 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012532 if (CandidateSet.empty())
12533 Diag(LLoc, diag::err_ovl_no_oper)
12534 << Args[0]->getType() << /*subscript*/ 0
12535 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12536 else
12537 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12538 << Args[0]->getType()
12539 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012540 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012541 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012542 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012543 }
12544
12545 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012546 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012547 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012548 << Args[0]->getType() << Args[1]->getType()
12549 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012550 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012551 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012552 return ExprError();
12553
12554 case OR_Deleted:
12555 Diag(LLoc, diag::err_ovl_deleted_oper)
12556 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012557 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012558 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012559 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012560 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012561 return ExprError();
12562 }
12563
12564 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012565 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012566}
12567
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012568/// BuildCallToMemberFunction - Build a call to a member
12569/// function. MemExpr is the expression that refers to the member
12570/// function (and includes the object parameter), Args/NumArgs are the
12571/// arguments to the function call (not including the object
12572/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012573/// expression refers to a non-static member function or an overloaded
12574/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012575ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012576Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012577 SourceLocation LParenLoc,
12578 MultiExprArg Args,
12579 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012580 assert(MemExprE->getType() == Context.BoundMemberTy ||
12581 MemExprE->getType() == Context.OverloadTy);
12582
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012583 // Dig out the member expression. This holds both the object
12584 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012585 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012586
John McCall0009fcc2011-04-26 20:42:42 +000012587 // Determine whether this is a call to a pointer-to-member function.
12588 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12589 assert(op->getType() == Context.BoundMemberTy);
12590 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12591
12592 QualType fnType =
12593 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12594
12595 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12596 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012597 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012598
12599 // Check that the object type isn't more qualified than the
12600 // member function we're calling.
12601 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12602
12603 QualType objectType = op->getLHS()->getType();
12604 if (op->getOpcode() == BO_PtrMemI)
12605 objectType = objectType->castAs<PointerType>()->getPointeeType();
12606 Qualifiers objectQuals = objectType.getQualifiers();
12607
12608 Qualifiers difference = objectQuals - funcQuals;
12609 difference.removeObjCGCAttr();
12610 difference.removeAddressSpace();
12611 if (difference) {
12612 std::string qualsString = difference.getAsString();
12613 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12614 << fnType.getUnqualifiedType()
12615 << qualsString
12616 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12617 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012618
John McCall0009fcc2011-04-26 20:42:42 +000012619 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012620 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012621 resultType, valueKind, RParenLoc);
12622
Alp Toker314cc812014-01-25 16:55:45 +000012623 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012624 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012625 return ExprError();
12626
Craig Topperc3ec1492014-05-26 06:22:03 +000012627 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012628 return ExprError();
12629
Richard Trieu9be9c682013-06-22 02:30:38 +000012630 if (CheckOtherCall(call, proto))
12631 return ExprError();
12632
John McCall0009fcc2011-04-26 20:42:42 +000012633 return MaybeBindToTemporary(call);
12634 }
12635
David Majnemerced8bdf2015-02-25 17:36:15 +000012636 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12637 return new (Context)
12638 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12639
John McCall4124c492011-10-17 18:40:02 +000012640 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012641 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012642 return ExprError();
12643
John McCall10eae182009-11-30 22:42:35 +000012644 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012645 CXXMethodDecl *Method = nullptr;
12646 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12647 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012648 if (isa<MemberExpr>(NakedMemExpr)) {
12649 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012650 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012651 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012652 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012653 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012654 } else {
12655 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012656 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012657
John McCall6e9f8f62009-12-03 04:06:58 +000012658 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012659 Expr::Classification ObjectClassification
12660 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12661 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012662
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012663 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012664 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12665 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012666
John McCall2d74de92009-12-01 22:10:20 +000012667 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012668 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012669 if (UnresExpr->hasExplicitTemplateArgs()) {
12670 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12671 TemplateArgs = &TemplateArgsBuffer;
12672 }
12673
John McCall10eae182009-11-30 22:42:35 +000012674 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12675 E = UnresExpr->decls_end(); I != E; ++I) {
12676
John McCall6e9f8f62009-12-03 04:06:58 +000012677 NamedDecl *Func = *I;
12678 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12679 if (isa<UsingShadowDecl>(Func))
12680 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12681
Douglas Gregor02824322011-01-26 19:30:28 +000012682
Francois Pichet64225792011-01-18 05:04:39 +000012683 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012684 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012685 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012686 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012687 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012688 // If explicit template arguments were provided, we can't call a
12689 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012690 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012691 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012692
John McCalla0296f72010-03-19 07:35:19 +000012693 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012694 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012695 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012696 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012697 AddMethodTemplateCandidate(
12698 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012699 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012700 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012701 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012702 }
Mike Stump11289f42009-09-09 15:08:12 +000012703
John McCall10eae182009-11-30 22:42:35 +000012704 DeclarationName DeclName = UnresExpr->getMemberName();
12705
John McCall4124c492011-10-17 18:40:02 +000012706 UnbridgedCasts.restore();
12707
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012708 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012709 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012710 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012711 case OR_Success:
12712 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012713 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012714 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012715 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12716 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012717 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012718 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012719 // called on both.
12720 // FIXME: This would be more comprehensively addressed by modifying
12721 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12722 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012723 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012724 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12725 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012726 break;
12727
12728 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012729 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012730 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012731 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012733 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012734 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012735
12736 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012737 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012738 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012740 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012741 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012742
12743 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012744 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012745 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012746 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012747 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012748 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012752 }
12753
John McCall16df1e52010-03-30 21:47:33 +000012754 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012755
John McCall2d74de92009-12-01 22:10:20 +000012756 // If overload resolution picked a static member, build a
12757 // non-member call based on that function.
12758 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012759 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12760 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012761 }
12762
John McCall10eae182009-11-30 22:42:35 +000012763 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012764 }
12765
Alp Toker314cc812014-01-25 16:55:45 +000012766 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012767 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12768 ResultType = ResultType.getNonLValueExprType(Context);
12769
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012770 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012771 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012772 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012773 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012774
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012775 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012776 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012777 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012778 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012779
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012780 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012781 // We only need to do this if there was actually an overload; otherwise
12782 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012783 if (!Method->isStatic()) {
12784 ExprResult ObjectArg =
12785 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12786 FoundDecl, Method);
12787 if (ObjectArg.isInvalid())
12788 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012789 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012790 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012791
12792 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012793 const FunctionProtoType *Proto =
12794 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012795 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012796 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012797 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012798
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012799 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012800
Richard Smith55ce3522012-06-25 20:30:08 +000012801 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012802 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012803
George Burgess IVaea6ade2015-09-25 17:53:16 +000012804 // In the case the method to call was not selected by the overloading
12805 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012806 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012807 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012808 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012809 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012810 diag::err_ovl_no_viable_member_function_in_call)
12811 << Method << Method->getSourceRange();
12812 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012813 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012814 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12815 return ExprError();
12816 }
12817 }
12818
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012819 if ((isa<CXXConstructorDecl>(CurContext) ||
12820 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000012821 TheCall->getMethodDecl()->isPure()) {
12822 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12823
Davide Italianoccb37382015-07-14 23:36:10 +000012824 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12825 MemExpr->performsVirtualDispatch(getLangOpts())) {
12826 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012827 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12828 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12829 << MD->getParent()->getDeclName();
12830
12831 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012832 if (getLangOpts().AppleKext)
12833 Diag(MemExpr->getLocStart(),
12834 diag::note_pure_qualified_call_kext)
12835 << MD->getParent()->getDeclName()
12836 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012837 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012838 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012839
12840 if (CXXDestructorDecl *DD =
12841 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12842 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012843 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012844 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12845 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12846 MemExpr->getMemberLoc());
12847 }
12848
John McCallb268a282010-08-23 23:25:46 +000012849 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012850}
12851
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012852/// BuildCallToObjectOfClassType - Build a call to an object of class
12853/// type (C++ [over.call.object]), which can end up invoking an
12854/// overloaded function call operator (@c operator()) or performing a
12855/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012856ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012857Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012858 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012859 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012860 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012861 if (checkPlaceholderForOverload(*this, Obj))
12862 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012863 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012864
12865 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012866 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012867 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012868
Nico Weberb58e51c2014-11-19 05:21:39 +000012869 assert(Object.get()->getType()->isRecordType() &&
12870 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012871 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012872
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012873 // C++ [over.call.object]p1:
12874 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012875 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012876 // candidate functions includes at least the function call
12877 // operators of T. The function call operators of T are obtained by
12878 // ordinary lookup of the name operator() in the context of
12879 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012880 OverloadCandidateSet CandidateSet(LParenLoc,
12881 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012882 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012883
John Wiegley01296292011-04-08 18:41:53 +000012884 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012885 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012886 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012887
John McCall27b18f82009-11-17 02:14:36 +000012888 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12889 LookupQualifiedName(R, Record->getDecl());
12890 R.suppressDiagnostics();
12891
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012892 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012893 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012894 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012895 Object.get()->Classify(Context), Args, CandidateSet,
12896 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012898
Douglas Gregorab7897a2008-11-19 22:57:39 +000012899 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012900 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012901 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012902 //
12903 // operator conversion-type-id () cv-qualifier;
12904 //
12905 // where cv-qualifier is the same cv-qualification as, or a
12906 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012907 // denotes the type "pointer to function of (P1,...,Pn) returning
12908 // R", or the type "reference to pointer to function of
12909 // (P1,...,Pn) returning R", or the type "reference to function
12910 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012911 // is also considered as a candidate function. Similarly,
12912 // surrogate call functions are added to the set of candidate
12913 // functions for each conversion function declared in an
12914 // accessible base class provided the function is not hidden
12915 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012916 const auto &Conversions =
12917 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12918 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012919 NamedDecl *D = *I;
12920 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12921 if (isa<UsingShadowDecl>(D))
12922 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012923
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012924 // Skip over templated conversion functions; they aren't
12925 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012926 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012927 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012928
John McCall6e9f8f62009-12-03 04:06:58 +000012929 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012930 if (!Conv->isExplicit()) {
12931 // Strip the reference type (if any) and then the pointer type (if
12932 // any) to get down to what might be a function type.
12933 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12934 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12935 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012936
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012937 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12938 {
12939 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012940 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012941 }
12942 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012943 }
Mike Stump11289f42009-09-09 15:08:12 +000012944
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012945 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12946
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012947 // Perform overload resolution.
12948 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012949 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +000012950 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012951 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012952 // Overload resolution succeeded; we'll build the appropriate call
12953 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012954 break;
12955
12956 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012957 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012958 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012959 << Object.get()->getType() << /*call*/ 1
12960 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012961 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012962 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012963 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012964 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012965 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012966 break;
12967
12968 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012969 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012970 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012971 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012972 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012973 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012974
12975 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012976 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012977 diag::err_ovl_deleted_object_call)
12978 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012979 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012980 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012981 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012982 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012983 break;
Mike Stump11289f42009-09-09 15:08:12 +000012984 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012985
Douglas Gregorb412e172010-07-25 18:17:45 +000012986 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012987 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012988
John McCall4124c492011-10-17 18:40:02 +000012989 UnbridgedCasts.restore();
12990
Craig Topperc3ec1492014-05-26 06:22:03 +000012991 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012992 // Since there is no function declaration, this is one of the
12993 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012994 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012995 = cast<CXXConversionDecl>(
12996 Best->Conversions[0].UserDefined.ConversionFunction);
12997
Craig Topperc3ec1492014-05-26 06:22:03 +000012998 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12999 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013000 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13001 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013002 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013003 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013004 // We selected one of the surrogate functions that converts the
13005 // object parameter to a function pointer. Perform the conversion
13006 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013007
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013008 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013009 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013010 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13011 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013012 if (Call.isInvalid())
13013 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013014 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013015 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13016 CK_UserDefinedConversion, Call.get(),
13017 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013018
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013019 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013020 }
13021
Craig Topperc3ec1492014-05-26 06:22:03 +000013022 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013023
Douglas Gregorab7897a2008-11-19 22:57:39 +000013024 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13025 // that calls this method, using Object for the implicit object
13026 // parameter and passing along the remaining arguments.
13027 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013028
13029 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013030 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013031 return ExprError();
13032
Chandler Carruth8e543b32010-12-12 08:17:55 +000013033 const FunctionProtoType *Proto =
13034 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013035
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013036 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013037
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013038 DeclarationNameInfo OpLocInfo(
13039 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13040 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013041 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013042 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013043 OpLocInfo.getLoc(),
13044 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013045 if (NewFn.isInvalid())
13046 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013047
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013048 // Build the full argument list for the method call (the implicit object
13049 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013050 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013051 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013052 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013053
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013054 // Once we've built TheCall, all of the expressions are properly
13055 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013056 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013057 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13058 ResultTy = ResultTy.getNonLValueExprType(Context);
13059
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013060 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013061 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013062 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013063
Alp Toker314cc812014-01-25 16:55:45 +000013064 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013065 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013066
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013067 // We may have default arguments. If so, we need to allocate more
13068 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013069 if (Args.size() < NumParams)
13070 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013071
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013072 bool IsError = false;
13073
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013074 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013075 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013076 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013077 Best->FoundDecl, Method);
13078 if (ObjRes.isInvalid())
13079 IsError = true;
13080 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013081 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013082 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013083
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013084 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013085 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013086 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013087 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013088 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013089
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013090 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013091
John McCalldadc5752010-08-24 06:29:42 +000013092 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013093 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013094 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013095 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013096 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013097
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013098 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013099 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013100 } else {
John McCalldadc5752010-08-24 06:29:42 +000013101 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013102 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13103 if (DefArg.isInvalid()) {
13104 IsError = true;
13105 break;
13106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013107
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013108 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013109 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013110
13111 TheCall->setArg(i + 1, Arg);
13112 }
13113
13114 // If this is a variadic call, handle args passed through "...".
13115 if (Proto->isVariadic()) {
13116 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013117 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013118 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13119 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013120 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013121 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013122 }
13123 }
13124
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013125 if (IsError) return true;
13126
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013127 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013128
Richard Smith55ce3522012-06-25 20:30:08 +000013129 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013130 return true;
13131
John McCalle172be52010-08-24 06:09:16 +000013132 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013133}
13134
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013135/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013136/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013137/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013138ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013139Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13140 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013141 assert(Base->getType()->isRecordType() &&
13142 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013143
John McCall4124c492011-10-17 18:40:02 +000013144 if (checkPlaceholderForOverload(*this, Base))
13145 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013146
John McCallbc077cf2010-02-08 23:07:23 +000013147 SourceLocation Loc = Base->getExprLoc();
13148
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013149 // C++ [over.ref]p1:
13150 //
13151 // [...] An expression x->m is interpreted as (x.operator->())->m
13152 // for a class object x of type T if T::operator->() exists and if
13153 // the operator is selected as the best match function by the
13154 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013155 DeclarationName OpName =
13156 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013157 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013158 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013159
John McCallbc077cf2010-02-08 23:07:23 +000013160 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013161 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013162 return ExprError();
13163
John McCall27b18f82009-11-17 02:14:36 +000013164 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13165 LookupQualifiedName(R, BaseRecord->getDecl());
13166 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013167
13168 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013169 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013170 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013171 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013172 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013173
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013174 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13175
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013176 // Perform overload resolution.
13177 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013178 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013179 case OR_Success:
13180 // Overload resolution succeeded; we'll build the call below.
13181 break;
13182
13183 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013184 if (CandidateSet.empty()) {
13185 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013186 if (NoArrowOperatorFound) {
13187 // Report this specific error to the caller instead of emitting a
13188 // diagnostic, as requested.
13189 *NoArrowOperatorFound = true;
13190 return ExprError();
13191 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013192 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13193 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013194 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013195 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013196 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013197 }
13198 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013199 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013200 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013201 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013202 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013203
13204 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013205 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13206 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013207 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013208 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013209
13210 case OR_Deleted:
13211 Diag(OpLoc, diag::err_ovl_deleted_oper)
13212 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013213 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013214 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013215 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013217 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013218 }
13219
Craig Topperc3ec1492014-05-26 06:22:03 +000013220 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013221
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013222 // Convert the object parameter.
13223 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013224 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013225 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013226 Best->FoundDecl, Method);
13227 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013228 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013229 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013230
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013231 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013232 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013233 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013234 if (FnExpr.isInvalid())
13235 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013236
Alp Toker314cc812014-01-25 16:55:45 +000013237 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013238 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13239 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013240 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013241 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013242 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013243
Alp Toker314cc812014-01-25 16:55:45 +000013244 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013245 return ExprError();
13246
13247 if (CheckFunctionCall(Method, TheCall,
13248 Method->getType()->castAs<FunctionProtoType>()))
13249 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013250
13251 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013252}
13253
Richard Smithbcc22fc2012-03-09 08:00:36 +000013254/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13255/// a literal operator described by the provided lookup results.
13256ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13257 DeclarationNameInfo &SuffixInfo,
13258 ArrayRef<Expr*> Args,
13259 SourceLocation LitEndLoc,
13260 TemplateArgumentListInfo *TemplateArgs) {
13261 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013262
Richard Smith100b24a2014-04-17 01:52:14 +000013263 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13264 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013265 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13266 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013267
Richard Smithbcc22fc2012-03-09 08:00:36 +000013268 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13269
Richard Smithbcc22fc2012-03-09 08:00:36 +000013270 // Perform overload resolution. This will usually be trivial, but might need
13271 // to perform substitutions for a literal operator template.
13272 OverloadCandidateSet::iterator Best;
13273 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13274 case OR_Success:
13275 case OR_Deleted:
13276 break;
13277
13278 case OR_No_Viable_Function:
13279 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13280 << R.getLookupName();
13281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13282 return ExprError();
13283
13284 case OR_Ambiguous:
13285 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13286 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13287 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013288 }
13289
Richard Smithbcc22fc2012-03-09 08:00:36 +000013290 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013291 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013292 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013293 SuffixInfo.getLoc(),
13294 SuffixInfo.getInfo());
13295 if (Fn.isInvalid())
13296 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013297
13298 // Check the argument types. This should almost always be a no-op, except
13299 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013300 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013301 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013302 ExprResult InputInit = PerformCopyInitialization(
13303 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13304 SourceLocation(), Args[ArgIdx]);
13305 if (InputInit.isInvalid())
13306 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013307 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013308 }
13309
Alp Toker314cc812014-01-25 16:55:45 +000013310 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013311 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13312 ResultTy = ResultTy.getNonLValueExprType(Context);
13313
Richard Smithc67fdd42012-03-07 08:35:16 +000013314 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013315 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013316 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013317 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13318
Alp Toker314cc812014-01-25 16:55:45 +000013319 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013320 return ExprError();
13321
Craig Topperc3ec1492014-05-26 06:22:03 +000013322 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013323 return ExprError();
13324
13325 return MaybeBindToTemporary(UDL);
13326}
13327
Sam Panzer0f384432012-08-21 00:52:01 +000013328/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13329/// given LookupResult is non-empty, it is assumed to describe a member which
13330/// will be invoked. Otherwise, the function will be found via argument
13331/// dependent lookup.
13332/// CallExpr is set to a valid expression and FRS_Success returned on success,
13333/// otherwise CallExpr is set to ExprError() and some non-success value
13334/// is returned.
13335Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013336Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13337 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013338 const DeclarationNameInfo &NameInfo,
13339 LookupResult &MemberLookup,
13340 OverloadCandidateSet *CandidateSet,
13341 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013342 Scope *S = nullptr;
13343
Richard Smith67ef14f2017-09-26 18:37:55 +000013344 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013345 if (!MemberLookup.empty()) {
13346 ExprResult MemberRef =
13347 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13348 /*IsPtr=*/false, CXXScopeSpec(),
13349 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013350 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013351 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013352 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013353 if (MemberRef.isInvalid()) {
13354 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013355 return FRS_DiagnosticIssued;
13356 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013357 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013358 if (CallExpr->isInvalid()) {
13359 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013360 return FRS_DiagnosticIssued;
13361 }
13362 } else {
13363 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013364 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013365 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013366 NestedNameSpecifierLoc(), NameInfo,
13367 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013368 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013369
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013370 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013371 CandidateSet, CallExpr);
13372 if (CandidateSet->empty() || CandidateSetError) {
13373 *CallExpr = ExprError();
13374 return FRS_NoViableFunction;
13375 }
13376 OverloadCandidateSet::iterator Best;
13377 OverloadingResult OverloadResult =
13378 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13379
13380 if (OverloadResult == OR_No_Viable_Function) {
13381 *CallExpr = ExprError();
13382 return FRS_NoViableFunction;
13383 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013384 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013385 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013386 OverloadResult,
13387 /*AllowTypoCorrection=*/false);
13388 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13389 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013390 return FRS_DiagnosticIssued;
13391 }
13392 }
13393 return FRS_Success;
13394}
13395
13396
Douglas Gregorcd695e52008-11-10 20:40:00 +000013397/// FixOverloadedFunctionReference - E is an expression that refers to
13398/// a C++ overloaded function (possibly with some parentheses and
13399/// perhaps a '&' around it). We have resolved the overloaded function
13400/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013401/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013402Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013403 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013404 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013405 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13406 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013407 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013408 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013409
Douglas Gregor51c538b2009-11-20 19:42:02 +000013410 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013411 }
13412
Douglas Gregor51c538b2009-11-20 19:42:02 +000013413 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013414 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13415 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013416 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013417 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013418 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013419 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013420 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013421 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013422
13423 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013424 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013425 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013426 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013427 }
13428
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013429 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13430 if (!GSE->isResultDependent()) {
13431 Expr *SubExpr =
13432 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13433 if (SubExpr == GSE->getResultExpr())
13434 return GSE;
13435
13436 // Replace the resulting type information before rebuilding the generic
13437 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013438 ArrayRef<Expr *> A = GSE->getAssocExprs();
13439 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013440 unsigned ResultIdx = GSE->getResultIndex();
13441 AssocExprs[ResultIdx] = SubExpr;
13442
13443 return new (Context) GenericSelectionExpr(
13444 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13445 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13446 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13447 ResultIdx);
13448 }
13449 // Rather than fall through to the unreachable, return the original generic
13450 // selection expression.
13451 return GSE;
13452 }
13453
Douglas Gregor51c538b2009-11-20 19:42:02 +000013454 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013455 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013456 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13458 if (Method->isStatic()) {
13459 // Do nothing: static member functions aren't any different
13460 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013461 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013462 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013463 // UnresolvedLookupExpr holding an overloaded member function
13464 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013465 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13466 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013467 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013468 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013469
John McCalld14a8642009-11-21 08:51:07 +000013470 assert(isa<DeclRefExpr>(SubExpr)
13471 && "fixed to something other than a decl ref");
13472 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13473 && "fixed to a member ref with no nested name qualifier");
13474
13475 // We have taken the address of a pointer to member
13476 // function. Perform the computation here so that we get the
13477 // appropriate pointer to member type.
13478 QualType ClassType
13479 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13480 QualType MemPtrType
13481 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013482 // Under the MS ABI, lock down the inheritance model now.
13483 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13484 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013485
John McCall7decc9e2010-11-18 06:31:45 +000013486 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13487 VK_RValue, OK_Ordinary,
13488 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013489 }
13490 }
John McCall16df1e52010-03-30 21:47:33 +000013491 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13492 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013493 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013494 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013495
John McCalle3027922010-08-25 11:45:40 +000013496 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013497 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013498 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013499 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013500 }
John McCalld14a8642009-11-21 08:51:07 +000013501
Richard Smith84a0b6d2016-10-18 23:39:12 +000013502 // C++ [except.spec]p17:
13503 // An exception-specification is considered to be needed when:
13504 // - in an expression the function is the unique lookup result or the
13505 // selected member of a set of overloaded functions
13506 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13507 ResolveExceptionSpec(E->getExprLoc(), FPT);
13508
John McCalld14a8642009-11-21 08:51:07 +000013509 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013510 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013511 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013512 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013513 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13514 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013515 }
13516
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013517 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13518 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013519 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013520 Fn,
John McCall113bee02012-03-10 09:33:50 +000013521 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013522 ULE->getNameLoc(),
13523 Fn->getType(),
13524 VK_LValue,
13525 Found.getDecl(),
13526 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013527 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013528 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13529 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013530 }
13531
John McCall10eae182009-11-30 22:42:35 +000013532 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013533 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013534 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013535 if (MemExpr->hasExplicitTemplateArgs()) {
13536 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13537 TemplateArgs = &TemplateArgsBuffer;
13538 }
John McCall6b51f282009-11-23 01:53:49 +000013539
John McCall2d74de92009-12-01 22:10:20 +000013540 Expr *Base;
13541
John McCall7decc9e2010-11-18 06:31:45 +000013542 // If we're filling in a static method where we used to have an
13543 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013544 if (MemExpr->isImplicitAccess()) {
13545 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013546 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13547 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013548 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013549 Fn,
John McCall113bee02012-03-10 09:33:50 +000013550 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013551 MemExpr->getMemberLoc(),
13552 Fn->getType(),
13553 VK_LValue,
13554 Found.getDecl(),
13555 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013556 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013557 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13558 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013559 } else {
13560 SourceLocation Loc = MemExpr->getMemberLoc();
13561 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013562 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013563 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013564 Base = new (Context) CXXThisExpr(Loc,
13565 MemExpr->getBaseType(),
13566 /*isImplicit=*/true);
13567 }
John McCall2d74de92009-12-01 22:10:20 +000013568 } else
John McCallc3007a22010-10-26 07:05:15 +000013569 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013570
John McCall4adb38c2011-04-27 00:36:17 +000013571 ExprValueKind valueKind;
13572 QualType type;
13573 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13574 valueKind = VK_LValue;
13575 type = Fn->getType();
13576 } else {
13577 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013578 type = Context.BoundMemberTy;
13579 }
13580
13581 MemberExpr *ME = MemberExpr::Create(
13582 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13583 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13584 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13585 OK_Ordinary);
13586 ME->setHadMultipleCandidates(true);
13587 MarkMemberReferenced(ME);
13588 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013590
John McCallc3007a22010-10-26 07:05:15 +000013591 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013592}
13593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013594ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013595 DeclAccessPair Found,
13596 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013597 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013598}