blob: 7905f5e6228a2a77b8606ce51a45346407298560 [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;
Mikhail Maltsev7b1a9502018-02-21 10:08:18 +0000330 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331 ToType->isRealFloatingType()) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000334 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000335
336 // If it's value-dependent, we can't tell whether it's narrowing.
337 if (Initializer->isValueDependent())
338 return NK_Dependent_Narrowing;
339
Simon Pilgrimf9409872017-06-01 18:13:02 +0000340 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000341 // Convert the integer to the floating type.
342 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
343 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
344 llvm::APFloat::rmNearestTiesToEven);
345 // And back.
346 llvm::APSInt ConvertedValue = IntConstantValue;
347 bool ignored;
348 Result.convertToInteger(ConvertedValue,
349 llvm::APFloat::rmTowardZero, &ignored);
350 // If the resulting value is different, this was a narrowing conversion.
351 if (IntConstantValue != ConvertedValue) {
352 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000353 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000354 return NK_Constant_Narrowing;
355 }
356 } else {
357 // Variables are always narrowings.
358 return NK_Variable_Narrowing;
359 }
360 }
361 return NK_Not_Narrowing;
362
363 // -- from long double to double or float, or from double to float, except
364 // where the source is a constant expression and the actual value after
365 // conversion is within the range of values that can be represented (even
366 // if it cannot be represented exactly), or
367 case ICK_Floating_Conversion:
368 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
369 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
370 // FromType is larger than ToType.
371 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000372
373 // If it's value-dependent, we can't tell whether it's narrowing.
374 if (Initializer->isValueDependent())
375 return NK_Dependent_Narrowing;
376
Richard Smith66e05fe2012-01-18 05:21:49 +0000377 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
378 // Constant!
379 assert(ConstantValue.isFloat());
380 llvm::APFloat FloatVal = ConstantValue.getFloat();
381 // Convert the source value into the target type.
382 bool ignored;
383 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
384 Ctx.getFloatTypeSemantics(ToType),
385 llvm::APFloat::rmNearestTiesToEven, &ignored);
386 // If there was no overflow, the source value is within the range of
387 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000388 if (ConvertStatus & llvm::APFloat::opOverflow) {
389 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000391 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000392 } else {
393 return NK_Variable_Narrowing;
394 }
395 }
396 return NK_Not_Narrowing;
397
398 // -- from an integer type or unscoped enumeration type to an integer type
399 // that cannot represent all the values of the original type, except where
400 // the source is a constant expression and the actual value after
401 // conversion will fit into the target type and will produce the original
402 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000403 case ICK_Integral_Conversion:
404 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000405 assert(FromType->isIntegralOrUnscopedEnumerationType());
406 assert(ToType->isIntegralOrUnscopedEnumerationType());
407 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
408 const unsigned FromWidth = Ctx.getIntWidth(FromType);
409 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
410 const unsigned ToWidth = Ctx.getIntWidth(ToType);
411
412 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000413 (FromWidth == ToWidth && FromSigned != ToSigned) ||
414 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 // Not all values of FromType can be represented in ToType.
416 llvm::APSInt InitializerValue;
417 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000418
419 // If it's value-dependent, we can't tell whether it's narrowing.
420 if (Initializer->isValueDependent())
421 return NK_Dependent_Narrowing;
422
Richard Smith25a80d42012-06-13 01:07:41 +0000423 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
424 // Such conversions on variables are always narrowing.
425 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000426 }
427 bool Narrowing = false;
428 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000429 // Negative -> unsigned is narrowing. Otherwise, more bits is never
430 // narrowing.
431 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000432 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000433 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000434 // Add a bit to the InitializerValue so we don't have to worry about
435 // signed vs. unsigned comparisons.
436 InitializerValue = InitializerValue.extend(
437 InitializerValue.getBitWidth() + 1);
438 // Convert the initializer to and from the target width and signed-ness.
439 llvm::APSInt ConvertedValue = InitializerValue;
440 ConvertedValue = ConvertedValue.trunc(ToWidth);
441 ConvertedValue.setIsSigned(ToSigned);
442 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
443 ConvertedValue.setIsSigned(InitializerValue.isSigned());
444 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000445 if (ConvertedValue != InitializerValue)
446 Narrowing = true;
447 }
448 if (Narrowing) {
449 ConstantType = Initializer->getType();
450 ConstantValue = APValue(InitializerValue);
451 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000452 }
453 }
454 return NK_Not_Narrowing;
455 }
456
457 default:
458 // Other kinds of conversions are not narrowings.
459 return NK_Not_Narrowing;
460 }
461}
462
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000463/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000465LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000466 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 bool PrintedSomething = false;
468 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 PrintedSomething = true;
471 }
472
473 if (Second != ICK_Identity) {
474 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000477 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000478
479 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000484 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000485 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486 PrintedSomething = true;
487 }
488
489 if (Third != ICK_Identity) {
490 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494 PrintedSomething = true;
495 }
496
497 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 }
500}
501
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000502/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000504void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000505 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000510 if (ConversionFunction)
511 OS << '\'' << *ConversionFunction << '\'';
512 else
513 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000516 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 }
518}
519
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000521/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000522void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000523 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000524 if (isStdInitializerListElement())
525 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526 switch (ConversionKind) {
527 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000528 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000529 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530 break;
531 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000532 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000533 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 break;
535 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000536 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537 break;
John McCall0d1da222010-01-12 00:44:57 +0000538 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000539 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000540 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000542 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 break;
544 }
545
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000546 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547}
548
John McCall0d1da222010-01-12 00:44:57 +0000549void AmbiguousConversionSequence::construct() {
550 new (&conversions()) ConversionSet();
551}
552
553void AmbiguousConversionSequence::destruct() {
554 conversions().~ConversionSet();
555}
556
557void
558AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
559 FromTypePtr = O.FromTypePtr;
560 ToTypePtr = O.ToTypePtr;
561 new (&conversions()) ConversionSet(O.conversions());
562}
563
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000565 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000566 // template argument information.
567 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 TemplateArgument FirstArg;
569 TemplateArgument SecondArg;
570 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000571 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000572 // template parameter and template argument information.
573 struct DFIParamWithArguments : DFIArguments {
574 TemplateParameter Param;
575 };
Richard Smith9b534542015-12-31 02:02:54 +0000576 // Structure used by DeductionFailureInfo to store template argument
577 // information and the index of the problematic call argument.
578 struct DFIDeducedMismatchArgs : DFIArguments {
579 TemplateArgumentList *TemplateArgs;
580 unsigned CallArgIndex;
581 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000582}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584/// \brief Convert from Sema's representation of template deduction information
585/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000586DeductionFailureInfo
587clang::MakeDeductionFailureInfo(ASTContext &Context,
588 Sema::TemplateDeductionResult TDK,
589 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000590 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000592 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000593 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000594 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000595 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000596 case Sema::TDK_TooManyArguments:
597 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000599 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000600 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000604 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000605 Result.Data = Info.Param.getOpaqueValue();
606 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Richard Smithc92d2062017-01-05 23:02:44 +0000608 case Sema::TDK_DeducedMismatch:
609 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000610 // FIXME: Should allocate from normal heap so that we can free this later.
611 auto *Saved = new (Context) DFIDeducedMismatchArgs;
612 Saved->FirstArg = Info.FirstArg;
613 Saved->SecondArg = Info.SecondArg;
614 Saved->TemplateArgs = Info.take();
615 Saved->CallArgIndex = Info.CallArgIndex;
616 Result.Data = Saved;
617 break;
618 }
619
Richard Smith44ecdbd2013-01-31 05:19:49 +0000620 case Sema::TDK_NonDeducedMismatch: {
621 // FIXME: Should allocate from normal heap so that we can free this later.
622 DFIArguments *Saved = new (Context) DFIArguments;
623 Saved->FirstArg = Info.FirstArg;
624 Saved->SecondArg = Info.SecondArg;
625 Result.Data = Saved;
626 break;
627 }
628
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000630 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000631 // FIXME: Should allocate from normal heap so that we can free this later.
632 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 Saved->Param = Info.Param;
634 Saved->FirstArg = Info.FirstArg;
635 Saved->SecondArg = Info.SecondArg;
636 Result.Data = Saved;
637 break;
638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000641 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000642 if (Info.hasSFINAEDiagnostic()) {
643 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
644 SourceLocation(), PartialDiagnostic::NullDiagnostic());
645 Info.takeSFINAEDiagnostic(*Diag);
646 Result.HasDiagnostic = true;
647 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000648 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000649
650 case Sema::TDK_Success:
651 case Sema::TDK_NonDependentConversionFailure:
652 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return Result;
656}
John McCall0d1da222010-01-12 00:44:57 +0000657
Larisse Voufo98b20f12013-07-19 23:00:19 +0000658void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
660 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000661 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 case Sema::TDK_InstantiationDepth:
663 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000664 case Sema::TDK_TooManyArguments:
665 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000666 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000667 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000668 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000671 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000672 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000673 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000674 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000675 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000676 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000677 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000678 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000679
680 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000681 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000683 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
684 Diag->~PartialDiagnosticAt();
685 HasDiagnostic = false;
686 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor461761d2010-05-08 18:20:53 +0000689 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000690 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 break;
692 }
693}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Larisse Voufo98b20f12013-07-19 23:00:19 +0000695PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000696 if (HasDiagnostic)
697 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000698 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000699}
700
Larisse Voufo98b20f12013-07-19 23:00:19 +0000701TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
703 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000704 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000706 case Sema::TDK_TooManyArguments:
707 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000709 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000710 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000711 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000712 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000713 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000714 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000717 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719
720 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000721 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000725 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 break;
727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return TemplateParameter();
730}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
Larisse Voufo98b20f12013-07-19 23:00:19 +0000732TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000733 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000734 case Sema::TDK_Success:
735 case Sema::TDK_Invalid:
736 case Sema::TDK_InstantiationDepth:
737 case Sema::TDK_TooManyArguments:
738 case Sema::TDK_TooFewArguments:
739 case Sema::TDK_Incomplete:
740 case Sema::TDK_InvalidExplicitArguments:
741 case Sema::TDK_Inconsistent:
742 case Sema::TDK_Underqualified:
743 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000744 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000745 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000746 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000747
Richard Smith9b534542015-12-31 02:02:54 +0000748 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000749 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000750 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
751
Richard Smith44ecdbd2013-01-31 05:19:49 +0000752 case Sema::TDK_SubstitutionFailure:
753 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754
Richard Smith44ecdbd2013-01-31 05:19:49 +0000755 // Unhandled
756 case Sema::TDK_MiscellaneousDeductionFailure:
757 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000758 }
759
Craig Topperc3ec1492014-05-26 06:22:03 +0000760 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000761}
762
Larisse Voufo98b20f12013-07-19 23:00:19 +0000763const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
765 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000766 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767 case Sema::TDK_InstantiationDepth:
768 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000769 case Sema::TDK_TooManyArguments:
770 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000771 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000772 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000773 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000774 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000775 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000778 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000779 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000780 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000781 case Sema::TDK_NonDeducedMismatch:
782 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000783
Douglas Gregor461761d2010-05-08 18:20:53 +0000784 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000785 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000786 break;
787 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788
Craig Topperc3ec1492014-05-26 06:22:03 +0000789 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000791
Larisse Voufo98b20f12013-07-19 23:00:19 +0000792const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000793 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
794 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000795 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000796 case Sema::TDK_InstantiationDepth:
797 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000798 case Sema::TDK_TooManyArguments:
799 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000800 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000801 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000802 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000803 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000806 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000807 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000808 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000809 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000810 case Sema::TDK_NonDeducedMismatch:
811 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000812
Douglas Gregor461761d2010-05-08 18:20:53 +0000813 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000814 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000815 break;
816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Craig Topperc3ec1492014-05-26 06:22:03 +0000818 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000819}
820
Richard Smith9b534542015-12-31 02:02:54 +0000821llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000822 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
823 case Sema::TDK_DeducedMismatch:
824 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000825 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
826
Richard Smithc92d2062017-01-05 23:02:44 +0000827 default:
828 return llvm::None;
829 }
Richard Smith9b534542015-12-31 02:02:54 +0000830}
831
Benjamin Kramer97e59492012-10-09 15:52:25 +0000832void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000833 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000834 for (auto &C : i->Conversions)
835 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000836 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
837 i->DeductionFailure.Destroy();
838 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000839}
840
Richard Smith67ef14f2017-09-26 18:37:55 +0000841void OverloadCandidateSet::clear(CandidateSetKind CSK) {
Benjamin Kramer97e59492012-10-09 15:52:25 +0000842 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000843 SlabAllocator.Reset();
844 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000845 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000846 Functions.clear();
Richard Smith67ef14f2017-09-26 18:37:55 +0000847 Kind = CSK;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000848}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
John McCall4124c492011-10-17 18:40:02 +0000850namespace {
851 class UnbridgedCastsSet {
852 struct Entry {
853 Expr **Addr;
854 Expr *Saved;
855 };
856 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000857
John McCall4124c492011-10-17 18:40:02 +0000858 public:
859 void save(Sema &S, Expr *&E) {
860 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
861 Entry entry = { &E, E };
862 Entries.push_back(entry);
863 E = S.stripARCUnbridgedCast(E);
864 }
865
866 void restore() {
867 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000868 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000869 *i->Addr = i->Saved;
870 }
871 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000872}
John McCall4124c492011-10-17 18:40:02 +0000873
874/// checkPlaceholderForOverload - Do any interesting placeholder-like
875/// preprocessing on the given expression.
876///
877/// \param unbridgedCasts a collection to which to add unbridged casts;
878/// without this, they will be immediately diagnosed as errors
879///
880/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000881static bool
882checkPlaceholderForOverload(Sema &S, Expr *&E,
883 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000884 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
885 // We can't handle overloaded expressions here because overload
886 // resolution might reasonably tweak them.
887 if (placeholder->getKind() == BuiltinType::Overload) return false;
888
889 // If the context potentially accepts unbridged ARC casts, strip
890 // the unbridged cast and add it to the collection for later restoration.
891 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
892 unbridgedCasts) {
893 unbridgedCasts->save(S, E);
894 return false;
895 }
896
897 // Go ahead and check everything else.
898 ExprResult result = S.CheckPlaceholderExpr(E);
899 if (result.isInvalid())
900 return true;
901
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000902 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000903 return false;
904 }
905
906 // Nothing to do.
907 return false;
908}
909
910/// checkArgPlaceholdersForOverload - Check a set of call operands for
911/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000912static bool checkArgPlaceholdersForOverload(Sema &S,
913 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000914 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000915 for (unsigned i = 0, e = Args.size(); i != e; ++i)
916 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000917 return true;
918
919 return false;
920}
921
George Burgess IV2d82b092017-04-06 00:23:31 +0000922/// Determine whether the given New declaration is an overload of the
923/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
924/// New and Old cannot be overloaded, e.g., if New has the same signature as
925/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
926/// functions (or function templates) at all. When it does return Ovl_Match or
927/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
928/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
929/// declaration.
930///
931/// Example: Given the following input:
932///
933/// void f(int, float); // #1
934/// void f(int, int); // #2
935/// int f(int, int); // #3
936///
937/// When we process #1, there is no previous declaration of "f", so IsOverload
938/// will not be used.
939///
940/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
941/// the parameter types, we see that #1 and #2 are overloaded (since they have
942/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
943/// unchanged.
944///
945/// When we process #3, Old is an overload set containing #1 and #2. We compare
946/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
947/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
948/// functions are not part of the signature), IsOverload returns Ovl_Match and
949/// MatchedDecl will be set to point to the FunctionDecl for #2.
950///
951/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
952/// by a using declaration. The rules for whether to hide shadow declarations
953/// ignore some properties which otherwise figure into a function template's
954/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000955Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000956Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
957 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000958 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000959 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000960 NamedDecl *OldD = *I;
961
962 bool OldIsUsingDecl = false;
963 if (isa<UsingShadowDecl>(OldD)) {
964 OldIsUsingDecl = true;
965
966 // We can always introduce two using declarations into the same
967 // context, even if they have identical signatures.
968 if (NewIsUsingDecl) continue;
969
970 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
971 }
972
Richard Smithf091e122015-09-15 01:28:55 +0000973 // A using-declaration does not conflict with another declaration
974 // if one of them is hidden.
975 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
976 continue;
977
John McCalle9cccd82010-06-16 08:42:20 +0000978 // If either declaration was introduced by a using declaration,
979 // we'll need to use slightly different rules for matching.
980 // Essentially, these rules are the normal rules, except that
981 // function templates hide function templates with different
982 // return types or template parameter lists.
983 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000984 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
985 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000986
Alp Tokera2794f92014-01-22 07:29:52 +0000987 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000988 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
989 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
990 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
991 continue;
992 }
993
Alp Tokera2794f92014-01-22 07:29:52 +0000994 if (!isa<FunctionTemplateDecl>(OldD) &&
995 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000996 continue;
997
John McCalldaa3d6b2009-12-09 03:35:25 +0000998 Match = *I;
999 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +00001000 }
Richard Smith151c4562016-12-20 21:35:28 +00001001 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001002 // We can overload with these, which can show up when doing
1003 // redeclaration checks for UsingDecls.
1004 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001005 } else if (isa<TagDecl>(OldD)) {
1006 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001007 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001008 // Optimistically assume that an unresolved using decl will
1009 // overload; if it doesn't, we'll have to diagnose during
1010 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001011 //
1012 // Exception: if the scope is dependent and this is not a class
1013 // member, the using declaration can only introduce an enumerator.
1014 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
John McCall84d87672009-12-10 09:41:52 +00001018 } else {
John McCall1f82f242009-11-18 22:49:29 +00001019 // (C++ 13p1):
1020 // Only function declarations can be overloaded; object and type
1021 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001022 Match = *I;
1023 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001024 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 }
John McCall1f82f242009-11-18 22:49:29 +00001026
John McCalldaa3d6b2009-12-09 03:35:25 +00001027 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001028}
1029
Richard Smithac974a32013-06-30 09:48:50 +00001030bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001031 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001032 // C++ [basic.start.main]p2: This function shall not be overloaded.
1033 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001034 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001035
David Majnemerc729b0b2013-09-16 22:44:20 +00001036 // MSVCRT user defined entry points cannot be overloaded.
1037 if (New->isMSVCRTEntryPoint())
1038 return false;
1039
John McCall1f82f242009-11-18 22:49:29 +00001040 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1041 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1042
1043 // C++ [temp.fct]p2:
1044 // A function template can be overloaded with other function templates
1045 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001046 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001047 return true;
1048
1049 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001050 QualType OldQType = Context.getCanonicalType(Old->getType());
1051 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001052
1053 // Compare the signatures (C++ 1.3.10) of the two functions to
1054 // determine whether they are overloads. If we find any mismatch
1055 // in the signature, they are overloads.
1056
1057 // If either of these functions is a K&R-style function (no
1058 // prototype), then we consider them to have matching signatures.
1059 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1060 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1061 return false;
1062
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001063 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1064 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001065
1066 // The signature of a function includes the types of its
1067 // parameters (C++ 1.3.10), which includes the presence or absence
1068 // of the ellipsis; see C++ DR 357).
1069 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001070 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001071 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001072 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001073 return true;
1074
1075 // C++ [temp.over.link]p4:
1076 // The signature of a function template consists of its function
1077 // signature, its return type and its template parameter list. The names
1078 // of the template parameters are significant only for establishing the
1079 // relationship between the template parameters and the rest of the
1080 // signature.
1081 //
1082 // We check the return type and template parameter lists for function
1083 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001084 //
1085 // However, we don't consider either of these when deciding whether
1086 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001087 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001088 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1089 OldTemplate->getTemplateParameters(),
1090 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001091 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001092 return true;
1093
1094 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001095 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001096 //
1097 // As part of this, also check whether one of the member functions
1098 // is static, in which case they are not overloads (C++
1099 // 13.1p2). While not part of the definition of the signature,
1100 // this check is important to determine whether these functions
1101 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001102 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1103 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001104 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001105 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1106 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001107 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001108 (OldMethod->getRefQualifier() == RQ_None ||
1109 NewMethod->getRefQualifier() == RQ_None)) {
1110 // C++0x [over.load]p2:
1111 // - Member function declarations with the same name and the same
1112 // parameter-type-list as well as member function template
1113 // declarations with the same name, the same parameter-type-list, and
1114 // the same template parameter lists cannot be overloaded if any of
1115 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001116 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001117 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001118 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001119 }
1120 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
Richard Smith574f4f62013-01-14 05:37:29 +00001123 // We may not have applied the implicit const for a constexpr member
1124 // function yet (because we haven't yet resolved whether this is a static
1125 // or non-static member function). Add it now, on the assumption that this
1126 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001127 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001128 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001129 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001130 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001131 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001132
1133 // We do not allow overloading based off of '__restrict'.
1134 OldQuals &= ~Qualifiers::Restrict;
1135 NewQuals &= ~Qualifiers::Restrict;
1136 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001137 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001140 // Though pass_object_size is placed on parameters and takes an argument, we
1141 // consider it to be a function-level modifier for the sake of function
1142 // identity. Either the function has one or more parameters with
1143 // pass_object_size or it doesn't.
1144 if (functionHasPassObjectSizeParams(New) !=
1145 functionHasPassObjectSizeParams(Old))
1146 return true;
1147
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001148 // enable_if attributes are an order-sensitive part of the signature.
1149 for (specific_attr_iterator<EnableIfAttr>
1150 NewI = New->specific_attr_begin<EnableIfAttr>(),
1151 NewE = New->specific_attr_end<EnableIfAttr>(),
1152 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1153 OldE = Old->specific_attr_end<EnableIfAttr>();
1154 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1155 if (NewI == NewE || OldI == OldE)
1156 return true;
1157 llvm::FoldingSetNodeID NewID, OldID;
1158 NewI->getCond()->Profile(NewID, Context, true);
1159 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001160 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001161 return true;
1162 }
1163
Justin Lebarba122ab2016-03-30 23:30:21 +00001164 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001165 // Don't allow overloading of destructors. (In theory we could, but it
1166 // would be a giant change to clang.)
1167 if (isa<CXXDestructorDecl>(New))
1168 return false;
1169
Artem Belevich94a55e82015-09-22 17:22:59 +00001170 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1171 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001172 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001173 return false;
1174
1175 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1176
Justin Lebar53b000af2016-10-03 16:48:27 +00001177 // Allow overloading of functions with same signature and different CUDA
1178 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001179 return NewTarget != OldTarget;
1180 }
1181
John McCall1f82f242009-11-18 22:49:29 +00001182 // The signatures match; this is not an overload.
1183 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184}
1185
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001186/// \brief Checks availability of the function depending on the current
1187/// function context. Inside an unavailable function, unavailability is ignored.
1188///
1189/// \returns true if \arg FD is unavailable and current context is inside
1190/// an available function, false otherwise.
1191bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001192 if (!FD->isUnavailable())
1193 return false;
1194
1195 // Walk up the context of the caller.
1196 Decl *C = cast<Decl>(CurContext);
1197 do {
1198 if (C->isUnavailable())
1199 return false;
1200 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1201 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001202}
1203
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001204/// \brief Tries a user-defined conversion from From to ToType.
1205///
1206/// Produces an implicit conversion sequence for when a standard conversion
1207/// is not an option. See TryImplicitConversion for more information.
1208static ImplicitConversionSequence
1209TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1210 bool SuppressUserConversions,
1211 bool AllowExplicit,
1212 bool InOverloadResolution,
1213 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001214 bool AllowObjCWritebackConversion,
1215 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001216 ImplicitConversionSequence ICS;
1217
1218 if (SuppressUserConversions) {
1219 // We're not in the case above, so there is no conversion that
1220 // we can perform.
1221 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1222 return ICS;
1223 }
1224
1225 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001226 OverloadCandidateSet Conversions(From->getExprLoc(),
1227 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001228 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1229 Conversions, AllowExplicit,
1230 AllowObjCConversionOnExplicit)) {
1231 case OR_Success:
1232 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001233 ICS.setUserDefined();
1234 // C++ [over.ics.user]p4:
1235 // A conversion of an expression of class type to the same class
1236 // type is given Exact Match rank, and a conversion of an
1237 // expression of class type to a base class of that type is
1238 // given Conversion rank, in spite of the fact that a copy
1239 // constructor (i.e., a user-defined conversion function) is
1240 // called for those cases.
1241 if (CXXConstructorDecl *Constructor
1242 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1243 QualType FromCanon
1244 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1245 QualType ToCanon
1246 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1247 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001248 (FromCanon == ToCanon ||
1249 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001250 // Turn this into a "standard" conversion sequence, so that it
1251 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001252 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001253 ICS.setStandard();
1254 ICS.Standard.setAsIdentityConversion();
1255 ICS.Standard.setFromType(From->getType());
1256 ICS.Standard.setAllToTypes(ToType);
1257 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001258 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001259 if (ToCanon != FromCanon)
1260 ICS.Standard.Second = ICK_Derived_To_Base;
1261 }
1262 }
Richard Smith48372b62015-01-27 03:30:40 +00001263 break;
1264
1265 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001266 ICS.setAmbiguous();
1267 ICS.Ambiguous.setFromType(From->getType());
1268 ICS.Ambiguous.setToType(ToType);
1269 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1270 Cand != Conversions.end(); ++Cand)
1271 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001272 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001273 break;
Richard Smith48372b62015-01-27 03:30:40 +00001274
1275 // Fall through.
1276 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001278 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001279 }
1280
1281 return ICS;
1282}
1283
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001284/// TryImplicitConversion - Attempt to perform an implicit conversion
1285/// from the given expression (Expr) to the given type (ToType). This
1286/// function returns an implicit conversion sequence that can be used
1287/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288///
1289/// void f(float f);
1290/// void g(int i) { f(i); }
1291///
1292/// this routine would produce an implicit conversion sequence to
1293/// describe the initialization of f from i, which will be a standard
1294/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1295/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1296//
1297/// Note that this routine only determines how the conversion can be
1298/// performed; it does not actually perform the conversion. As such,
1299/// it will not produce any diagnostics if no conversion is available,
1300/// but will instead return an implicit conversion sequence of kind
1301/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001302///
1303/// If @p SuppressUserConversions, then user-defined conversions are
1304/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001305/// If @p AllowExplicit, then explicit user-defined conversions are
1306/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001307///
1308/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1309/// writeback conversion, which allows __autoreleasing id* parameters to
1310/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001311static ImplicitConversionSequence
1312TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1313 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001315 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001316 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001317 bool AllowObjCWritebackConversion,
1318 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001320 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001321 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001322 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001323 return ICS;
1324 }
1325
David Blaikiebbafb8a2012-03-11 07:00:24 +00001326 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001327 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001328 return ICS;
1329 }
1330
Douglas Gregor836a7e82010-08-11 02:15:33 +00001331 // C++ [over.ics.user]p4:
1332 // A conversion of an expression of class type to the same class
1333 // type is given Exact Match rank, and a conversion of an
1334 // expression of class type to a base class of that type is
1335 // given Conversion rank, in spite of the fact that a copy/move
1336 // constructor (i.e., a user-defined conversion function) is
1337 // called for those cases.
1338 QualType FromType = From->getType();
1339 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001340 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001341 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001342 ICS.setStandard();
1343 ICS.Standard.setAsIdentityConversion();
1344 ICS.Standard.setFromType(FromType);
1345 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001346
Douglas Gregor5ab11652010-04-17 22:01:05 +00001347 // We don't actually check at this point whether there is a valid
1348 // copy/move constructor, since overloading just assumes that it
1349 // exists. When we actually perform initialization, we'll find the
1350 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001351 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352
Douglas Gregor5ab11652010-04-17 22:01:05 +00001353 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001354 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001355 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356
Douglas Gregor836a7e82010-08-11 02:15:33 +00001357 return ICS;
1358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001360 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1361 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001362 AllowObjCWritebackConversion,
1363 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001364}
1365
John McCall31168b02011-06-15 23:02:42 +00001366ImplicitConversionSequence
1367Sema::TryImplicitConversion(Expr *From, QualType ToType,
1368 bool SuppressUserConversions,
1369 bool AllowExplicit,
1370 bool InOverloadResolution,
1371 bool CStyle,
1372 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001373 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001374 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001375 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001376 AllowObjCWritebackConversion,
1377 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001378}
1379
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001381/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001382/// converted expression. Flavor is the kind of conversion we're
1383/// performing, used in the error message. If @p AllowExplicit,
1384/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001385ExprResult
1386Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001387 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001388 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001389 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001390}
1391
John Wiegley01296292011-04-08 18:41:53 +00001392ExprResult
1393Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001394 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001395 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001396 if (checkPlaceholderForOverload(*this, From))
1397 return ExprError();
1398
John McCall31168b02011-06-15 23:02:42 +00001399 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1400 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001401 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001402 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001403 if (getLangOpts().ObjC1)
1404 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1405 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001406 ICS = ::TryImplicitConversion(*this, From, ToType,
1407 /*SuppressUserConversions=*/false,
1408 AllowExplicit,
1409 /*InOverloadResolution=*/false,
1410 /*CStyle=*/false,
1411 AllowObjCWritebackConversion,
1412 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001413 return PerformImplicitConversion(From, ToType, ICS, Action);
1414}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415
1416/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001417/// conversion that strips "noexcept" or "noreturn" off the nested function
1418/// type.
1419bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001420 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001421 if (Context.hasSameUnqualifiedType(FromType, ToType))
1422 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
John McCall991eb4b2010-12-21 00:44:39 +00001424 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001425 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001426 // where F adds one of the following at most once:
1427 // - a pointer
1428 // - a member pointer
1429 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001430 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001431 CanQualType CanTo = Context.getCanonicalType(ToType);
1432 CanQualType CanFrom = Context.getCanonicalType(FromType);
1433 Type::TypeClass TyClass = CanTo->getTypeClass();
1434 if (TyClass != CanFrom->getTypeClass()) return false;
1435 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1436 if (TyClass == Type::Pointer) {
1437 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1438 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1439 } else if (TyClass == Type::BlockPointer) {
1440 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1441 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1442 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001443 auto ToMPT = CanTo.getAs<MemberPointerType>();
1444 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1445 // A function pointer conversion cannot change the class of the function.
1446 if (ToMPT->getClass() != FromMPT->getClass())
1447 return false;
1448 CanTo = ToMPT->getPointeeType();
1449 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001450 } else {
1451 return false;
1452 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001453
John McCall991eb4b2010-12-21 00:44:39 +00001454 TyClass = CanTo->getTypeClass();
1455 if (TyClass != CanFrom->getTypeClass()) return false;
1456 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1457 return false;
1458 }
1459
Richard Smith3c4f8d22016-10-16 17:54:23 +00001460 const auto *FromFn = cast<FunctionType>(CanFrom);
1461 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001462
Richard Smith6f427402016-10-20 00:01:36 +00001463 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001464 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1465
1466 bool Changed = false;
1467
1468 // Drop 'noreturn' if not present in target type.
1469 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1470 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1471 Changed = true;
1472 }
1473
1474 // Drop 'noexcept' if not present in target type.
1475 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001476 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001477 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1478 FromFn = cast<FunctionType>(
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00001479 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1480 EST_None)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001481 .getTypePtr());
1482 Changed = true;
1483 }
Artem Belevich55ebd6c2018-04-03 18:29:31 +00001484
Akira Hatanaka98a49332017-09-22 00:41:05 +00001485 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1486 // only if the ExtParameterInfo lists of the two function prototypes can be
1487 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1488 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1489 bool CanUseToFPT, CanUseFromFPT;
1490 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1491 CanUseFromFPT, NewParamInfos) &&
1492 CanUseToFPT && !CanUseFromFPT) {
1493 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1494 ExtInfo.ExtParameterInfos =
1495 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1496 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1497 FromFPT->getParamTypes(), ExtInfo);
1498 FromFn = QT->getAs<FunctionType>();
1499 Changed = true;
1500 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001501 }
1502
1503 if (!Changed)
1504 return false;
1505
John McCall991eb4b2010-12-21 00:44:39 +00001506 assert(QualType(FromFn, 0).isCanonical());
1507 if (QualType(FromFn, 0) != CanTo) return false;
1508
1509 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001510 return true;
1511}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512
Douglas Gregor46188682010-05-18 22:42:18 +00001513/// \brief Determine whether the conversion from FromType to ToType is a valid
1514/// vector conversion.
1515///
1516/// \param ICK Will be set to the vector conversion kind, if this is a vector
1517/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001518static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001520 // We need at least one of these types to be a vector type to have a vector
1521 // conversion.
1522 if (!ToType->isVectorType() && !FromType->isVectorType())
1523 return false;
1524
1525 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001526 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001527 return false;
1528
1529 // There are no conversions between extended vector types, only identity.
1530 if (ToType->isExtVectorType()) {
1531 // There are no conversions between extended vector types other than the
1532 // identity conversion.
1533 if (FromType->isExtVectorType())
1534 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Douglas Gregor46188682010-05-18 22:42:18 +00001536 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001537 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001538 ICK = ICK_Vector_Splat;
1539 return true;
1540 }
1541 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001542
1543 // We can perform the conversion between vector types in the following cases:
1544 // 1)vector types are equivalent AltiVec and GCC vector types
1545 // 2)lax vector conversions are permitted and the vector types are of the
1546 // same size
1547 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001548 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1549 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001550 ICK = ICK_Vector_Conversion;
1551 return true;
1552 }
Douglas Gregor46188682010-05-18 22:42:18 +00001553 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001554
Douglas Gregor46188682010-05-18 22:42:18 +00001555 return false;
1556}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001558static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1559 bool InOverloadResolution,
1560 StandardConversionSequence &SCS,
1561 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001562
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563/// IsStandardConversion - Determines whether there is a standard
1564/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1565/// expression From to the type ToType. Standard conversion sequences
1566/// only consider non-class types; for conversions that involve class
1567/// types, use TryImplicitConversion. If a conversion exists, SCS will
1568/// contain the standard conversion sequence required to perform this
1569/// conversion and this routine will return true. Otherwise, this
1570/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001571static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1572 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001573 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001574 bool CStyle,
1575 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001579 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001580 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001581 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001582 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001584 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001585 // abort early. When overloading in C, however, we do permit them.
1586 if (S.getLangOpts().CPlusPlus &&
1587 (FromType->isRecordType() || ToType->isRecordType()))
1588 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 // The first conversion can be an lvalue-to-rvalue conversion,
1591 // array-to-pointer conversion, or function-to-pointer conversion
1592 // (C++ 4p1).
1593
John McCall5c32be02010-08-24 20:38:10 +00001594 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001595 DeclAccessPair AccessPair;
1596 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001598 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001599 // We were able to resolve the address of the overloaded function,
1600 // so we can convert to the type of that function.
1601 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001602 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001603
1604 // we can sometimes resolve &foo<int> regardless of ToType, so check
1605 // if the type matches (identity) or we are converting to bool
1606 if (!S.Context.hasSameUnqualifiedType(
1607 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1608 QualType resultTy;
1609 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001610 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001611 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001612 // otherwise, only a boolean conversion is standard
1613 if (!ToType->isBooleanType())
1614 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616
Chandler Carruthffce2452011-03-29 08:08:18 +00001617 // Check if the "from" expression is taking the address of an overloaded
1618 // function and recompute the FromType accordingly. Take advantage of the
1619 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001620 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001621 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1622 if (Method && !Method->isStatic()) {
1623 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1624 "Non-unary operator on non-static member address");
1625 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1626 == UO_AddrOf &&
1627 "Non-address-of operator on non-static member address");
1628 const Type *ClassType
1629 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1630 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001631 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1632 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1633 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001634 "Non-address-of operator for overloaded function expression");
1635 FromType = S.Context.getPointerType(FromType);
1636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637
Douglas Gregor980fb162010-04-29 18:24:40 +00001638 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001639 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1640 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001641 assert(S.Context.hasSameType(
1642 FromType,
1643 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001644 } else {
1645 return false;
1646 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001647 }
John McCall154a2fd2011-08-30 00:57:29 +00001648 // Lvalue-to-rvalue conversion (C++11 4.1):
1649 // A glvalue (3.10) of a non-function, non-array type T can
1650 // be converted to a prvalue.
1651 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001652 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001653 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001654 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656
Douglas Gregorc79862f2012-04-12 17:51:55 +00001657 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001658 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001659 // of the type of the lvalue ...
1660 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1661 FromType = Atomic->getValueType();
1662
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 // If T is a non-class type, the type of the rvalue is the
1664 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001665 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1666 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001667 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001668 } else if (FromType->isArrayType()) {
1669 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001670 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671
1672 // An lvalue or rvalue of type "array of N T" or "array of unknown
1673 // bound of T" can be converted to an rvalue of type "pointer to
1674 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001675 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676
John McCall5c32be02010-08-24 20:38:10 +00001677 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001678 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001679 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680
1681 // For the purpose of ranking in overload resolution
1682 // (13.3.3.1.1), this conversion is considered an
1683 // array-to-pointer conversion followed by a qualification
1684 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 SCS.Second = ICK_Identity;
1686 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001687 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001688 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690 }
John McCall086a4642010-11-24 05:12:34 +00001691 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001692 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001695 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1696 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1697 if (!S.checkAddressOfFunctionIsAvailable(FD))
1698 return false;
1699
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 // An lvalue of function type T can be converted to an rvalue of
1701 // type "pointer to T." The result is a pointer to the
1702 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001703 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001704 } else {
1705 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001707 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001708 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709
1710 // The second conversion can be an integral promotion, floating
1711 // point promotion, integral conversion, floating point conversion,
1712 // floating-integral conversion, pointer conversion,
1713 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001714 // For overloading in C, this can also be a "compatible-type"
1715 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001716 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001717 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001718 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 // The unqualified versions of the types are the same: there's no
1720 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001721 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001722 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001723 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001724 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001726 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001727 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001728 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001730 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001731 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001732 SCS.Second = ICK_Complex_Promotion;
1733 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001734 } else if (ToType->isBooleanType() &&
1735 (FromType->isArithmeticType() ||
1736 FromType->isAnyPointerType() ||
1737 FromType->isBlockPointerType() ||
1738 FromType->isMemberPointerType() ||
1739 FromType->isNullPtrType())) {
1740 // Boolean conversions (C++ 4.12).
1741 SCS.Second = ICK_Boolean_Conversion;
1742 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001743 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001744 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001745 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001746 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001748 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001749 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750 SCS.Second = ICK_Complex_Conversion;
1751 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001752 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1753 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001754 // Complex-real conversions (C99 6.3.1.7)
1755 SCS.Second = ICK_Complex_Real;
1756 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001757 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001758 // FIXME: disable conversions between long double and __float128 if
1759 // their representation is different until there is back end support
1760 // We of course allow this conversion if long double is really double.
1761 if (&S.Context.getFloatTypeSemantics(FromType) !=
1762 &S.Context.getFloatTypeSemantics(ToType)) {
1763 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1764 ToType == S.Context.LongDoubleTy) ||
1765 (FromType == S.Context.LongDoubleTy &&
1766 ToType == S.Context.Float128Ty));
1767 if (Float128AndLongDouble &&
Benjamin Kramer98057952018-01-17 22:56:57 +00001768 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1769 &llvm::APFloat::PPCDoubleDouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001770 return false;
1771 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001772 // Floating point conversions (C++ 4.8).
1773 SCS.Second = ICK_Floating_Conversion;
1774 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001776 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001777 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001778 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001779 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001780 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001782 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001783 SCS.Second = ICK_Block_Pointer_Conversion;
1784 } else if (AllowObjCWritebackConversion &&
1785 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1786 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001787 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1788 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001789 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001790 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001791 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001792 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001794 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001795 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001796 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001797 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001798 SCS.Second = SecondICK;
1799 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001800 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001801 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001802 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001803 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001804 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001805 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1806 InOverloadResolution,
1807 SCS, CStyle)) {
1808 SCS.Second = ICK_TransparentUnionConversion;
1809 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001810 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1811 CStyle)) {
1812 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001813 // appropriately.
1814 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001815 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001816 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001817 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001818 SCS.Second = ICK_Zero_Event_Conversion;
1819 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001820 } else if (ToType->isQueueT() &&
1821 From->isIntegerConstantExpr(S.getASTContext()) &&
1822 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1823 SCS.Second = ICK_Zero_Queue_Conversion;
1824 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 } else {
1826 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001827 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001829 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001831 // The third conversion can be a function pointer conversion or a
1832 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001833 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001834 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1835 // Function pointer conversions (removing 'noexcept') including removal of
1836 // 'noreturn' (Clang extension).
1837 SCS.Third = ICK_Function_Conversion;
1838 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1839 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001840 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001841 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842 FromType = ToType;
1843 } else {
1844 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001845 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001846 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001847
1848 // C++ [over.best.ics]p6:
1849 // [...] Any difference in top-level cv-qualification is
1850 // subsumed by the initialization itself and does not constitute
1851 // a conversion. [...]
1852 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1853 QualType CanonTo = S.Context.getCanonicalType(ToType);
1854 if (CanonFrom.getLocalUnqualifiedType()
1855 == CanonTo.getLocalUnqualifiedType() &&
1856 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1857 FromType = ToType;
1858 CanonFrom = CanonTo;
1859 }
1860
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001861 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001862
George Burgess IV45461812015-10-11 20:13:20 +00001863 if (CanonFrom == CanonTo)
1864 return true;
1865
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001866 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001867 // this is a bad conversion sequence, unless we're resolving an overload in C.
1868 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001869 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870
George Burgess IV45461812015-10-11 20:13:20 +00001871 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001872 Sema::AssignConvertType Conv =
1873 S.CheckSingleAssignmentConstraints(ToType, ER,
1874 /*Diagnose=*/false,
1875 /*DiagnoseCFAudited=*/false,
1876 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001877 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001878 switch (Conv) {
1879 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001880 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001881 break;
1882 // For our purposes, discarding qualifiers is just as bad as using an
1883 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1884 // qualifiers, as well.
1885 case Sema::CompatiblePointerDiscardsQualifiers:
1886 case Sema::IncompatiblePointer:
1887 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001888 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001889 break;
1890 default:
George Burgess IV45461812015-10-11 20:13:20 +00001891 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001892 }
George Burgess IV45461812015-10-11 20:13:20 +00001893
George Burgess IV6098fd12016-09-03 00:28:25 +00001894 // First can only be an lvalue conversion, so we pretend that this was the
1895 // second conversion. First should already be valid from earlier in the
1896 // function.
1897 SCS.Second = SecondConv;
1898 SCS.setToType(1, ToType);
1899
1900 // Third is Identity, because Second should rank us worse than any other
1901 // conversion. This could also be ICK_Qualification, but it's simpler to just
1902 // lump everything in with the second conversion, and we don't gain anything
1903 // from making this ICK_Qualification.
1904 SCS.Third = ICK_Identity;
1905 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001906 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001907}
George Burgess IV2099b542016-09-02 22:59:57 +00001908
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001909static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001910IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001911 QualType &ToType,
1912 bool InOverloadResolution,
1913 StandardConversionSequence &SCS,
1914 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001915
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001916 const RecordType *UT = ToType->getAsUnionType();
1917 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1918 return false;
1919 // The field to initialize within the transparent union.
1920 RecordDecl *UD = UT->getDecl();
1921 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001922 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001923 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1924 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001925 ToType = it->getType();
1926 return true;
1927 }
1928 }
1929 return false;
1930}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931
1932/// IsIntegralPromotion - Determines whether the conversion from the
1933/// expression From (whose potentially-adjusted type is FromType) to
1934/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1935/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001936bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001937 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001938 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939 if (!To) {
1940 return false;
1941 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942
1943 // An rvalue of type char, signed char, unsigned char, short int, or
1944 // unsigned short int can be converted to an rvalue of type int if
1945 // int can represent all the values of the source type; otherwise,
1946 // the source rvalue can be converted to an rvalue of type unsigned
1947 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001948 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1949 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 if (// We can promote any signed, promotable integer type to an int
1951 (FromType->isSignedIntegerType() ||
1952 // We can promote any unsigned integer type whose size is
1953 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001954 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001955 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001956 }
1957
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001958 return To->getKind() == BuiltinType::UInt;
1959 }
1960
Richard Smithb9c5a602012-09-13 21:18:54 +00001961 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // A prvalue of an unscoped enumeration type whose underlying type is not
1963 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1964 // following types that can represent all the values of the enumeration
1965 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1966 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001967 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001969 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970 // with lowest integer conversion rank (4.13) greater than the rank of long
1971 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001972 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001973 // C++11 [conv.prom]p4:
1974 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1975 // can be converted to a prvalue of its underlying type. Moreover, if
1976 // integral promotion can be applied to its underlying type, a prvalue of an
1977 // unscoped enumeration type whose underlying type is fixed can also be
1978 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001979 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1980 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1981 // provided for a scoped enumeration.
1982 if (FromEnumType->getDecl()->isScoped())
1983 return false;
1984
Richard Smithb9c5a602012-09-13 21:18:54 +00001985 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001986 // even if that's not the promoted type. Note that the check for promoting
1987 // the underlying type is based on the type alone, and does not consider
1988 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001989 if (FromEnumType->getDecl()->isFixed()) {
1990 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1991 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001992 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001993 }
1994
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001995 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001997 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001998 return Context.hasSameUnqualifiedType(
1999 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00002000 }
John McCall56774992009-12-09 09:09:27 +00002001
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002002 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2004 // to an rvalue a prvalue of the first of the following types that can
2005 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002006 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002008 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002010 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002012 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002013 // Determine whether the type we're converting from is signed or
2014 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002015 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002016 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 // The types we'll try to promote to, in the appropriate
2019 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002020 QualType PromoteTypes[6] = {
2021 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002022 Context.LongTy, Context.UnsignedLongTy ,
2023 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002025 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2027 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002028 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2030 // We found the type that we can promote to. If this is the
2031 // type we wanted, we have a promotion. Otherwise, no
2032 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002033 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002034 }
2035 }
2036 }
2037
2038 // An rvalue for an integral bit-field (9.6) can be converted to an
2039 // rvalue of type int if int can represent all the values of the
2040 // bit-field; otherwise, it can be converted to unsigned int if
2041 // unsigned int can represent all the values of the bit-field. If
2042 // the bit-field is larger yet, no integral promotion applies to
2043 // it. If the bit-field has an enumerated type, it is treated as any
2044 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002045 // FIXME: We should delay checking of bit-fields until we actually perform the
2046 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002047 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002048 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002049 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002050 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002051 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002052 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002053 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002055 // Are we promoting to an int from a bitfield that fits in an int?
2056 if (BitWidth < ToSize ||
2057 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2058 return To->getKind() == BuiltinType::Int;
2059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002061 // Are we promoting to an unsigned int from an unsigned bitfield
2062 // that fits into an unsigned int?
2063 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2064 return To->getKind() == BuiltinType::UInt;
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002067 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002068 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002072 // An rvalue of type bool can be converted to an rvalue of type int,
2073 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002074 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002075 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002076 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002077
2078 return false;
2079}
2080
2081/// IsFloatingPointPromotion - Determines whether the conversion from
2082/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2083/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002084bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002085 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2086 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002087 /// An rvalue of type float can be converted to an rvalue of type
2088 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002089 if (FromBuiltin->getKind() == BuiltinType::Float &&
2090 ToBuiltin->getKind() == BuiltinType::Double)
2091 return true;
2092
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002093 // C99 6.3.1.5p1:
2094 // When a float is promoted to double or long double, or a
2095 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002096 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002097 (FromBuiltin->getKind() == BuiltinType::Float ||
2098 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002099 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2100 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002101 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002102
2103 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002104 if (!getLangOpts().NativeHalfType &&
2105 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002106 ToBuiltin->getKind() == BuiltinType::Float)
2107 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002108 }
2109
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002110 return false;
2111}
2112
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002113/// \brief Determine if a conversion is a complex promotion.
2114///
2115/// A complex promotion is defined as a complex -> complex conversion
2116/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002117/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002118bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002119 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002120 if (!FromComplex)
2121 return false;
2122
John McCall9dd450b2009-09-21 23:43:11 +00002123 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002124 if (!ToComplex)
2125 return false;
2126
2127 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002128 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002129 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002130 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002131}
2132
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2134/// the pointer type FromPtr to a pointer to type ToPointee, with the
2135/// same type qualifiers as FromPtr has on its pointee type. ToType,
2136/// if non-empty, will be a pointer to ToType that may or may not have
2137/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002138///
Mike Stump11289f42009-09-09 15:08:12 +00002139static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002140BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002141 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002142 ASTContext &Context,
2143 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002144 assert((FromPtr->getTypeClass() == Type::Pointer ||
2145 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2146 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
John McCall31168b02011-06-15 23:02:42 +00002148 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002149 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002150 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
2152 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002153 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002154 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002155 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002156
John McCall31168b02011-06-15 23:02:42 +00002157 if (StripObjCLifetime)
2158 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002159
Mike Stump11289f42009-09-09 15:08:12 +00002160 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002161 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002162 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002163 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002164 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002165
2166 // Build a pointer to ToPointee. It has the right qualifiers
2167 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002168 if (isa<ObjCObjectPointerType>(ToType))
2169 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002170 return Context.getPointerType(ToPointee);
2171 }
2172
2173 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002174 QualType QualifiedCanonToPointee
2175 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002177 if (isa<ObjCObjectPointerType>(ToType))
2178 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2179 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002180}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002181
Mike Stump11289f42009-09-09 15:08:12 +00002182static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002183 bool InOverloadResolution,
2184 ASTContext &Context) {
2185 // Handle value-dependent integral null pointer constants correctly.
2186 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2187 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002188 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002189 return !InOverloadResolution;
2190
Douglas Gregor56751b52009-09-25 04:25:58 +00002191 return Expr->isNullPointerConstant(Context,
2192 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2193 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002194}
Mike Stump11289f42009-09-09 15:08:12 +00002195
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196/// IsPointerConversion - Determines whether the conversion of the
2197/// expression From, which has the (possibly adjusted) type FromType,
2198/// can be converted to the type ToType via a pointer conversion (C++
2199/// 4.10). If so, returns true and places the converted type (that
2200/// might differ from ToType in its cv-qualifiers at some level) into
2201/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002202///
Douglas Gregora29dc052008-11-27 01:19:21 +00002203/// This routine also supports conversions to and from block pointers
2204/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2205/// pointers to interfaces. FIXME: Once we've determined the
2206/// appropriate overloading rules for Objective-C, we may want to
2207/// split the Objective-C checks into a different routine; however,
2208/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002209/// conversions, so for now they live here. IncompatibleObjC will be
2210/// set if the conversion is an allowed Objective-C conversion that
2211/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002213 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002214 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002215 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002216 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002217 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2218 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002219 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002220
Mike Stump11289f42009-09-09 15:08:12 +00002221 // Conversion from a null pointer constant to any Objective-C pointer type.
2222 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002223 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002224 ConvertedType = ToType;
2225 return true;
2226 }
2227
Douglas Gregor231d1c62008-11-27 00:15:41 +00002228 // Blocks: Block pointers can be converted to void*.
2229 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002230 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002231 ConvertedType = ToType;
2232 return true;
2233 }
2234 // Blocks: A null pointer constant can be converted to a block
2235 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002236 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002237 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002238 ConvertedType = ToType;
2239 return true;
2240 }
2241
Sebastian Redl576fd422009-05-10 18:38:11 +00002242 // If the left-hand-side is nullptr_t, the right side can be a null
2243 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002244 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002245 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002246 ConvertedType = ToType;
2247 return true;
2248 }
2249
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002250 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251 if (!ToTypePtr)
2252 return false;
2253
2254 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002255 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002256 ConvertedType = ToType;
2257 return true;
2258 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002261 // , including objective-c pointers.
2262 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002263 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002264 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002265 ConvertedType = BuildSimilarlyQualifiedPointerType(
2266 FromType->getAs<ObjCObjectPointerType>(),
2267 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002268 ToType, Context);
2269 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002270 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002271 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002272 if (!FromTypePtr)
2273 return false;
2274
2275 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002276
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002278 // pointer conversion, so don't do all of the work below.
2279 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2280 return false;
2281
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 // An rvalue of type "pointer to cv T," where T is an object type,
2283 // can be converted to an rvalue of type "pointer to cv void" (C++
2284 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002285 if (FromPointeeType->isIncompleteOrObjectType() &&
2286 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002287 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002288 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002289 ToType, Context,
2290 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002291 return true;
2292 }
2293
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002294 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002295 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002296 ToPointeeType->isVoidType()) {
2297 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2298 ToPointeeType,
2299 ToType, Context);
2300 return true;
2301 }
2302
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002303 // When we're overloading in C, we allow a special kind of pointer
2304 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002305 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002306 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002307 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002308 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002309 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002310 return true;
2311 }
2312
Douglas Gregor5c407d92008-10-23 00:40:37 +00002313 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002314 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002315 // An rvalue of type "pointer to cv D," where D is a class type,
2316 // can be converted to an rvalue of type "pointer to cv B," where
2317 // B is a base class (clause 10) of D. If B is an inaccessible
2318 // (clause 11) or ambiguous (10.2) base class of D, a program that
2319 // necessitates this conversion is ill-formed. The result of the
2320 // conversion is a pointer to the base class sub-object of the
2321 // derived class object. The null pointer value is converted to
2322 // the null pointer value of the destination type.
2323 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002324 // Note that we do not check for ambiguity or inaccessibility
2325 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002326 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002327 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002328 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002329 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002331 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002332 ToType, Context);
2333 return true;
2334 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002335
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002336 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2337 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339 ToPointeeType,
2340 ToType, Context);
2341 return true;
2342 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002343
Douglas Gregora119f102008-12-19 19:13:09 +00002344 return false;
2345}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002346
Douglas Gregoraec25842011-04-26 23:16:46 +00002347/// \brief Adopt the given qualifiers for the given type.
2348static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2349 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002350
Douglas Gregoraec25842011-04-26 23:16:46 +00002351 // Check whether qualifiers already match.
2352 if (TQs == Qs)
2353 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002354
Douglas Gregoraec25842011-04-26 23:16:46 +00002355 if (Qs.compatiblyIncludes(TQs))
2356 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002357
Douglas Gregoraec25842011-04-26 23:16:46 +00002358 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2359}
Douglas Gregora119f102008-12-19 19:13:09 +00002360
2361/// isObjCPointerConversion - Determines whether this is an
2362/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2363/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002364bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002365 QualType& ConvertedType,
2366 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002367 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregoraec25842011-04-26 23:16:46 +00002370 // The set of qualifiers on the type we're converting from.
2371 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002372
Steve Naroff7cae42b2009-07-10 23:34:53 +00002373 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002374 const ObjCObjectPointerType* ToObjCPtr =
2375 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002376 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002377 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002378
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002380 // If the pointee types are the same (ignoring qualifications),
2381 // then this is not a pointer conversion.
2382 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2383 FromObjCPtr->getPointeeType()))
2384 return false;
2385
Douglas Gregorab209d82015-07-07 03:58:42 +00002386 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002387 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002388 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2389 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002390 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002391 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2392 FromObjCPtr->getPointeeType()))
2393 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002394 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002395 ToObjCPtr->getPointeeType(),
2396 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002397 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002398 return true;
2399 }
2400
2401 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2402 // Okay: this is some kind of implicit downcast of Objective-C
2403 // interfaces, which is permitted. However, we're going to
2404 // complain about it.
2405 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002407 ToObjCPtr->getPointeeType(),
2408 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002409 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002410 return true;
2411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002413 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002414 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002415 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002416 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002418 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002419 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002420 // to a block pointer type.
2421 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002422 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002423 return true;
2424 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002425 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002428 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002430 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002431 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002432 return true;
2433 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002434 else
Douglas Gregora119f102008-12-19 19:13:09 +00002435 return false;
2436
Douglas Gregor033f56d2008-12-23 00:53:59 +00002437 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002438 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002439 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002440 else if (const BlockPointerType *FromBlockPtr =
2441 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002442 FromPointeeType = FromBlockPtr->getPointeeType();
2443 else
Douglas Gregora119f102008-12-19 19:13:09 +00002444 return false;
2445
Douglas Gregora119f102008-12-19 19:13:09 +00002446 // If we have pointers to pointers, recursively check whether this
2447 // is an Objective-C conversion.
2448 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2449 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2450 IncompatibleObjC)) {
2451 // We always complain about this conversion.
2452 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002453 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002454 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002455 return true;
2456 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002457 // Allow conversion of pointee being objective-c pointer to another one;
2458 // as in I* to id.
2459 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2460 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2461 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2462 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002463
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002464 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002465 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002466 return true;
2467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468
Douglas Gregor033f56d2008-12-23 00:53:59 +00002469 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002470 // differences in the argument and result types are in Objective-C
2471 // pointer conversions. If so, we permit the conversion (but
2472 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002473 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002474 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002475 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002476 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002477 if (FromFunctionType && ToFunctionType) {
2478 // If the function types are exactly the same, this isn't an
2479 // Objective-C pointer conversion.
2480 if (Context.getCanonicalType(FromPointeeType)
2481 == Context.getCanonicalType(ToPointeeType))
2482 return false;
2483
2484 // Perform the quick checks that will tell us whether these
2485 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002486 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002487 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2488 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2489 return false;
2490
2491 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002492 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2493 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002494 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002495 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2496 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002497 ConvertedType, IncompatibleObjC)) {
2498 // Okay, we have an Objective-C pointer conversion.
2499 HasObjCConversion = true;
2500 } else {
2501 // Function types are too different. Abort.
2502 return false;
2503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Douglas Gregora119f102008-12-19 19:13:09 +00002505 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002506 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002507 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002508 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2509 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002510 if (Context.getCanonicalType(FromArgType)
2511 == Context.getCanonicalType(ToArgType)) {
2512 // Okay, the types match exactly. Nothing to do.
2513 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2514 ConvertedType, IncompatibleObjC)) {
2515 // Okay, we have an Objective-C pointer conversion.
2516 HasObjCConversion = true;
2517 } else {
2518 // Argument types are too different. Abort.
2519 return false;
2520 }
2521 }
2522
2523 if (HasObjCConversion) {
2524 // We had an Objective-C conversion. Allow this pointer
2525 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002526 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002527 IncompatibleObjC = true;
2528 return true;
2529 }
2530 }
2531
Sebastian Redl72b597d2009-01-25 19:43:20 +00002532 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
John McCall31168b02011-06-15 23:02:42 +00002535/// \brief Determine whether this is an Objective-C writeback conversion,
2536/// used for parameter passing when performing automatic reference counting.
2537///
2538/// \param FromType The type we're converting form.
2539///
2540/// \param ToType The type we're converting to.
2541///
2542/// \param ConvertedType The type that will be produced after applying
2543/// this conversion.
2544bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2545 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002546 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002547 Context.hasSameUnqualifiedType(FromType, ToType))
2548 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002549
John McCall31168b02011-06-15 23:02:42 +00002550 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2551 QualType ToPointee;
2552 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2553 ToPointee = ToPointer->getPointeeType();
2554 else
2555 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002556
John McCall31168b02011-06-15 23:02:42 +00002557 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002558 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002559 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002560 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002561 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002562
John McCall31168b02011-06-15 23:02:42 +00002563 // Argument must be a pointer to __strong to __weak.
2564 QualType FromPointee;
2565 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2566 FromPointee = FromPointer->getPointeeType();
2567 else
2568 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002569
John McCall31168b02011-06-15 23:02:42 +00002570 Qualifiers FromQuals = FromPointee.getQualifiers();
2571 if (!FromPointee->isObjCLifetimeType() ||
2572 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2573 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2574 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002575
John McCall31168b02011-06-15 23:02:42 +00002576 // Make sure that we have compatible qualifiers.
2577 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2578 if (!ToQuals.compatiblyIncludes(FromQuals))
2579 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002580
John McCall31168b02011-06-15 23:02:42 +00002581 // Remove qualifiers from the pointee type we're converting from; they
2582 // aren't used in the compatibility check belong, and we'll be adding back
2583 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2584 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002585
John McCall31168b02011-06-15 23:02:42 +00002586 // The unqualified form of the pointee types must be compatible.
2587 ToPointee = ToPointee.getUnqualifiedType();
2588 bool IncompatibleObjC;
2589 if (Context.typesAreCompatible(FromPointee, ToPointee))
2590 FromPointee = ToPointee;
2591 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2592 IncompatibleObjC))
2593 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002594
John McCall31168b02011-06-15 23:02:42 +00002595 /// \brief Construct the type we're converting to, which is a pointer to
2596 /// __autoreleasing pointee.
2597 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2598 ConvertedType = Context.getPointerType(FromPointee);
2599 return true;
2600}
2601
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002602bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2603 QualType& ConvertedType) {
2604 QualType ToPointeeType;
2605 if (const BlockPointerType *ToBlockPtr =
2606 ToType->getAs<BlockPointerType>())
2607 ToPointeeType = ToBlockPtr->getPointeeType();
2608 else
2609 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002610
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002611 QualType FromPointeeType;
2612 if (const BlockPointerType *FromBlockPtr =
2613 FromType->getAs<BlockPointerType>())
2614 FromPointeeType = FromBlockPtr->getPointeeType();
2615 else
2616 return false;
2617 // We have pointer to blocks, check whether the only
2618 // differences in the argument and result types are in Objective-C
2619 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002620
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002621 const FunctionProtoType *FromFunctionType
2622 = FromPointeeType->getAs<FunctionProtoType>();
2623 const FunctionProtoType *ToFunctionType
2624 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002625
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002626 if (!FromFunctionType || !ToFunctionType)
2627 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002628
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002629 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002630 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002631
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002632 // Perform the quick checks that will tell us whether these
2633 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002634 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002635 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2636 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002637
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002638 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2639 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2640 if (FromEInfo != ToEInfo)
2641 return false;
2642
2643 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002644 if (Context.hasSameType(FromFunctionType->getReturnType(),
2645 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002646 // Okay, the types match exactly. Nothing to do.
2647 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002648 QualType RHS = FromFunctionType->getReturnType();
2649 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002650 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002651 !RHS.hasQualifiers() && LHS.hasQualifiers())
2652 LHS = LHS.getUnqualifiedType();
2653
2654 if (Context.hasSameType(RHS,LHS)) {
2655 // OK exact match.
2656 } else if (isObjCPointerConversion(RHS, LHS,
2657 ConvertedType, IncompatibleObjC)) {
2658 if (IncompatibleObjC)
2659 return false;
2660 // Okay, we have an Objective-C pointer conversion.
2661 }
2662 else
2663 return false;
2664 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002665
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002666 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002667 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002668 ArgIdx != NumArgs; ++ArgIdx) {
2669 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002670 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2671 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002672 if (Context.hasSameType(FromArgType, ToArgType)) {
2673 // Okay, the types match exactly. Nothing to do.
2674 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2675 ConvertedType, IncompatibleObjC)) {
2676 if (IncompatibleObjC)
2677 return false;
2678 // Okay, we have an Objective-C pointer conversion.
2679 } else
2680 // Argument types are too different. Abort.
2681 return false;
2682 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002683
2684 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2685 bool CanUseToFPT, CanUseFromFPT;
2686 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2687 CanUseToFPT, CanUseFromFPT,
2688 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002689 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002690
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002691 ConvertedType = ToType;
2692 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002693}
2694
Richard Trieucaff2472011-11-23 22:32:32 +00002695enum {
2696 ft_default,
2697 ft_different_class,
2698 ft_parameter_arity,
2699 ft_parameter_mismatch,
2700 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002701 ft_qualifer_mismatch,
2702 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002703};
2704
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002705/// Attempts to get the FunctionProtoType from a Type. Handles
2706/// MemberFunctionPointers properly.
2707static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2708 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2709 return FPT;
2710
2711 if (auto *MPT = FromType->getAs<MemberPointerType>())
2712 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2713
2714 return nullptr;
2715}
2716
Richard Trieucaff2472011-11-23 22:32:32 +00002717/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2718/// function types. Catches different number of parameter, mismatch in
2719/// parameter types, and different return types.
2720void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2721 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002722 // If either type is not valid, include no extra info.
2723 if (FromType.isNull() || ToType.isNull()) {
2724 PDiag << ft_default;
2725 return;
2726 }
2727
Richard Trieucaff2472011-11-23 22:32:32 +00002728 // Get the function type from the pointers.
2729 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2730 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2731 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002732 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002733 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2734 << QualType(FromMember->getClass(), 0);
2735 return;
2736 }
2737 FromType = FromMember->getPointeeType();
2738 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002739 }
2740
Richard Trieu96ed5b62011-12-13 23:19:45 +00002741 if (FromType->isPointerType())
2742 FromType = FromType->getPointeeType();
2743 if (ToType->isPointerType())
2744 ToType = ToType->getPointeeType();
2745
2746 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002747 FromType = FromType.getNonReferenceType();
2748 ToType = ToType.getNonReferenceType();
2749
Richard Trieucaff2472011-11-23 22:32:32 +00002750 // Don't print extra info for non-specialized template functions.
2751 if (FromType->isInstantiationDependentType() &&
2752 !FromType->getAs<TemplateSpecializationType>()) {
2753 PDiag << ft_default;
2754 return;
2755 }
2756
Richard Trieu96ed5b62011-12-13 23:19:45 +00002757 // No extra info for same types.
2758 if (Context.hasSameType(FromType, ToType)) {
2759 PDiag << ft_default;
2760 return;
2761 }
2762
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002763 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2764 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002765
2766 // Both types need to be function types.
2767 if (!FromFunction || !ToFunction) {
2768 PDiag << ft_default;
2769 return;
2770 }
2771
Alp Toker9cacbab2014-01-20 20:26:09 +00002772 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2773 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2774 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002775 return;
2776 }
2777
2778 // Handle different parameter types.
2779 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002780 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002781 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002782 << ToFunction->getParamType(ArgPos)
2783 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002784 return;
2785 }
2786
2787 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002788 if (!Context.hasSameType(FromFunction->getReturnType(),
2789 ToFunction->getReturnType())) {
2790 PDiag << ft_return_type << ToFunction->getReturnType()
2791 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002792 return;
2793 }
2794
2795 unsigned FromQuals = FromFunction->getTypeQuals(),
2796 ToQuals = ToFunction->getTypeQuals();
2797 if (FromQuals != ToQuals) {
2798 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2799 return;
2800 }
2801
Richard Smith3c4f8d22016-10-16 17:54:23 +00002802 // Handle exception specification differences on canonical type (in C++17
2803 // onwards).
2804 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2805 ->isNothrow(Context) !=
2806 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2807 ->isNothrow(Context)) {
2808 PDiag << ft_noexcept;
2809 return;
2810 }
2811
Richard Trieucaff2472011-11-23 22:32:32 +00002812 // Unable to find a difference, so add no extra info.
2813 PDiag << ft_default;
2814}
2815
Alp Toker9cacbab2014-01-20 20:26:09 +00002816/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002817/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002818/// they have same number of arguments. If the parameters are different,
2819/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002820bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2821 const FunctionProtoType *NewType,
2822 unsigned *ArgPos) {
2823 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2824 N = NewType->param_type_begin(),
2825 E = OldType->param_type_end();
2826 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002827 if (!Context.hasSameType(O->getUnqualifiedType(),
2828 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002829 if (ArgPos)
2830 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002831 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002832 }
2833 }
2834 return true;
2835}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002836
Douglas Gregor39c16d42008-10-24 04:54:22 +00002837/// CheckPointerConversion - Check the pointer conversion from the
2838/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002839/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002840/// conversions for which IsPointerConversion has already returned
2841/// true. It returns true and produces a diagnostic if there was an
2842/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002843bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002844 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002845 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002846 bool IgnoreBaseAccess,
2847 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002848 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002849 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002850
John McCall8cb679e2010-11-15 09:13:47 +00002851 Kind = CK_BitCast;
2852
George Burgess IV60bc9722016-01-13 23:36:34 +00002853 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002854 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002855 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002856 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2857 DiagRuntimeBehavior(From->getExprLoc(), From,
2858 PDiag(diag::warn_impcast_bool_to_null_pointer)
2859 << ToType << From->getSourceRange());
2860 else if (!isUnevaluatedContext())
2861 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2862 << ToType << From->getSourceRange();
2863 }
John McCall9320b872011-09-09 05:25:32 +00002864 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2865 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002866 QualType FromPointeeType = FromPtrType->getPointeeType(),
2867 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002868
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002869 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2870 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002871 // We must have a derived-to-base conversion. Check an
2872 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002873 unsigned InaccessibleID = 0;
2874 unsigned AmbigiousID = 0;
2875 if (Diagnose) {
2876 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2877 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2878 }
2879 if (CheckDerivedToBaseConversion(
2880 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2881 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2882 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002883 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002885 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002886 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002887 }
David Majnemer6bf02822015-10-31 08:42:14 +00002888
George Burgess IV60bc9722016-01-13 23:36:34 +00002889 if (Diagnose && !IsCStyleOrFunctionalCast &&
2890 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002891 assert(getLangOpts().MSVCCompat &&
2892 "this should only be possible with MSVCCompat!");
2893 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2894 << From->getSourceRange();
2895 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002896 }
John McCall9320b872011-09-09 05:25:32 +00002897 } else if (const ObjCObjectPointerType *ToPtrType =
2898 ToType->getAs<ObjCObjectPointerType>()) {
2899 if (const ObjCObjectPointerType *FromPtrType =
2900 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002901 // Objective-C++ conversions are always okay.
2902 // FIXME: We should have a different class of conversions for the
2903 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002904 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002905 return false;
John McCall9320b872011-09-09 05:25:32 +00002906 } else if (FromType->isBlockPointerType()) {
2907 Kind = CK_BlockPointerToObjCPointerCast;
2908 } else {
2909 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002910 }
John McCall9320b872011-09-09 05:25:32 +00002911 } else if (ToType->isBlockPointerType()) {
2912 if (!FromType->isBlockPointerType())
2913 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002914 }
John McCall8cb679e2010-11-15 09:13:47 +00002915
2916 // We shouldn't fall into this case unless it's valid for other
2917 // reasons.
2918 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2919 Kind = CK_NullToPointer;
2920
Douglas Gregor39c16d42008-10-24 04:54:22 +00002921 return false;
2922}
2923
Sebastian Redl72b597d2009-01-25 19:43:20 +00002924/// IsMemberPointerConversion - Determines whether the conversion of the
2925/// expression From, which has the (possibly adjusted) type FromType, can be
2926/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2927/// If so, returns true and places the converted type (that might differ from
2928/// ToType in its cv-qualifiers at some level) into ConvertedType.
2929bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002931 bool InOverloadResolution,
2932 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002933 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002934 if (!ToTypePtr)
2935 return false;
2936
2937 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002938 if (From->isNullPointerConstant(Context,
2939 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2940 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002941 ConvertedType = ToType;
2942 return true;
2943 }
2944
2945 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002946 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002947 if (!FromTypePtr)
2948 return false;
2949
2950 // A pointer to member of B can be converted to a pointer to member of D,
2951 // where D is derived from B (C++ 4.11p2).
2952 QualType FromClass(FromTypePtr->getClass(), 0);
2953 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002954
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002955 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002956 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002957 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2958 ToClass.getTypePtr());
2959 return true;
2960 }
2961
2962 return false;
2963}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965/// CheckMemberPointerConversion - Check the member pointer conversion from the
2966/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002967/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002968/// for which IsMemberPointerConversion has already returned true. It returns
2969/// true and produces a diagnostic if there was an error, or returns false
2970/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002971bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002972 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002973 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002974 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002977 if (!FromPtrType) {
2978 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002980 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002981 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002982 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002983 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002984 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002986 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002987 assert(ToPtrType && "No member pointer cast has a target type "
2988 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002989
Sebastian Redled8f2002009-01-28 18:33:18 +00002990 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2991 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002992
Sebastian Redled8f2002009-01-28 18:33:18 +00002993 // FIXME: What about dependent types?
2994 assert(FromClass->isRecordType() && "Pointer into non-class.");
2995 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002996
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002998 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002999 bool DerivationOkay =
3000 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003001 assert(DerivationOkay &&
3002 "Should not have been called if derivation isn't OK.");
3003 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003004
Sebastian Redled8f2002009-01-28 18:33:18 +00003005 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3006 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003007 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3008 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3009 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3010 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003011 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003012
Douglas Gregor89ee6822009-02-28 01:32:25 +00003013 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003014 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3015 << FromClass << ToClass << QualType(VBase, 0)
3016 << From->getSourceRange();
3017 return true;
3018 }
3019
John McCall5b0829a2010-02-10 09:31:12 +00003020 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003021 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3022 Paths.front(),
3023 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003024
Anders Carlssond7923c62009-08-22 23:33:40 +00003025 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003026 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003027 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003028 return false;
3029}
3030
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003031/// Determine whether the lifetime conversion between the two given
3032/// qualifiers sets is nontrivial.
3033static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3034 Qualifiers ToQuals) {
3035 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003036 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003037 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3038 return false;
3039
3040 return true;
3041}
3042
Douglas Gregor9a657932008-10-21 23:43:52 +00003043/// IsQualificationConversion - Determines whether the conversion from
3044/// an rvalue of type FromType to ToType is a qualification conversion
3045/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003046///
3047/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3048/// when the qualification conversion involves a change in the Objective-C
3049/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003050bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003052 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003053 FromType = Context.getCanonicalType(FromType);
3054 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003055 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003056
Douglas Gregor9a657932008-10-21 23:43:52 +00003057 // If FromType and ToType are the same type, this is not a
3058 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003059 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003060 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003061
Douglas Gregor9a657932008-10-21 23:43:52 +00003062 // (C++ 4.4p4):
3063 // A conversion can add cv-qualifiers at levels other than the first
3064 // in multi-level pointers, subject to the following rules: [...]
3065 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003066 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003067 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003068 // Within each iteration of the loop, we check the qualifiers to
3069 // determine if this still looks like a qualification
3070 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003071 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003072 // until there are no more pointers or pointers-to-members left to
3073 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003074 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003075
Douglas Gregor90609aa2011-04-25 18:40:17 +00003076 Qualifiers FromQuals = FromType.getQualifiers();
3077 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003078
3079 // Ignore __unaligned qualifier if this type is void.
3080 if (ToType.getUnqualifiedType()->isVoidType())
3081 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003082
John McCall31168b02011-06-15 23:02:42 +00003083 // Objective-C ARC:
3084 // Check Objective-C lifetime conversions.
3085 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3086 UnwrappedAnyPointer) {
3087 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003088 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3089 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003090 FromQuals.removeObjCLifetime();
3091 ToQuals.removeObjCLifetime();
3092 } else {
3093 // Qualification conversions cannot cast between different
3094 // Objective-C lifetime qualifiers.
3095 return false;
3096 }
3097 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003098
Douglas Gregorf30053d2011-05-08 06:09:53 +00003099 // Allow addition/removal of GC attributes but not changing GC attributes.
3100 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3101 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3102 FromQuals.removeObjCGCAttr();
3103 ToQuals.removeObjCGCAttr();
3104 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003105
Douglas Gregor9a657932008-10-21 23:43:52 +00003106 // -- for every j > 0, if const is in cv 1,j then const is in cv
3107 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003108 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003109 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003110
Douglas Gregor9a657932008-10-21 23:43:52 +00003111 // -- if the cv 1,j and cv 2,j are different, then const is in
3112 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003113 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003114 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003115 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003116
Douglas Gregor9a657932008-10-21 23:43:52 +00003117 // Keep track of whether all prior cv-qualifiers in the "to" type
3118 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003119 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003120 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003121 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003122
3123 // We are left with FromType and ToType being the pointee types
3124 // after unwrapping the original FromType and ToType the same number
3125 // of types. If we unwrapped any pointers, and if FromType and
3126 // ToType have the same unqualified type (since we checked
3127 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003128 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003129}
3130
Douglas Gregorc79862f2012-04-12 17:51:55 +00003131/// \brief - Determine whether this is a conversion from a scalar type to an
3132/// atomic type.
3133///
3134/// If successful, updates \c SCS's second and third steps in the conversion
3135/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003136static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3137 bool InOverloadResolution,
3138 StandardConversionSequence &SCS,
3139 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003140 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3141 if (!ToAtomic)
3142 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003143
Douglas Gregorc79862f2012-04-12 17:51:55 +00003144 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003145 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003146 InOverloadResolution, InnerSCS,
3147 CStyle, /*AllowObjCWritebackConversion=*/false))
3148 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003149
Douglas Gregorc79862f2012-04-12 17:51:55 +00003150 SCS.Second = InnerSCS.Second;
3151 SCS.setToType(1, InnerSCS.getToType(1));
3152 SCS.Third = InnerSCS.Third;
3153 SCS.QualificationIncludesObjCLifetime
3154 = InnerSCS.QualificationIncludesObjCLifetime;
3155 SCS.setToType(2, InnerSCS.getToType(2));
3156 return true;
3157}
3158
Sebastian Redle5417162012-03-27 18:33:03 +00003159static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3160 CXXConstructorDecl *Constructor,
3161 QualType Type) {
3162 const FunctionProtoType *CtorType =
3163 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003164 if (CtorType->getNumParams() > 0) {
3165 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003166 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3167 return true;
3168 }
3169 return false;
3170}
3171
Sebastian Redl82ace982012-02-11 23:51:08 +00003172static OverloadingResult
3173IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3174 CXXRecordDecl *To,
3175 UserDefinedConversionSequence &User,
3176 OverloadCandidateSet &CandidateSet,
3177 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003178 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003179 for (auto *D : S.LookupConstructors(To)) {
3180 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003181 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003182 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003183
Richard Smithc2bebe92016-05-11 20:37:46 +00003184 bool Usable = !Info.Constructor->isInvalidDecl() &&
3185 S.isInitListConstructor(Info.Constructor) &&
3186 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003187 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003188 // If the first argument is (a reference to) the target type,
3189 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003190 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3191 S.Context, Info.Constructor, ToType);
3192 if (Info.ConstructorTmpl)
3193 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3194 /*ExplicitArgs*/ nullptr, From,
3195 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003196 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003197 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3198 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003199 }
3200 }
3201
3202 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3203
3204 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003205 switch (auto Result =
3206 CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003207 Best)) {
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003208 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003209 case OR_Success: {
3210 // Record the standard conversion we used and the conversion function.
3211 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003212 QualType ThisType = Constructor->getThisType(S.Context);
3213 // Initializer lists don't have conversions as such.
3214 User.Before.setAsIdentityConversion();
3215 User.HadMultipleCandidates = HadMultipleCandidates;
3216 User.ConversionFunction = Constructor;
3217 User.FoundConversionFunction = Best->FoundDecl;
3218 User.After.setAsIdentityConversion();
3219 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3220 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003221 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003222 }
3223
3224 case OR_No_Viable_Function:
3225 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003226 case OR_Ambiguous:
3227 return OR_Ambiguous;
3228 }
3229
3230 llvm_unreachable("Invalid OverloadResult!");
3231}
3232
Douglas Gregor576e98c2009-01-30 23:27:23 +00003233/// Determines whether there is a user-defined conversion sequence
3234/// (C++ [over.ics.user]) that converts expression From to the type
3235/// ToType. If such a conversion exists, User will contain the
3236/// user-defined conversion sequence that performs such a conversion
3237/// and this routine will return true. Otherwise, this routine returns
3238/// false and User is unspecified.
3239///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003240/// \param AllowExplicit true if the conversion should consider C++0x
3241/// "explicit" conversion functions as well as non-explicit conversion
3242/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003243///
3244/// \param AllowObjCConversionOnExplicit true if the conversion should
3245/// allow an extra Objective-C pointer conversion on uses of explicit
3246/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003247static OverloadingResult
3248IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003249 UserDefinedConversionSequence &User,
3250 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003251 bool AllowExplicit,
3252 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003253 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Richard Smith67ef14f2017-09-26 18:37:55 +00003254 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003255
Douglas Gregor5ab11652010-04-17 22:01:05 +00003256 // Whether we will only visit constructors.
3257 bool ConstructorsOnly = false;
3258
3259 // If the type we are conversion to is a class type, enumerate its
3260 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003261 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003262 // C++ [over.match.ctor]p1:
3263 // When objects of class type are direct-initialized (8.5), or
3264 // copy-initialized from an expression of the same or a
3265 // derived class type (8.5), overload resolution selects the
3266 // constructor. [...] For copy-initialization, the candidate
3267 // functions are all the converting constructors (12.3.1) of
3268 // that class. The argument list is the expression-list within
3269 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003270 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003271 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003272 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003273 ConstructorsOnly = true;
3274
Richard Smithdb0ac552015-12-18 22:40:25 +00003275 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003276 // We're not going to find any constructors.
3277 } else if (CXXRecordDecl *ToRecordDecl
3278 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003279
3280 Expr **Args = &From;
3281 unsigned NumArgs = 1;
3282 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003283 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003284 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003285 OverloadingResult Result = IsInitializerListConstructorConversion(
3286 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3287 if (Result != OR_No_Viable_Function)
3288 return Result;
3289 // Never mind.
Richard Smith67ef14f2017-09-26 18:37:55 +00003290 CandidateSet.clear(
3291 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Sebastian Redl82ace982012-02-11 23:51:08 +00003292
3293 // If we're list-initializing, we pass the individual elements as
3294 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003295 Args = InitList->getInits();
3296 NumArgs = InitList->getNumInits();
3297 ListInitializing = true;
3298 }
3299
Richard Smithc2bebe92016-05-11 20:37:46 +00003300 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3301 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003302 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003303 continue;
John McCalla0296f72010-03-19 07:35:19 +00003304
Richard Smithc2bebe92016-05-11 20:37:46 +00003305 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003306 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003307 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003308 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003309 Usable = Usable &&
3310 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003311 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003312 bool SuppressUserConversions = !ConstructorsOnly;
3313 if (SuppressUserConversions && ListInitializing) {
3314 SuppressUserConversions = false;
3315 if (NumArgs == 1) {
3316 // If the first argument is (a reference to) the target type,
3317 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003318 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003319 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003320 }
3321 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003322 if (Info.ConstructorTmpl)
3323 S.AddTemplateOverloadCandidate(
3324 Info.ConstructorTmpl, Info.FoundDecl,
3325 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3326 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003327 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003328 // Allow one user-defined conversion when user specifies a
3329 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003330 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003331 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003332 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003333 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003334 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003335 }
3336 }
3337
Douglas Gregor5ab11652010-04-17 22:01:05 +00003338 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003339 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003340 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003341 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003342 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003343 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003344 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003345 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3346 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003347 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3348 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003349 DeclAccessPair FoundDecl = I.getPair();
3350 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003351 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3352 if (isa<UsingShadowDecl>(D))
3353 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3354
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003355 CXXConversionDecl *Conv;
3356 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003357 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3358 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003359 else
John McCallda4458e2010-03-31 01:36:47 +00003360 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003361
3362 if (AllowExplicit || !Conv->isExplicit()) {
3363 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003364 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3365 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003366 CandidateSet,
3367 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003368 else
John McCall5c32be02010-08-24 20:38:10 +00003369 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003370 From, ToType, CandidateSet,
3371 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003372 }
3373 }
3374 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003375 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003376
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003377 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3378
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003379 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003380 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003381 Best)) {
John McCall5c32be02010-08-24 20:38:10 +00003382 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003383 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003384 // Record the standard conversion we used and the conversion function.
3385 if (CXXConstructorDecl *Constructor
3386 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3387 // C++ [over.ics.user]p1:
3388 // If the user-defined conversion is specified by a
3389 // constructor (12.3.1), the initial standard conversion
3390 // sequence converts the source type to the type required by
3391 // the argument of the constructor.
3392 //
3393 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003394 if (isa<InitListExpr>(From)) {
3395 // Initializer lists don't have conversions as such.
3396 User.Before.setAsIdentityConversion();
3397 } else {
3398 if (Best->Conversions[0].isEllipsis())
3399 User.EllipsisConversion = true;
3400 else {
3401 User.Before = Best->Conversions[0].Standard;
3402 User.EllipsisConversion = false;
3403 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003404 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003405 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003406 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003407 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003408 User.After.setAsIdentityConversion();
3409 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3410 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003411 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003412 }
3413 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003414 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3415 // C++ [over.ics.user]p1:
3416 //
3417 // [...] If the user-defined conversion is specified by a
3418 // conversion function (12.3.2), the initial standard
3419 // conversion sequence converts the source type to the
3420 // implicit object parameter of the conversion function.
3421 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003422 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003423 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003424 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003425 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003426
John McCall5c32be02010-08-24 20:38:10 +00003427 // C++ [over.ics.user]p2:
3428 // The second standard conversion sequence converts the
3429 // result of the user-defined conversion to the target type
3430 // for the sequence. Since an implicit conversion sequence
3431 // is an initialization, the special rules for
3432 // initialization by user-defined conversion apply when
3433 // selecting the best user-defined conversion for a
3434 // user-defined conversion sequence (see 13.3.3 and
3435 // 13.3.3.1).
3436 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003437 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003438 }
David Blaikie8a40f702012-01-17 06:56:22 +00003439 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003440
John McCall5c32be02010-08-24 20:38:10 +00003441 case OR_No_Viable_Function:
3442 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443
John McCall5c32be02010-08-24 20:38:10 +00003444 case OR_Ambiguous:
3445 return OR_Ambiguous;
3446 }
3447
David Blaikie8a40f702012-01-17 06:56:22 +00003448 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003449}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003451bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003452Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003453 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003454 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3455 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003457 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003458 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003459 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003460 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3461 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003462 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003463 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003464 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003465 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003466 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003467 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003468 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003469 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003470 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003472}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003473
Douglas Gregor2837aa22012-02-22 17:32:19 +00003474/// \brief Compare the user-defined conversion functions or constructors
3475/// of two user-defined conversion sequences to determine whether any ordering
3476/// is possible.
3477static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003478compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003479 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003480 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003481 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003482
Douglas Gregor2837aa22012-02-22 17:32:19 +00003483 // Objective-C++:
3484 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003485 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003486 // respectively, always prefer the conversion to a function pointer,
3487 // because the function pointer is more lightweight and is more likely
3488 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003489 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003490 if (!Conv1)
3491 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003492
Douglas Gregor2837aa22012-02-22 17:32:19 +00003493 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3494 if (!Conv2)
3495 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003496
Douglas Gregor2837aa22012-02-22 17:32:19 +00003497 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3498 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3499 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3500 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003501 return Block1 ? ImplicitConversionSequence::Worse
3502 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003503 }
3504
3505 return ImplicitConversionSequence::Indistinguishable;
3506}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003507
3508static bool hasDeprecatedStringLiteralToCharPtrConversion(
3509 const ImplicitConversionSequence &ICS) {
3510 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3511 (ICS.isUserDefined() &&
3512 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3513}
3514
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003515/// CompareImplicitConversionSequences - Compare two implicit
3516/// conversion sequences to determine whether one is better than the
3517/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003518static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003519CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003520 const ImplicitConversionSequence& ICS1,
3521 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003522{
3523 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3524 // conversion sequences (as defined in 13.3.3.1)
3525 // -- a standard conversion sequence (13.3.3.1.1) is a better
3526 // conversion sequence than a user-defined conversion sequence or
3527 // an ellipsis conversion sequence, and
3528 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3529 // conversion sequence than an ellipsis conversion sequence
3530 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003531 //
John McCall0d1da222010-01-12 00:44:57 +00003532 // C++0x [over.best.ics]p10:
3533 // For the purpose of ranking implicit conversion sequences as
3534 // described in 13.3.3.2, the ambiguous conversion sequence is
3535 // treated as a user-defined sequence that is indistinguishable
3536 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003537
3538 // String literal to 'char *' conversion has been deprecated in C++03. It has
3539 // been removed from C++11. We still accept this conversion, if it happens at
3540 // the best viable function. Otherwise, this conversion is considered worse
3541 // than ellipsis conversion. Consider this as an extension; this is not in the
3542 // standard. For example:
3543 //
3544 // int &f(...); // #1
3545 // void f(char*); // #2
3546 // void g() { int &r = f("foo"); }
3547 //
3548 // In C++03, we pick #2 as the best viable function.
3549 // In C++11, we pick #1 as the best viable function, because ellipsis
3550 // conversion is better than string-literal to char* conversion (since there
3551 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3552 // convert arguments, #2 would be the best viable function in C++11.
3553 // If the best viable function has this conversion, a warning will be issued
3554 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3555
3556 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3557 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3558 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3559 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3560 ? ImplicitConversionSequence::Worse
3561 : ImplicitConversionSequence::Better;
3562
Douglas Gregor5ab11652010-04-17 22:01:05 +00003563 if (ICS1.getKindRank() < ICS2.getKindRank())
3564 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003565 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003566 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003567
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003568 // The following checks require both conversion sequences to be of
3569 // the same kind.
3570 if (ICS1.getKind() != ICS2.getKind())
3571 return ImplicitConversionSequence::Indistinguishable;
3572
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003573 ImplicitConversionSequence::CompareKind Result =
3574 ImplicitConversionSequence::Indistinguishable;
3575
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003576 // Two implicit conversion sequences of the same form are
3577 // indistinguishable conversion sequences unless one of the
3578 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003579
Larisse Voufo19d08672015-01-27 18:47:05 +00003580 // List-initialization sequence L1 is a better conversion sequence than
3581 // list-initialization sequence L2 if:
3582 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3583 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003584 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003585 // and N1 is smaller than N2.,
3586 // even if one of the other rules in this paragraph would otherwise apply.
3587 if (!ICS1.isBad()) {
3588 if (ICS1.isStdInitializerListElement() &&
3589 !ICS2.isStdInitializerListElement())
3590 return ImplicitConversionSequence::Better;
3591 if (!ICS1.isStdInitializerListElement() &&
3592 ICS2.isStdInitializerListElement())
3593 return ImplicitConversionSequence::Worse;
3594 }
3595
John McCall0d1da222010-01-12 00:44:57 +00003596 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003597 // Standard conversion sequence S1 is a better conversion sequence than
3598 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003599 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003600 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003601 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003602 // User-defined conversion sequence U1 is a better conversion
3603 // sequence than another user-defined conversion sequence U2 if
3604 // they contain the same user-defined conversion function or
3605 // constructor and if the second standard conversion sequence of
3606 // U1 is better than the second standard conversion sequence of
3607 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003608 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003609 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003610 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003611 ICS1.UserDefined.After,
3612 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003613 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003614 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003615 ICS1.UserDefined.ConversionFunction,
3616 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003617 }
3618
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003619 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003620}
3621
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003622static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3623 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3624 Qualifiers Quals;
3625 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003629 return Context.hasSameUnqualifiedType(T1, T2);
3630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003632// Per 13.3.3.2p3, compare the given standard conversion sequences to
3633// determine if one is a proper subset of the other.
3634static ImplicitConversionSequence::CompareKind
3635compareStandardConversionSubsets(ASTContext &Context,
3636 const StandardConversionSequence& SCS1,
3637 const StandardConversionSequence& SCS2) {
3638 ImplicitConversionSequence::CompareKind Result
3639 = ImplicitConversionSequence::Indistinguishable;
3640
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003642 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003643 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3644 return ImplicitConversionSequence::Better;
3645 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3646 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003648 if (SCS1.Second != SCS2.Second) {
3649 if (SCS1.Second == ICK_Identity)
3650 Result = ImplicitConversionSequence::Better;
3651 else if (SCS2.Second == ICK_Identity)
3652 Result = ImplicitConversionSequence::Worse;
3653 else
3654 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003655 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003656 return ImplicitConversionSequence::Indistinguishable;
3657
3658 if (SCS1.Third == SCS2.Third) {
3659 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3660 : ImplicitConversionSequence::Indistinguishable;
3661 }
3662
3663 if (SCS1.Third == ICK_Identity)
3664 return Result == ImplicitConversionSequence::Worse
3665 ? ImplicitConversionSequence::Indistinguishable
3666 : ImplicitConversionSequence::Better;
3667
3668 if (SCS2.Third == ICK_Identity)
3669 return Result == ImplicitConversionSequence::Better
3670 ? ImplicitConversionSequence::Indistinguishable
3671 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003673 return ImplicitConversionSequence::Indistinguishable;
3674}
3675
Douglas Gregore696ebb2011-01-26 14:52:12 +00003676/// \brief Determine whether one of the given reference bindings is better
3677/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003678static bool
3679isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3680 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003681 // C++0x [over.ics.rank]p3b4:
3682 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3683 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003685 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003687 // reference*.
3688 //
3689 // FIXME: Rvalue references. We're going rogue with the above edits,
3690 // because the semantics in the current C++0x working paper (N3225 at the
3691 // time of this writing) break the standard definition of std::forward
3692 // and std::reference_wrapper when dealing with references to functions.
3693 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003694 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3695 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3696 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
Douglas Gregore696ebb2011-01-26 14:52:12 +00003698 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3699 SCS2.IsLvalueReference) ||
3700 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003701 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003702}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003704/// CompareStandardConversionSequences - Compare two standard
3705/// conversion sequences to determine whether one is better than the
3706/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003707static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003708CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003709 const StandardConversionSequence& SCS1,
3710 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003711{
3712 // Standard conversion sequence S1 is a better conversion sequence
3713 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3714
3715 // -- S1 is a proper subsequence of S2 (comparing the conversion
3716 // sequences in the canonical form defined by 13.3.3.1.1,
3717 // excluding any Lvalue Transformation; the identity conversion
3718 // sequence is considered to be a subsequence of any
3719 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003720 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003721 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003722 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003723
3724 // -- the rank of S1 is better than the rank of S2 (by the rules
3725 // defined below), or, if not that,
3726 ImplicitConversionRank Rank1 = SCS1.getRank();
3727 ImplicitConversionRank Rank2 = SCS2.getRank();
3728 if (Rank1 < Rank2)
3729 return ImplicitConversionSequence::Better;
3730 else if (Rank2 < Rank1)
3731 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003732
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003733 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3734 // are indistinguishable unless one of the following rules
3735 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003736
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003737 // A conversion that is not a conversion of a pointer, or
3738 // pointer to member, to bool is better than another conversion
3739 // that is such a conversion.
3740 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3741 return SCS2.isPointerConversionToBool()
3742 ? ImplicitConversionSequence::Better
3743 : ImplicitConversionSequence::Worse;
3744
Douglas Gregor5c407d92008-10-23 00:40:37 +00003745 // C++ [over.ics.rank]p4b2:
3746 //
3747 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003748 // conversion of B* to A* is better than conversion of B* to
3749 // void*, and conversion of A* to void* is better than conversion
3750 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003751 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003752 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003753 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003754 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003755 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3756 // Exactly one of the conversion sequences is a conversion to
3757 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003758 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3759 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003760 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3761 // Neither conversion sequence converts to a void pointer; compare
3762 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003763 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003764 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003765 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003766 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3767 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003768 // Both conversion sequences are conversions to void
3769 // pointers. Compare the source types to determine if there's an
3770 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003771 QualType FromType1 = SCS1.getFromType();
3772 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003773
3774 // Adjust the types we're converting from via the array-to-pointer
3775 // conversion, if we need to.
3776 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003777 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003778 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003779 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003780
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003781 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3782 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003783
Richard Smith0f59cb32015-12-18 21:45:41 +00003784 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003785 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003786 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003787 return ImplicitConversionSequence::Worse;
3788
3789 // Objective-C++: If one interface is more specific than the
3790 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003791 const ObjCObjectPointerType* FromObjCPtr1
3792 = FromType1->getAs<ObjCObjectPointerType>();
3793 const ObjCObjectPointerType* FromObjCPtr2
3794 = FromType2->getAs<ObjCObjectPointerType>();
3795 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003796 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003797 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003798 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003799 FromObjCPtr1);
3800 if (AssignLeft != AssignRight) {
3801 return AssignLeft? ImplicitConversionSequence::Better
3802 : ImplicitConversionSequence::Worse;
3803 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003804 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003805 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003806
3807 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3808 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003809 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003810 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003811 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003812
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003813 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003814 // Check for a better reference binding based on the kind of bindings.
3815 if (isBetterReferenceBindingKind(SCS1, SCS2))
3816 return ImplicitConversionSequence::Better;
3817 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3818 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819
Sebastian Redlb28b4072009-03-22 23:49:27 +00003820 // C++ [over.ics.rank]p3b4:
3821 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3822 // which the references refer are the same type except for
3823 // top-level cv-qualifiers, and the type to which the reference
3824 // initialized by S2 refers is more cv-qualified than the type
3825 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003826 QualType T1 = SCS1.getToType(2);
3827 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003828 T1 = S.Context.getCanonicalType(T1);
3829 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003830 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003831 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3832 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003833 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003834 // Objective-C++ ARC: If the references refer to objects with different
3835 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003836 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003837 SCS2.ObjCLifetimeConversionBinding) {
3838 return SCS1.ObjCLifetimeConversionBinding
3839 ? ImplicitConversionSequence::Worse
3840 : ImplicitConversionSequence::Better;
3841 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003842
Chandler Carruth8e543b32010-12-12 08:17:55 +00003843 // If the type is an array type, promote the element qualifiers to the
3844 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003845 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003846 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003847 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003848 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003849 if (T2.isMoreQualifiedThan(T1))
3850 return ImplicitConversionSequence::Better;
3851 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003852 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003853 }
3854 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003855
Francois Pichet08d2fa02011-09-18 21:37:37 +00003856 // In Microsoft mode, prefer an integral conversion to a
3857 // floating-to-integral conversion if the integral conversion
3858 // is between types of the same size.
3859 // For example:
3860 // void f(float);
3861 // void f(int);
3862 // int main {
3863 // long a;
3864 // f(a);
3865 // }
3866 // Here, MSVC will call f(int) instead of generating a compile error
3867 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003868 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3869 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003870 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003871 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003872 return ImplicitConversionSequence::Better;
3873
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003874 return ImplicitConversionSequence::Indistinguishable;
3875}
3876
3877/// CompareQualificationConversions - Compares two standard conversion
3878/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003879/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003880static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003881CompareQualificationConversions(Sema &S,
3882 const StandardConversionSequence& SCS1,
3883 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003884 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003885 // -- S1 and S2 differ only in their qualification conversion and
3886 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3887 // cv-qualification signature of type T1 is a proper subset of
3888 // the cv-qualification signature of type T2, and S1 is not the
3889 // deprecated string literal array-to-pointer conversion (4.2).
3890 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3891 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3892 return ImplicitConversionSequence::Indistinguishable;
3893
3894 // FIXME: the example in the standard doesn't use a qualification
3895 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003896 QualType T1 = SCS1.getToType(2);
3897 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003898 T1 = S.Context.getCanonicalType(T1);
3899 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003900 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003901 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3902 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003903
3904 // If the types are the same, we won't learn anything by unwrapped
3905 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003906 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003907 return ImplicitConversionSequence::Indistinguishable;
3908
Chandler Carruth607f38e2009-12-29 07:16:59 +00003909 // If the type is an array type, promote the element qualifiers to the type
3910 // for comparison.
3911 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003912 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003913 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003914 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003915
Mike Stump11289f42009-09-09 15:08:12 +00003916 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003917 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003918
John McCall31168b02011-06-15 23:02:42 +00003919 // Objective-C++ ARC:
3920 // Prefer qualification conversions not involving a change in lifetime
3921 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003922 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003923 SCS2.QualificationIncludesObjCLifetime) {
3924 Result = SCS1.QualificationIncludesObjCLifetime
3925 ? ImplicitConversionSequence::Worse
3926 : ImplicitConversionSequence::Better;
3927 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003928
John McCall5c32be02010-08-24 20:38:10 +00003929 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003930 // Within each iteration of the loop, we check the qualifiers to
3931 // determine if this still looks like a qualification
3932 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003933 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003934 // until there are no more pointers or pointers-to-members left
3935 // to unwrap. This essentially mimics what
3936 // IsQualificationConversion does, but here we're checking for a
3937 // strict subset of qualifiers.
3938 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3939 // The qualifiers are the same, so this doesn't tell us anything
3940 // about how the sequences rank.
3941 ;
3942 else if (T2.isMoreQualifiedThan(T1)) {
3943 // T1 has fewer qualifiers, so it could be the better sequence.
3944 if (Result == ImplicitConversionSequence::Worse)
3945 // Neither has qualifiers that are a subset of the other's
3946 // qualifiers.
3947 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003948
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003949 Result = ImplicitConversionSequence::Better;
3950 } else if (T1.isMoreQualifiedThan(T2)) {
3951 // T2 has fewer qualifiers, so it could be the better sequence.
3952 if (Result == ImplicitConversionSequence::Better)
3953 // Neither has qualifiers that are a subset of the other's
3954 // qualifiers.
3955 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003956
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003957 Result = ImplicitConversionSequence::Worse;
3958 } else {
3959 // Qualifiers are disjoint.
3960 return ImplicitConversionSequence::Indistinguishable;
3961 }
3962
3963 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003964 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003965 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003966 }
3967
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003968 // Check that the winning standard conversion sequence isn't using
3969 // the deprecated string literal array to pointer conversion.
3970 switch (Result) {
3971 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003972 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003973 Result = ImplicitConversionSequence::Indistinguishable;
3974 break;
3975
3976 case ImplicitConversionSequence::Indistinguishable:
3977 break;
3978
3979 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003980 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003981 Result = ImplicitConversionSequence::Indistinguishable;
3982 break;
3983 }
3984
3985 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003986}
3987
Douglas Gregor5c407d92008-10-23 00:40:37 +00003988/// CompareDerivedToBaseConversions - Compares two standard conversion
3989/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003990/// various kinds of derived-to-base conversions (C++
3991/// [over.ics.rank]p4b3). As part of these checks, we also look at
3992/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003993static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003994CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003995 const StandardConversionSequence& SCS1,
3996 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003997 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003998 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003999 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004000 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004001
4002 // Adjust the types we're converting from via the array-to-pointer
4003 // conversion, if we need to.
4004 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004005 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004007 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004008
4009 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004010 FromType1 = S.Context.getCanonicalType(FromType1);
4011 ToType1 = S.Context.getCanonicalType(ToType1);
4012 FromType2 = S.Context.getCanonicalType(FromType2);
4013 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004014
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004015 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004016 //
4017 // If class B is derived directly or indirectly from class A and
4018 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004019 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004020 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004021 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004022 SCS2.Second == ICK_Pointer_Conversion &&
4023 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4024 FromType1->isPointerType() && FromType2->isPointerType() &&
4025 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004026 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004027 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004028 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004029 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004030 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004031 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004032 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004033 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004034
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004035 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004036 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004037 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004038 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004039 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004040 return ImplicitConversionSequence::Worse;
4041 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004042
4043 // -- conversion of B* to A* is better than conversion of C* to A*,
4044 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004045 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004046 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004047 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004048 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004049 }
4050 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4051 SCS2.Second == ICK_Pointer_Conversion) {
4052 const ObjCObjectPointerType *FromPtr1
4053 = FromType1->getAs<ObjCObjectPointerType>();
4054 const ObjCObjectPointerType *FromPtr2
4055 = FromType2->getAs<ObjCObjectPointerType>();
4056 const ObjCObjectPointerType *ToPtr1
4057 = ToType1->getAs<ObjCObjectPointerType>();
4058 const ObjCObjectPointerType *ToPtr2
4059 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004060
Douglas Gregor058d3de2011-01-31 18:51:41 +00004061 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4062 // Apply the same conversion ranking rules for Objective-C pointer types
4063 // that we do for C++ pointers to class types. However, we employ the
4064 // Objective-C pseudo-subtyping relationship used for assignment of
4065 // Objective-C pointer types.
4066 bool FromAssignLeft
4067 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4068 bool FromAssignRight
4069 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4070 bool ToAssignLeft
4071 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4072 bool ToAssignRight
4073 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004074
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004075 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004076 // type is better than a conversion to 'id'.
4077 if (ToPtr1->isObjCIdType() &&
4078 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4079 return ImplicitConversionSequence::Worse;
4080 if (ToPtr2->isObjCIdType() &&
4081 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4082 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004083
4084 // A conversion to a non-id object pointer type is better than a
4085 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004086 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4087 return ImplicitConversionSequence::Worse;
4088 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4089 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004090
4091 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004092 // type is better than a conversion to 'Class'.
4093 if (ToPtr1->isObjCClassType() &&
4094 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4095 return ImplicitConversionSequence::Worse;
4096 if (ToPtr2->isObjCClassType() &&
4097 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4098 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004099
4100 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004101 // conversion to a qualified 'Class' type.
4102 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4103 return ImplicitConversionSequence::Worse;
4104 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4105 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004106
Douglas Gregor058d3de2011-01-31 18:51:41 +00004107 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004108 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004109 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004110 (ToAssignLeft != ToAssignRight)) {
4111 if (FromPtr1->isSpecialized()) {
4112 // "conversion of B<A> * to B * is better than conversion of B * to
4113 // C *.
4114 bool IsFirstSame =
4115 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4116 bool IsSecondSame =
4117 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4118 if (IsFirstSame) {
4119 if (!IsSecondSame)
4120 return ImplicitConversionSequence::Better;
4121 } else if (IsSecondSame)
4122 return ImplicitConversionSequence::Worse;
4123 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004124 return ToAssignLeft? ImplicitConversionSequence::Worse
4125 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004126 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004127
4128 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4129 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4130 (FromAssignLeft != FromAssignRight))
4131 return FromAssignLeft? ImplicitConversionSequence::Better
4132 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004133 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004134 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004135
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004136 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004137 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4138 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4139 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004141 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004143 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004145 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004147 ToType2->getAs<MemberPointerType>();
4148 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4149 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4150 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4151 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4152 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4153 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4154 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4155 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004156 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004157 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004158 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004159 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004160 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004161 return ImplicitConversionSequence::Better;
4162 }
4163 // conversion of B::* to C::* is better than conversion of A::* to C::*
4164 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004165 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004166 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004167 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004168 return ImplicitConversionSequence::Worse;
4169 }
4170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171
Douglas Gregor5ab11652010-04-17 22:01:05 +00004172 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004173 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004174 // -- binding of an expression of type C to a reference of type
4175 // B& is better than binding an expression of type C to a
4176 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004177 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4178 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004179 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004180 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004181 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004182 return ImplicitConversionSequence::Worse;
4183 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004184
Douglas Gregor2fe98832008-11-03 19:09:14 +00004185 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004186 // -- binding of an expression of type B to a reference of type
4187 // A& is better than binding an expression of type C to a
4188 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004189 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4190 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004191 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004192 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004193 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004194 return ImplicitConversionSequence::Worse;
4195 }
4196 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004197
Douglas Gregor5c407d92008-10-23 00:40:37 +00004198 return ImplicitConversionSequence::Indistinguishable;
4199}
4200
Douglas Gregor45bb4832013-03-26 23:36:30 +00004201/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4202/// C++ class.
4203static bool isTypeValid(QualType T) {
4204 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4205 return !Record->isInvalidDecl();
4206
4207 return true;
4208}
4209
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004210/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4211/// determine whether they are reference-related,
4212/// reference-compatible, reference-compatible with added
4213/// qualification, or incompatible, for use in C++ initialization by
4214/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4215/// type, and the first type (T1) is the pointee type of the reference
4216/// type being initialized.
4217Sema::ReferenceCompareResult
4218Sema::CompareReferenceRelationship(SourceLocation Loc,
4219 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004220 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004221 bool &ObjCConversion,
4222 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004223 assert(!OrigT1->isReferenceType() &&
4224 "T1 must be the pointee type of the reference type");
4225 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4226
4227 QualType T1 = Context.getCanonicalType(OrigT1);
4228 QualType T2 = Context.getCanonicalType(OrigT2);
4229 Qualifiers T1Quals, T2Quals;
4230 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4231 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4232
4233 // C++ [dcl.init.ref]p4:
4234 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4235 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4236 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004237 DerivedToBase = false;
4238 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004239 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004240 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004241 if (UnqualT1 == UnqualT2) {
4242 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004243 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004244 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004245 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004246 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004247 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4248 UnqualT2->isObjCObjectOrInterfaceType() &&
4249 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4250 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004251 else if (UnqualT2->isFunctionType() &&
4252 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4253 // C++1z [dcl.init.ref]p4:
4254 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4255 // function" and T1 is "function"
4256 //
4257 // We extend this to also apply to 'noreturn', so allow any function
4258 // conversion between function types.
4259 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004260 else
4261 return Ref_Incompatible;
4262
4263 // At this point, we know that T1 and T2 are reference-related (at
4264 // least).
4265
4266 // If the type is an array type, promote the element qualifiers to the type
4267 // for comparison.
4268 if (isa<ArrayType>(T1) && T1Quals)
4269 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4270 if (isa<ArrayType>(T2) && T2Quals)
4271 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4272
4273 // C++ [dcl.init.ref]p4:
4274 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4275 // reference-related to T2 and cv1 is the same cv-qualification
4276 // as, or greater cv-qualification than, cv2. For purposes of
4277 // overload resolution, cases for which cv1 is greater
4278 // cv-qualification than cv2 are identified as
4279 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004280 //
4281 // Note that we also require equivalence of Objective-C GC and address-space
4282 // qualifiers when performing these computations, so that e.g., an int in
4283 // address space 1 is not reference-compatible with an int in address
4284 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004285 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4286 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004287 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4288 ObjCLifetimeConversion = true;
4289
John McCall31168b02011-06-15 23:02:42 +00004290 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004291 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004292 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004293
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004294 // MS compiler ignores __unaligned qualifier for references; do the same.
4295 T1Quals.removeUnaligned();
4296 T2Quals.removeUnaligned();
4297
Richard Smithce766292016-10-21 23:01:55 +00004298 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004299 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 else
4301 return Ref_Related;
4302}
4303
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004304/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004305/// with DeclType. Return true if something definite is found.
4306static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004307FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4308 QualType DeclType, SourceLocation DeclLoc,
4309 Expr *Init, QualType T2, bool AllowRvalues,
4310 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004311 assert(T2->isRecordType() && "Can only find conversions of record types.");
4312 CXXRecordDecl *T2RecordDecl
4313 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4314
Richard Smith67ef14f2017-09-26 18:37:55 +00004315 OverloadCandidateSet CandidateSet(
4316 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004317 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4318 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004319 NamedDecl *D = *I;
4320 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4321 if (isa<UsingShadowDecl>(D))
4322 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4323
4324 FunctionTemplateDecl *ConvTemplate
4325 = dyn_cast<FunctionTemplateDecl>(D);
4326 CXXConversionDecl *Conv;
4327 if (ConvTemplate)
4328 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4329 else
4330 Conv = cast<CXXConversionDecl>(D);
4331
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004333 // explicit conversions, skip it.
4334 if (!AllowExplicit && Conv->isExplicit())
4335 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336
Douglas Gregor836a7e82010-08-11 02:15:33 +00004337 if (AllowRvalues) {
4338 bool DerivedToBase = false;
4339 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004340 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004341
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004342 // If we are initializing an rvalue reference, don't permit conversion
4343 // functions that return lvalues.
4344 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4345 const ReferenceType *RefType
4346 = Conv->getConversionType()->getAs<LValueReferenceType>();
4347 if (RefType && !RefType->getPointeeType()->isFunctionType())
4348 continue;
4349 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004350
Douglas Gregor836a7e82010-08-11 02:15:33 +00004351 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004352 S.CompareReferenceRelationship(
4353 DeclLoc,
4354 Conv->getConversionType().getNonReferenceType()
4355 .getUnqualifiedType(),
4356 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004357 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004358 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004359 continue;
4360 } else {
4361 // If the conversion function doesn't return a reference type,
4362 // it can't be considered for this conversion. An rvalue reference
4363 // is only acceptable if its referencee is a function type.
4364
4365 const ReferenceType *RefType =
4366 Conv->getConversionType()->getAs<ReferenceType>();
4367 if (!RefType ||
4368 (!RefType->isLValueReferenceType() &&
4369 !RefType->getPointeeType()->isFunctionType()))
4370 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
Douglas Gregor836a7e82010-08-11 02:15:33 +00004373 if (ConvTemplate)
4374 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004375 Init, DeclType, CandidateSet,
4376 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004377 else
4378 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004379 DeclType, CandidateSet,
4380 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004381 }
4382
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004383 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4384
Sebastian Redld92badf2010-06-30 18:13:39 +00004385 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004386 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004387 case OR_Success:
4388 // C++ [over.ics.ref]p1:
4389 //
4390 // [...] If the parameter binds directly to the result of
4391 // applying a conversion function to the argument
4392 // expression, the implicit conversion sequence is a
4393 // user-defined conversion sequence (13.3.3.1.2), with the
4394 // second standard conversion sequence either an identity
4395 // conversion or, if the conversion function returns an
4396 // entity of a type that is a derived class of the parameter
4397 // type, a derived-to-base Conversion.
4398 if (!Best->FinalConversion.DirectBinding)
4399 return false;
4400
4401 ICS.setUserDefined();
4402 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4403 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004404 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004405 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004406 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004407 ICS.UserDefined.EllipsisConversion = false;
4408 assert(ICS.UserDefined.After.ReferenceBinding &&
4409 ICS.UserDefined.After.DirectBinding &&
4410 "Expected a direct reference binding!");
4411 return true;
4412
4413 case OR_Ambiguous:
4414 ICS.setAmbiguous();
4415 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4416 Cand != CandidateSet.end(); ++Cand)
4417 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004418 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004419 return true;
4420
4421 case OR_No_Viable_Function:
4422 case OR_Deleted:
4423 // There was no suitable conversion, or we found a deleted
4424 // conversion; continue with other checks.
4425 return false;
4426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
David Blaikie8a40f702012-01-17 06:56:22 +00004428 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004429}
4430
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004431/// \brief Compute an implicit conversion sequence for reference
4432/// initialization.
4433static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004434TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004435 SourceLocation DeclLoc,
4436 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004437 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004438 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4439
4440 // Most paths end in a failed conversion.
4441 ImplicitConversionSequence ICS;
4442 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4443
4444 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4445 QualType T2 = Init->getType();
4446
4447 // If the initializer is the address of an overloaded function, try
4448 // to resolve the overloaded function. If all goes well, T2 is the
4449 // type of the resulting function.
4450 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4451 DeclAccessPair Found;
4452 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4453 false, Found))
4454 T2 = Fn->getType();
4455 }
4456
4457 // Compute some basic properties of the types and the initializer.
4458 bool isRValRef = DeclType->isRValueReferenceType();
4459 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004460 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004461 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004462 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004464 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004465 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004466
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467
Sebastian Redld92badf2010-06-30 18:13:39 +00004468 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004469 // A reference to type "cv1 T1" is initialized by an expression
4470 // of type "cv2 T2" as follows:
4471
Sebastian Redld92badf2010-06-30 18:13:39 +00004472 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004473 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004474 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4475 // reference-compatible with "cv2 T2," or
4476 //
4477 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004478 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004479 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004480 // When a parameter of reference type binds directly (8.5.3)
4481 // to an argument expression, the implicit conversion sequence
4482 // is the identity conversion, unless the argument expression
4483 // has a type that is a derived class of the parameter type,
4484 // in which case the implicit conversion sequence is a
4485 // derived-to-base Conversion (13.3.3.1).
4486 ICS.setStandard();
4487 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004488 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4489 : ObjCConversion? ICK_Compatible_Conversion
4490 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004491 ICS.Standard.Third = ICK_Identity;
4492 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4493 ICS.Standard.setToType(0, T2);
4494 ICS.Standard.setToType(1, T1);
4495 ICS.Standard.setToType(2, T1);
4496 ICS.Standard.ReferenceBinding = true;
4497 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004498 ICS.Standard.IsLvalueReference = !isRValRef;
4499 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4500 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004501 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004502 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004503 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004504 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004505
Sebastian Redld92badf2010-06-30 18:13:39 +00004506 // Nothing more to do: the inaccessibility/ambiguity check for
4507 // derived-to-base conversions is suppressed when we're
4508 // computing the implicit conversion sequence (C++
4509 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004510 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004511 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004512
Sebastian Redld92badf2010-06-30 18:13:39 +00004513 // -- has a class type (i.e., T2 is a class type), where T1 is
4514 // not reference-related to T2, and can be implicitly
4515 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4516 // is reference-compatible with "cv3 T3" 92) (this
4517 // conversion is selected by enumerating the applicable
4518 // conversion functions (13.3.1.6) and choosing the best
4519 // one through overload resolution (13.3)),
4520 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004521 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004522 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004523 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4524 Init, T2, /*AllowRvalues=*/false,
4525 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004526 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004527 }
4528 }
4529
Sebastian Redld92badf2010-06-30 18:13:39 +00004530 // -- Otherwise, the reference shall be an lvalue reference to a
4531 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004532 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004533 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004534 return ICS;
4535
Douglas Gregorf143cd52011-01-24 16:14:37 +00004536 // -- If the initializer expression
4537 //
4538 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004539 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004540 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004541 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004542 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4543 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004544 ICS.setStandard();
4545 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004547 : ObjCConversion? ICK_Compatible_Conversion
4548 : ICK_Identity;
4549 ICS.Standard.Third = ICK_Identity;
4550 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4551 ICS.Standard.setToType(0, T2);
4552 ICS.Standard.setToType(1, T1);
4553 ICS.Standard.setToType(2, T1);
4554 ICS.Standard.ReferenceBinding = true;
4555 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4556 // binding unless we're binding to a class prvalue.
4557 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4558 // allow the use of rvalue references in C++98/03 for the benefit of
4559 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004561 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004562 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004563 ICS.Standard.IsLvalueReference = !isRValRef;
4564 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004566 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004567 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004568 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004569 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregorf143cd52011-01-24 16:14:37 +00004573 // -- has a class type (i.e., T2 is a class type), where T1 is not
4574 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 // an xvalue, class prvalue, or function lvalue of type
4576 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004577 // "cv3 T3",
4578 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004580 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004582 // class subobject).
4583 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004584 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004585 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4586 Init, T2, /*AllowRvalues=*/true,
4587 AllowExplicit)) {
4588 // In the second case, if the reference is an rvalue reference
4589 // and the second standard conversion sequence of the
4590 // user-defined conversion sequence includes an lvalue-to-rvalue
4591 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004593 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4594 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4595
Douglas Gregor95273c32011-01-21 16:36:05 +00004596 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598
Richard Smith19172c42014-07-14 02:28:44 +00004599 // A temporary of function type cannot be created; don't even try.
4600 if (T1->isFunctionType())
4601 return ICS;
4602
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004603 // -- Otherwise, a temporary of type "cv1 T1" is created and
4604 // initialized from the initializer expression using the
4605 // rules for a non-reference copy initialization (8.5). The
4606 // reference is then bound to the temporary. If T1 is
4607 // reference-related to T2, cv1 must be the same
4608 // cv-qualification as, or greater cv-qualification than,
4609 // cv2; otherwise, the program is ill-formed.
4610 if (RefRelationship == Sema::Ref_Related) {
4611 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4612 // we would be reference-compatible or reference-compatible with
4613 // added qualification. But that wasn't the case, so the reference
4614 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004615 //
4616 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004617 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004618 Qualifiers T1Quals = T1.getQualifiers();
4619 Qualifiers T2Quals = T2.getQualifiers();
4620 T1Quals.removeObjCGCAttr();
4621 T1Quals.removeObjCLifetime();
4622 T2Quals.removeObjCGCAttr();
4623 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004624 // MS compiler ignores __unaligned qualifier for references; do the same.
4625 T1Quals.removeUnaligned();
4626 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004627 if (!T1Quals.compatiblyIncludes(T2Quals))
4628 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004629 }
4630
4631 // If at least one of the types is a class type, the types are not
4632 // related, and we aren't allowed any user conversions, the
4633 // reference binding fails. This case is important for breaking
4634 // recursion, since TryImplicitConversion below will attempt to
4635 // create a temporary through the use of a copy constructor.
4636 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4637 (T1->isRecordType() || T2->isRecordType()))
4638 return ICS;
4639
Douglas Gregorcba72b12011-01-21 05:18:22 +00004640 // If T1 is reference-related to T2 and the reference is an rvalue
4641 // reference, the initializer expression shall not be an lvalue.
4642 if (RefRelationship >= Sema::Ref_Related &&
4643 isRValRef && Init->Classify(S.Context).isLValue())
4644 return ICS;
4645
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004646 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004647 // When a parameter of reference type is not bound directly to
4648 // an argument expression, the conversion sequence is the one
4649 // required to convert the argument expression to the
4650 // underlying type of the reference according to
4651 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4652 // to copy-initializing a temporary of the underlying type with
4653 // the argument expression. Any difference in top-level
4654 // cv-qualification is subsumed by the initialization itself
4655 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004656 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4657 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004658 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004659 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004660 /*AllowObjCWritebackConversion=*/false,
4661 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004662
4663 // Of course, that's still a reference binding.
4664 if (ICS.isStandard()) {
4665 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004666 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004667 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004668 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004669 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004670 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004671 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004672 const ReferenceType *LValRefType =
4673 ICS.UserDefined.ConversionFunction->getReturnType()
4674 ->getAs<LValueReferenceType>();
4675
4676 // C++ [over.ics.ref]p3:
4677 // Except for an implicit object parameter, for which see 13.3.1, a
4678 // standard conversion sequence cannot be formed if it requires [...]
4679 // binding an rvalue reference to an lvalue other than a function
4680 // lvalue.
4681 // Note that the function case is not possible here.
4682 if (DeclType->isRValueReferenceType() && LValRefType) {
4683 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4684 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4685 // reference to an rvalue!
4686 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4687 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004688 }
Richard Smith19172c42014-07-14 02:28:44 +00004689
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004690 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004691 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004692 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4693 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004694 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4695 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004696 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004697
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004698 return ICS;
4699}
4700
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004701static ImplicitConversionSequence
4702TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4703 bool SuppressUserConversions,
4704 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004705 bool AllowObjCWritebackConversion,
4706 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004707
4708/// TryListConversion - Try to copy-initialize a value of type ToType from the
4709/// initializer list From.
4710static ImplicitConversionSequence
4711TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4712 bool SuppressUserConversions,
4713 bool InOverloadResolution,
4714 bool AllowObjCWritebackConversion) {
4715 // C++11 [over.ics.list]p1:
4716 // When an argument is an initializer list, it is not an expression and
4717 // special rules apply for converting it to a parameter type.
4718
4719 ImplicitConversionSequence Result;
4720 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4721
Sebastian Redl09edce02012-01-23 22:09:39 +00004722 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004723 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004724 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004725 return Result;
4726
Larisse Voufo19d08672015-01-27 18:47:05 +00004727 // Per DR1467:
4728 // If the parameter type is a class X and the initializer list has a single
4729 // element of type cv U, where U is X or a class derived from X, the
4730 // implicit conversion sequence is the one required to convert the element
4731 // to the parameter type.
4732 //
4733 // Otherwise, if the parameter type is a character array [... ]
4734 // and the initializer list has a single element that is an
4735 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4736 // implicit conversion sequence is the identity conversion.
4737 if (From->getNumInits() == 1) {
4738 if (ToType->isRecordType()) {
4739 QualType InitType = From->getInit(0)->getType();
4740 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004741 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004742 return TryCopyInitialization(S, From->getInit(0), ToType,
4743 SuppressUserConversions,
4744 InOverloadResolution,
4745 AllowObjCWritebackConversion);
4746 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004747 // FIXME: Check the other conditions here: array of character type,
4748 // initializer is a string literal.
4749 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004750 InitializedEntity Entity =
4751 InitializedEntity::InitializeParameter(S.Context, ToType,
4752 /*Consumed=*/false);
4753 if (S.CanPerformCopyInitialization(Entity, From)) {
4754 Result.setStandard();
4755 Result.Standard.setAsIdentityConversion();
4756 Result.Standard.setFromType(ToType);
4757 Result.Standard.setAllToTypes(ToType);
4758 return Result;
4759 }
4760 }
4761 }
4762
4763 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004764 // C++11 [over.ics.list]p2:
4765 // If the parameter type is std::initializer_list<X> or "array of X" and
4766 // all the elements can be implicitly converted to X, the implicit
4767 // conversion sequence is the worst conversion necessary to convert an
4768 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004769 //
4770 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004771 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004772 // list has exactly N elements or if it has fewer than N elements and X is
4773 // default-constructible, and if all the elements of the initializer list
4774 // can be implicitly converted to X, the implicit conversion sequence is
4775 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004776 //
4777 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004778 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004779 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004780 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004781 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004782 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004783 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004784 if (!X.isNull()) {
4785 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4786 Expr *Init = From->getInit(i);
4787 ImplicitConversionSequence ICS =
4788 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4789 InOverloadResolution,
4790 AllowObjCWritebackConversion);
4791 // If a single element isn't convertible, fail.
4792 if (ICS.isBad()) {
4793 Result = ICS;
4794 break;
4795 }
4796 // Otherwise, look for the worst conversion.
4797 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004798 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4799 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004800 ImplicitConversionSequence::Worse)
4801 Result = ICS;
4802 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004803
4804 // For an empty list, we won't have computed any conversion sequence.
4805 // Introduce the identity conversion sequence.
4806 if (From->getNumInits() == 0) {
4807 Result.setStandard();
4808 Result.Standard.setAsIdentityConversion();
4809 Result.Standard.setFromType(ToType);
4810 Result.Standard.setAllToTypes(ToType);
4811 }
4812
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004813 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004814 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004815 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004816
Larisse Voufo19d08672015-01-27 18:47:05 +00004817 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004818 // C++11 [over.ics.list]p3:
4819 // Otherwise, if the parameter is a non-aggregate class X and overload
4820 // resolution chooses a single best constructor [...] the implicit
4821 // conversion sequence is a user-defined conversion sequence. If multiple
4822 // constructors are viable but none is better than the others, the
4823 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004824 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4825 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004826 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4827 /*AllowExplicit=*/false,
4828 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004829 AllowObjCWritebackConversion,
4830 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004831 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004832
Larisse Voufo19d08672015-01-27 18:47:05 +00004833 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004834 // C++11 [over.ics.list]p4:
4835 // Otherwise, if the parameter has an aggregate type which can be
4836 // initialized from the initializer list [...] the implicit conversion
4837 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004838 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004839 // Type is an aggregate, argument is an init list. At this point it comes
4840 // down to checking whether the initialization works.
4841 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004842 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4843 // need to call into the initialization code here; overload resolution
4844 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004845 InitializedEntity Entity =
4846 InitializedEntity::InitializeParameter(S.Context, ToType,
4847 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004848 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004849 Result.setUserDefined();
4850 Result.UserDefined.Before.setAsIdentityConversion();
4851 // Initializer lists don't have a type.
4852 Result.UserDefined.Before.setFromType(QualType());
4853 Result.UserDefined.Before.setAllToTypes(QualType());
4854
4855 Result.UserDefined.After.setAsIdentityConversion();
4856 Result.UserDefined.After.setFromType(ToType);
4857 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004858 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004859 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004860 return Result;
4861 }
4862
Larisse Voufo19d08672015-01-27 18:47:05 +00004863 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004864 // C++11 [over.ics.list]p5:
4865 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004866 if (ToType->isReferenceType()) {
4867 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4868 // mention initializer lists in any way. So we go by what list-
4869 // initialization would do and try to extrapolate from that.
4870
4871 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4872
4873 // If the initializer list has a single element that is reference-related
4874 // to the parameter type, we initialize the reference from that.
4875 if (From->getNumInits() == 1) {
4876 Expr *Init = From->getInit(0);
4877
4878 QualType T2 = Init->getType();
4879
4880 // If the initializer is the address of an overloaded function, try
4881 // to resolve the overloaded function. If all goes well, T2 is the
4882 // type of the resulting function.
4883 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4884 DeclAccessPair Found;
4885 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4886 Init, ToType, false, Found))
4887 T2 = Fn->getType();
4888 }
4889
4890 // Compute some basic properties of the types and the initializer.
4891 bool dummy1 = false;
4892 bool dummy2 = false;
4893 bool dummy3 = false;
4894 Sema::ReferenceCompareResult RefRelationship
4895 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4896 dummy2, dummy3);
4897
Richard Smith4d2bbd72013-09-06 01:22:42 +00004898 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004899 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4900 SuppressUserConversions,
4901 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004902 }
Sebastian Redldf888642011-12-03 14:54:30 +00004903 }
4904
4905 // Otherwise, we bind the reference to a temporary created from the
4906 // initializer list.
4907 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4908 InOverloadResolution,
4909 AllowObjCWritebackConversion);
4910 if (Result.isFailure())
4911 return Result;
4912 assert(!Result.isEllipsis() &&
4913 "Sub-initialization cannot result in ellipsis conversion.");
4914
4915 // Can we even bind to a temporary?
4916 if (ToType->isRValueReferenceType() ||
4917 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4918 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4919 Result.UserDefined.After;
4920 SCS.ReferenceBinding = true;
4921 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4922 SCS.BindsToRvalue = true;
4923 SCS.BindsToFunctionLvalue = false;
4924 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4925 SCS.ObjCLifetimeConversionBinding = false;
4926 } else
4927 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4928 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004929 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004930 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004931
Larisse Voufo19d08672015-01-27 18:47:05 +00004932 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004933 // C++11 [over.ics.list]p6:
4934 // Otherwise, if the parameter type is not a class:
4935 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004936 // - if the initializer list has one element that is not itself an
4937 // initializer list, the implicit conversion sequence is the one
4938 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004939 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004940 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004941 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4942 SuppressUserConversions,
4943 InOverloadResolution,
4944 AllowObjCWritebackConversion);
4945 // - if the initializer list has no elements, the implicit conversion
4946 // sequence is the identity conversion.
4947 else if (NumInits == 0) {
4948 Result.setStandard();
4949 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004950 Result.Standard.setFromType(ToType);
4951 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004952 }
4953 return Result;
4954 }
4955
Larisse Voufo19d08672015-01-27 18:47:05 +00004956 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004957 // C++11 [over.ics.list]p7:
4958 // In all cases other than those enumerated above, no conversion is possible
4959 return Result;
4960}
4961
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004962/// TryCopyInitialization - Try to copy-initialize a value of type
4963/// ToType from the expression From. Return the implicit conversion
4964/// sequence required to pass this argument, which may be a bad
4965/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004966/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004967/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004968static ImplicitConversionSequence
4969TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004971 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004972 bool AllowObjCWritebackConversion,
4973 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004974 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4975 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4976 InOverloadResolution,AllowObjCWritebackConversion);
4977
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004978 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004979 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004980 /*FIXME:*/From->getLocStart(),
4981 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004982 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004983
John McCall5c32be02010-08-24 20:38:10 +00004984 return TryImplicitConversion(S, From, ToType,
4985 SuppressUserConversions,
4986 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004987 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004988 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004989 AllowObjCWritebackConversion,
4990 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004991}
4992
Anna Zaks1b068122011-07-28 19:46:48 +00004993static bool TryCopyInitialization(const CanQualType FromQTy,
4994 const CanQualType ToQTy,
4995 Sema &S,
4996 SourceLocation Loc,
4997 ExprValueKind FromVK) {
4998 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4999 ImplicitConversionSequence ICS =
5000 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5001
5002 return !ICS.isBad();
5003}
5004
Douglas Gregor436424c2008-11-18 23:14:02 +00005005/// TryObjectArgumentInitialization - Try to initialize the object
5006/// parameter of the given member function (@c Method) from the
5007/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005008static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005009TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005010 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005011 CXXMethodDecl *Method,
5012 CXXRecordDecl *ActingContext) {
5013 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005014 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5015 // const volatile object.
5016 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5017 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005018 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005019
5020 // Set up the conversion sequence as a "bad" conversion, to allow us
5021 // to exit early.
5022 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005023
5024 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005025 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005026 FromType = PT->getPointeeType();
5027
Douglas Gregor02824322011-01-26 19:30:28 +00005028 // When we had a pointer, it's implicitly dereferenced, so we
5029 // better have an lvalue.
5030 assert(FromClassification.isLValue());
5031 }
5032
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005033 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005034
Douglas Gregor02824322011-01-26 19:30:28 +00005035 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005037 // parameter is
5038 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005039 // - "lvalue reference to cv X" for functions declared without a
5040 // ref-qualifier or with the & ref-qualifier
5041 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005042 // ref-qualifier
5043 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005045 // cv-qualification on the member function declaration.
5046 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005048 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005049 // (C++ [over.match.funcs]p5). We perform a simplified version of
5050 // reference binding here, that allows class rvalues to bind to
5051 // non-constant references.
5052
Douglas Gregor02824322011-01-26 19:30:28 +00005053 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005054 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005056 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005057 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005058 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005059 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005060 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005061 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005062
5063 // Check that we have either the same type or a derived type. It
5064 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005065 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005066 ImplicitConversionKind SecondKind;
5067 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5068 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005069 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005070 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005071 else {
John McCall65eb8792010-02-25 01:37:24 +00005072 ICS.setBad(BadConversionSequence::unrelated_class,
5073 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005074 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005075 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005076
Douglas Gregor02824322011-01-26 19:30:28 +00005077 // Check the ref-qualifier.
5078 switch (Method->getRefQualifier()) {
5079 case RQ_None:
5080 // Do nothing; we don't care about lvalueness or rvalueness.
5081 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082
Douglas Gregor02824322011-01-26 19:30:28 +00005083 case RQ_LValue:
5084 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5085 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005087 ImplicitParamType);
5088 return ICS;
5089 }
5090 break;
5091
5092 case RQ_RValue:
5093 if (!FromClassification.isRValue()) {
5094 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005096 ImplicitParamType);
5097 return ICS;
5098 }
5099 break;
5100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregor436424c2008-11-18 23:14:02 +00005102 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005103 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005104 ICS.Standard.setAsIdentityConversion();
5105 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005106 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005107 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005108 ICS.Standard.ReferenceBinding = true;
5109 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005111 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005112 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5113 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5114 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005115 return ICS;
5116}
5117
5118/// PerformObjectArgumentInitialization - Perform initialization of
5119/// the implicit object parameter for the given Method with the given
5120/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005121ExprResult
5122Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005124 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005125 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005126 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005127 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005128 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005129
Douglas Gregor02824322011-01-26 19:30:28 +00005130 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005131 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005132 FromRecordType = PT->getPointeeType();
5133 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005134 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005135 } else {
5136 FromRecordType = From->getType();
5137 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005138 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005139 }
5140
John McCall6e9f8f62009-12-03 04:06:58 +00005141 // Note that we always use the true parent context when performing
5142 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005143 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005144 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5145 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005146 if (ICS.isBad()) {
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005147 switch (ICS.Bad.Kind) {
5148 case BadConversionSequence::bad_qualifiers: {
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005149 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 }
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005161 break;
5162 }
5163
5164 case BadConversionSequence::lvalue_ref_to_rvalue:
5165 case BadConversionSequence::rvalue_ref_to_lvalue: {
5166 bool IsRValueQualified =
5167 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5168 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5169 << Method->getDeclName() << FromClassification.isRValue()
5170 << IsRValueQualified;
5171 Diag(Method->getLocation(), diag::note_previous_decl)
5172 << Method->getDeclName();
5173 return ExprError();
5174 }
5175
5176 case BadConversionSequence::no_conversion:
5177 case BadConversionSequence::unrelated_class:
5178 break;
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005179 }
5180
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005181 return Diag(From->getLocStart(),
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005182 diag::err_member_function_call_bad_type)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005183 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005184 }
Mike Stump11289f42009-09-09 15:08:12 +00005185
John Wiegley01296292011-04-08 18:41:53 +00005186 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5187 ExprResult FromRes =
5188 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5189 if (FromRes.isInvalid())
5190 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005191 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005192 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005193
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005194 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005195 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005196 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005197 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005198}
5199
Douglas Gregor5fb53972009-01-14 15:45:31 +00005200/// TryContextuallyConvertToBool - Attempt to contextually convert the
5201/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005202static ImplicitConversionSequence
5203TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005204 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005205 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005206 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005207 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005208 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005209 /*AllowObjCWritebackConversion=*/false,
5210 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005211}
5212
5213/// PerformContextuallyConvertToBool - Perform a contextual conversion
5214/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005215ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005216 if (checkPlaceholderForOverload(*this, From))
5217 return ExprError();
5218
John McCall5c32be02010-08-24 20:38:10 +00005219 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005220 if (!ICS.isBad())
5221 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222
Fariborz Jahanian76197412009-11-18 18:26:29 +00005223 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005224 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005225 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005226 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005227 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005228}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005229
Richard Smithf8379a02012-01-18 23:55:52 +00005230/// Check that the specified conversion is permitted in a converted constant
5231/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5232/// is acceptable.
5233static bool CheckConvertedConstantConversions(Sema &S,
5234 StandardConversionSequence &SCS) {
5235 // Since we know that the target type is an integral or unscoped enumeration
5236 // type, most conversion kinds are impossible. All possible First and Third
5237 // conversions are fine.
5238 switch (SCS.Second) {
5239 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005240 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005241 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005242 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005243 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005244 return true;
5245
5246 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005247 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005248 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5249 // conversion, so we allow it in a converted constant expression.
5250 //
5251 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5252 // a lot of popular code. We should at least add a warning for this
5253 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005254 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5255 SCS.getToType(2)->isBooleanType();
5256
Richard Smith410cc892014-11-26 03:26:53 +00005257 case ICK_Pointer_Conversion:
5258 case ICK_Pointer_Member:
5259 // C++1z: null pointer conversions and null member pointer conversions are
5260 // only permitted if the source type is std::nullptr_t.
5261 return SCS.getFromType()->isNullPtrType();
5262
5263 case ICK_Floating_Promotion:
5264 case ICK_Complex_Promotion:
5265 case ICK_Floating_Conversion:
5266 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005267 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005268 case ICK_Compatible_Conversion:
5269 case ICK_Derived_To_Base:
5270 case ICK_Vector_Conversion:
5271 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005272 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005273 case ICK_Block_Pointer_Conversion:
5274 case ICK_TransparentUnionConversion:
5275 case ICK_Writeback_Conversion:
5276 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005277 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005278 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005279 return false;
5280
5281 case ICK_Lvalue_To_Rvalue:
5282 case ICK_Array_To_Pointer:
5283 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005284 llvm_unreachable("found a first conversion kind in Second");
5285
Richard Smithf8379a02012-01-18 23:55:52 +00005286 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005287 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005288
5289 case ICK_Num_Conversion_Kinds:
5290 break;
5291 }
5292
5293 llvm_unreachable("unknown conversion kind");
5294}
5295
5296/// CheckConvertedConstantExpression - Check that the expression From is a
5297/// converted constant expression of type T, perform the conversion and produce
5298/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005299static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5300 QualType T, APValue &Value,
5301 Sema::CCEKind CCE,
5302 bool RequireInt) {
5303 assert(S.getLangOpts().CPlusPlus11 &&
5304 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005305
Richard Smith410cc892014-11-26 03:26:53 +00005306 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005307 return ExprError();
5308
Richard Smith410cc892014-11-26 03:26:53 +00005309 // C++1z [expr.const]p3:
5310 // A converted constant expression of type T is an expression,
5311 // implicitly converted to type T, where the converted
5312 // expression is a constant expression and the implicit conversion
5313 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005314 // C++1z [stmt.if]p2:
5315 // If the if statement is of the form if constexpr, the value of the
5316 // condition shall be a contextually converted constant expression of type
5317 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005318 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005319 CCE == Sema::CCEK_ConstexprIf
5320 ? TryContextuallyConvertToBool(S, From)
5321 : TryCopyInitialization(S, From, T,
5322 /*SuppressUserConversions=*/false,
5323 /*InOverloadResolution=*/false,
5324 /*AllowObjcWritebackConversion=*/false,
5325 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005326 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005327 switch (ICS.getKind()) {
5328 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005329 SCS = &ICS.Standard;
5330 break;
5331 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005332 // We are converting to a non-class type, so the Before sequence
5333 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005334 SCS = &ICS.UserDefined.After;
5335 break;
5336 case ImplicitConversionSequence::AmbiguousConversion:
5337 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005338 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5339 return S.Diag(From->getLocStart(),
5340 diag::err_typecheck_converted_constant_expression)
5341 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005342 return ExprError();
5343
5344 case ImplicitConversionSequence::EllipsisConversion:
5345 llvm_unreachable("ellipsis conversion in converted constant expression");
5346 }
5347
Richard Smith410cc892014-11-26 03:26:53 +00005348 // Check that we would only use permitted conversions.
5349 if (!CheckConvertedConstantConversions(S, *SCS)) {
5350 return S.Diag(From->getLocStart(),
5351 diag::err_typecheck_converted_constant_expression_disallowed)
5352 << From->getType() << From->getSourceRange() << T;
5353 }
5354 // [...] and where the reference binding (if any) binds directly.
5355 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5356 return S.Diag(From->getLocStart(),
5357 diag::err_typecheck_converted_constant_expression_indirect)
5358 << From->getType() << From->getSourceRange() << T;
5359 }
5360
5361 ExprResult Result =
5362 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005363 if (Result.isInvalid())
5364 return Result;
5365
5366 // Check for a narrowing implicit conversion.
5367 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005368 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005369 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005370 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005371 case NK_Dependent_Narrowing:
5372 // Implicit conversion to a narrower type, but the expression is
5373 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005374 case NK_Variable_Narrowing:
5375 // Implicit conversion to a narrower type, and the value is not a constant
5376 // expression. We'll diagnose this in a moment.
5377 case NK_Not_Narrowing:
5378 break;
5379
5380 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005381 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005382 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005383 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005384 break;
5385
5386 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005387 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005388 << CCE << /*Constant*/0 << From->getType() << T;
5389 break;
5390 }
5391
Richard Smith52e624f2016-12-21 21:42:57 +00005392 if (Result.get()->isValueDependent()) {
5393 Value = APValue();
5394 return Result;
5395 }
5396
Richard Smithf8379a02012-01-18 23:55:52 +00005397 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005398 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005399 Expr::EvalResult Eval;
5400 Eval.Diag = &Notes;
5401
Richard Smith410cc892014-11-26 03:26:53 +00005402 if ((T->isReferenceType()
5403 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5404 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5405 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005406 // The expression can't be folded, so we can't keep it at this position in
5407 // the AST.
5408 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005409 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005410 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005411
5412 if (Notes.empty()) {
5413 // It's a constant expression.
5414 return Result;
5415 }
Richard Smithf8379a02012-01-18 23:55:52 +00005416 }
5417
5418 // It's not a constant expression. Produce an appropriate diagnostic.
5419 if (Notes.size() == 1 &&
5420 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005421 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005422 else {
Richard Smith410cc892014-11-26 03:26:53 +00005423 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005424 << CCE << From->getSourceRange();
5425 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005426 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005427 }
Richard Smith410cc892014-11-26 03:26:53 +00005428 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005429}
5430
Richard Smith410cc892014-11-26 03:26:53 +00005431ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5432 APValue &Value, CCEKind CCE) {
5433 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5434}
5435
5436ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5437 llvm::APSInt &Value,
5438 CCEKind CCE) {
5439 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5440
5441 APValue V;
5442 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005443 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005444 Value = V.getInt();
5445 return R;
5446}
5447
5448
John McCallfec112d2011-09-09 06:11:02 +00005449/// dropPointerConversions - If the given standard conversion sequence
5450/// involves any pointer conversions, remove them. This may change
5451/// the result type of the conversion sequence.
5452static void dropPointerConversion(StandardConversionSequence &SCS) {
5453 if (SCS.Second == ICK_Pointer_Conversion) {
5454 SCS.Second = ICK_Identity;
5455 SCS.Third = ICK_Identity;
5456 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5457 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005458}
John McCall5c32be02010-08-24 20:38:10 +00005459
John McCallfec112d2011-09-09 06:11:02 +00005460/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5461/// convert the expression From to an Objective-C pointer type.
5462static ImplicitConversionSequence
5463TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5464 // Do an implicit conversion to 'id'.
5465 QualType Ty = S.Context.getObjCIdType();
5466 ImplicitConversionSequence ICS
5467 = TryImplicitConversion(S, From, Ty,
5468 // FIXME: Are these flags correct?
5469 /*SuppressUserConversions=*/false,
5470 /*AllowExplicit=*/true,
5471 /*InOverloadResolution=*/false,
5472 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005473 /*AllowObjCWritebackConversion=*/false,
5474 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005475
5476 // Strip off any final conversions to 'id'.
5477 switch (ICS.getKind()) {
5478 case ImplicitConversionSequence::BadConversion:
5479 case ImplicitConversionSequence::AmbiguousConversion:
5480 case ImplicitConversionSequence::EllipsisConversion:
5481 break;
5482
5483 case ImplicitConversionSequence::UserDefinedConversion:
5484 dropPointerConversion(ICS.UserDefined.After);
5485 break;
5486
5487 case ImplicitConversionSequence::StandardConversion:
5488 dropPointerConversion(ICS.Standard);
5489 break;
5490 }
5491
5492 return ICS;
5493}
5494
5495/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5496/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005497/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005498ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005499 if (checkPlaceholderForOverload(*this, From))
5500 return ExprError();
5501
John McCall8b07ec22010-05-15 11:32:37 +00005502 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005503 ImplicitConversionSequence ICS =
5504 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005505 if (!ICS.isBad())
5506 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005507 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005508}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005509
Richard Smith8dd34252012-02-04 07:07:42 +00005510/// Determine whether the provided type is an integral type, or an enumeration
5511/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005512bool Sema::ICEConvertDiagnoser::match(QualType T) {
5513 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5514 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005515}
5516
Larisse Voufo236bec22013-06-10 06:50:24 +00005517static ExprResult
5518diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5519 Sema::ContextualImplicitConverter &Converter,
5520 QualType T, UnresolvedSetImpl &ViableConversions) {
5521
5522 if (Converter.Suppress)
5523 return ExprError();
5524
5525 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5526 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5527 CXXConversionDecl *Conv =
5528 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5529 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5530 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5531 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005532 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005533}
5534
5535static bool
5536diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5537 Sema::ContextualImplicitConverter &Converter,
5538 QualType T, bool HadMultipleCandidates,
5539 UnresolvedSetImpl &ExplicitConversions) {
5540 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5541 DeclAccessPair Found = ExplicitConversions[0];
5542 CXXConversionDecl *Conversion =
5543 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5544
5545 // The user probably meant to invoke the given explicit
5546 // conversion; use it.
5547 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5548 std::string TypeStr;
5549 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5550
5551 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5552 << FixItHint::CreateInsertion(From->getLocStart(),
5553 "static_cast<" + TypeStr + ">(")
5554 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005555 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005556 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5557
5558 // If we aren't in a SFINAE context, build a call to the
5559 // explicit conversion function.
5560 if (SemaRef.isSFINAEContext())
5561 return true;
5562
Craig Topperc3ec1492014-05-26 06:22:03 +00005563 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005564 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5565 HadMultipleCandidates);
5566 if (Result.isInvalid())
5567 return true;
5568 // Record usage of conversion in an implicit cast.
5569 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005570 CK_UserDefinedConversion, Result.get(),
5571 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 }
5573 return false;
5574}
5575
5576static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5577 Sema::ContextualImplicitConverter &Converter,
5578 QualType T, bool HadMultipleCandidates,
5579 DeclAccessPair &Found) {
5580 CXXConversionDecl *Conversion =
5581 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005582 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005583
5584 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5585 if (!Converter.SuppressConversion) {
5586 if (SemaRef.isSFINAEContext())
5587 return true;
5588
5589 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5590 << From->getSourceRange();
5591 }
5592
5593 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5594 HadMultipleCandidates);
5595 if (Result.isInvalid())
5596 return true;
5597 // Record usage of conversion in an implicit cast.
5598 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005599 CK_UserDefinedConversion, Result.get(),
5600 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005601 return false;
5602}
5603
5604static ExprResult finishContextualImplicitConversion(
5605 Sema &SemaRef, SourceLocation Loc, Expr *From,
5606 Sema::ContextualImplicitConverter &Converter) {
5607 if (!Converter.match(From->getType()) && !Converter.Suppress)
5608 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5609 << From->getSourceRange();
5610
5611 return SemaRef.DefaultLvalueConversion(From);
5612}
5613
5614static void
5615collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5616 UnresolvedSetImpl &ViableConversions,
5617 OverloadCandidateSet &CandidateSet) {
5618 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5619 DeclAccessPair FoundDecl = ViableConversions[I];
5620 NamedDecl *D = FoundDecl.getDecl();
5621 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5622 if (isa<UsingShadowDecl>(D))
5623 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5624
5625 CXXConversionDecl *Conv;
5626 FunctionTemplateDecl *ConvTemplate;
5627 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5628 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5629 else
5630 Conv = cast<CXXConversionDecl>(D);
5631
5632 if (ConvTemplate)
5633 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005634 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5635 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005636 else
5637 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005638 ToType, CandidateSet,
5639 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005640 }
5641}
5642
Richard Smithccc11812013-05-21 19:05:48 +00005643/// \brief Attempt to convert the given expression to a type which is accepted
5644/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005645///
Richard Smithccc11812013-05-21 19:05:48 +00005646/// This routine will attempt to convert an expression of class type to a
5647/// type accepted by the specified converter. In C++11 and before, the class
5648/// must have a single non-explicit conversion function converting to a matching
5649/// type. In C++1y, there can be multiple such conversion functions, but only
5650/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005651///
Douglas Gregor4799d032010-06-30 00:20:43 +00005652/// \param Loc The source location of the construct that requires the
5653/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005654///
James Dennett18348b62012-06-22 08:52:37 +00005655/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005656///
Richard Smithccc11812013-05-21 19:05:48 +00005657/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005658///
Douglas Gregor4799d032010-06-30 00:20:43 +00005659/// \returns The expression, converted to an integral or enumeration type if
5660/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005661ExprResult Sema::PerformContextualImplicitConversion(
5662 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005663 // We can't perform any more checking for type-dependent expressions.
5664 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005665 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666
Eli Friedman1da70392012-01-26 00:26:18 +00005667 // Process placeholders immediately.
5668 if (From->hasPlaceholderType()) {
5669 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005670 if (result.isInvalid())
5671 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005672 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005673 }
5674
Richard Smithccc11812013-05-21 19:05:48 +00005675 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005676 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005677 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005678 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005679
5680 // FIXME: Check for missing '()' if T is a function type?
5681
Richard Smithccc11812013-05-21 19:05:48 +00005682 // We can only perform contextual implicit conversions on objects of class
5683 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005684 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005685 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005686 if (!Converter.Suppress)
5687 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005688 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005691 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005692 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005693 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005694 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005695
5696 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005697 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005698
Craig Toppere14c0f82014-03-12 04:55:44 +00005699 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005700 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005701 }
Richard Smithccc11812013-05-21 19:05:48 +00005702 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005703
Richard Smithdb0ac552015-12-18 22:40:25 +00005704 if (Converter.Suppress ? !isCompleteType(Loc, T)
5705 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005706 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005708 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005709 UnresolvedSet<4>
5710 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005711 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005712 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005713 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Larisse Voufo236bec22013-06-10 06:50:24 +00005715 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005716 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005717
Larisse Voufo236bec22013-06-10 06:50:24 +00005718 // To check that there is only one target type, in C++1y:
5719 QualType ToType;
5720 bool HasUniqueTargetType = true;
5721
5722 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005723 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005724 NamedDecl *D = (*I)->getUnderlyingDecl();
5725 CXXConversionDecl *Conversion;
5726 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5727 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005728 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005729 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5730 else
5731 continue; // C++11 does not consider conversion operator templates(?).
5732 } else
5733 Conversion = cast<CXXConversionDecl>(D);
5734
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005735 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005736 "Conversion operator templates are considered potentially "
5737 "viable in C++1y");
5738
5739 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5740 if (Converter.match(CurToType) || ConvTemplate) {
5741
5742 if (Conversion->isExplicit()) {
5743 // FIXME: For C++1y, do we need this restriction?
5744 // cf. diagnoseNoViableConversion()
5745 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005746 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005747 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005748 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005749 if (ToType.isNull())
5750 ToType = CurToType.getUnqualifiedType();
5751 else if (HasUniqueTargetType &&
5752 (CurToType.getUnqualifiedType() != ToType))
5753 HasUniqueTargetType = false;
5754 }
5755 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005756 }
Richard Smith8dd34252012-02-04 07:07:42 +00005757 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005760 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005761 // C++1y [conv]p6:
5762 // ... An expression e of class type E appearing in such a context
5763 // is said to be contextually implicitly converted to a specified
5764 // type T and is well-formed if and only if e can be implicitly
5765 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005766 // for conversion functions whose return type is cv T or reference to
5767 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005768 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005769
Larisse Voufo236bec22013-06-10 06:50:24 +00005770 // If no unique T is found:
5771 if (ToType.isNull()) {
5772 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5773 HadMultipleCandidates,
5774 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005775 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005776 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778
Larisse Voufo236bec22013-06-10 06:50:24 +00005779 // If more than one unique Ts are found:
5780 if (!HasUniqueTargetType)
5781 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5782 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005783
Larisse Voufo236bec22013-06-10 06:50:24 +00005784 // If one unique T is found:
5785 // First, build a candidate set from the previously recorded
5786 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005787 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005788 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5789 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Larisse Voufo236bec22013-06-10 06:50:24 +00005791 // Then, perform overload resolution over the candidate set.
5792 OverloadCandidateSet::iterator Best;
5793 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5794 case OR_Success: {
5795 // Apply this conversion.
5796 DeclAccessPair Found =
5797 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5798 if (recordConversion(*this, Loc, From, Converter, T,
5799 HadMultipleCandidates, Found))
5800 return ExprError();
5801 break;
5802 }
5803 case OR_Ambiguous:
5804 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5805 ViableConversions);
5806 case OR_No_Viable_Function:
5807 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5808 HadMultipleCandidates,
5809 ExplicitConversions))
5810 return ExprError();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005811 LLVM_FALLTHROUGH;
Larisse Voufo236bec22013-06-10 06:50:24 +00005812 case OR_Deleted:
5813 // We'll complain below about a non-integral condition type.
5814 break;
5815 }
5816 } else {
5817 switch (ViableConversions.size()) {
5818 case 0: {
5819 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5820 HadMultipleCandidates,
5821 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005822 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005823
Larisse Voufo236bec22013-06-10 06:50:24 +00005824 // We'll complain below about a non-integral condition type.
5825 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005826 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005827 case 1: {
5828 // Apply this conversion.
5829 DeclAccessPair Found = ViableConversions[0];
5830 if (recordConversion(*this, Loc, From, Converter, T,
5831 HadMultipleCandidates, Found))
5832 return ExprError();
5833 break;
5834 }
5835 default:
5836 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5837 ViableConversions);
5838 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840
Larisse Voufo236bec22013-06-10 06:50:24 +00005841 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005842}
5843
Richard Smith100b24a2014-04-17 01:52:14 +00005844/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5845/// an acceptable non-member overloaded operator for a call whose
5846/// arguments have types T1 (and, if non-empty, T2). This routine
5847/// implements the check in C++ [over.match.oper]p3b2 concerning
5848/// enumeration types.
5849static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5850 FunctionDecl *Fn,
5851 ArrayRef<Expr *> Args) {
5852 QualType T1 = Args[0]->getType();
5853 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5854
5855 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5856 return true;
5857
5858 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5859 return true;
5860
5861 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5862 if (Proto->getNumParams() < 1)
5863 return false;
5864
5865 if (T1->isEnumeralType()) {
5866 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5867 if (Context.hasSameUnqualifiedType(T1, ArgType))
5868 return true;
5869 }
5870
5871 if (Proto->getNumParams() < 2)
5872 return false;
5873
5874 if (!T2.isNull() && T2->isEnumeralType()) {
5875 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5876 if (Context.hasSameUnqualifiedType(T2, ArgType))
5877 return true;
5878 }
5879
5880 return false;
5881}
5882
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005883/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005884/// candidate functions, using the given function call arguments. If
5885/// @p SuppressUserConversions, then don't allow user-defined
5886/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005887///
James Dennett2a4d13c2012-06-15 07:13:21 +00005888/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005889/// based on an incomplete set of function arguments. This feature is used by
5890/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005891void
5892Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005893 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005894 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005895 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005896 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005897 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005898 bool AllowExplicit,
5899 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005900 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005901 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005902 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005903 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005904 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005905
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005907 if (!isa<CXXConstructorDecl>(Method)) {
5908 // If we get here, it's because we're calling a member function
5909 // that is named without a member access expression (e.g.,
5910 // "this->f") that was either written explicitly or created
5911 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005912 // function, e.g., X::f(). We use an empty type for the implied
5913 // object argument (C++ [over.call.func]p3), and the acting context
5914 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005915 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005916 Expr::Classification::makeSimpleLValue(), Args,
5917 CandidateSet, SuppressUserConversions,
5918 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005919 return;
5920 }
5921 // We treat a constructor like a non-member function, since its object
5922 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005923 }
5924
Douglas Gregorff7028a2009-11-13 23:59:09 +00005925 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005926 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005927
Richard Smith100b24a2014-04-17 01:52:14 +00005928 // C++ [over.match.oper]p3:
5929 // if no operand has a class type, only those non-member functions in the
5930 // lookup set that have a first parameter of type T1 or "reference to
5931 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5932 // is a right operand) a second parameter of type T2 or "reference to
5933 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5934 // candidate functions.
5935 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5936 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5937 return;
5938
Richard Smith8b86f2d2013-11-04 01:48:18 +00005939 // C++11 [class.copy]p11: [DR1402]
5940 // A defaulted move constructor that is defined as deleted is ignored by
5941 // overload resolution.
5942 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5943 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5944 Constructor->isMoveConstructor())
5945 return;
5946
Douglas Gregor27381f32009-11-23 12:27:39 +00005947 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005948 EnterExpressionEvaluationContext Unevaluated(
5949 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005950
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005951 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005952 OverloadCandidate &Candidate =
5953 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005954 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005955 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005956 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005957 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005958 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005959 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005960
Erich Keane281d20b2018-01-08 21:34:17 +00005961 if (Function->isMultiVersion() &&
5962 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5963 Candidate.Viable = false;
5964 Candidate.FailureKind = ovl_non_default_multiversion_function;
5965 return;
5966 }
5967
John McCall578a1f82014-12-14 01:46:53 +00005968 if (Constructor) {
5969 // C++ [class.copy]p3:
5970 // A member function template is never instantiated to perform the copy
5971 // of a class object to an object of its class type.
5972 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005973 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005974 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005975 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5976 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005977 Candidate.Viable = false;
5978 Candidate.FailureKind = ovl_fail_illegal_constructor;
5979 return;
5980 }
Richard Smith836a3b42017-01-13 20:46:54 +00005981
5982 // C++ [over.match.funcs]p8: (proposed DR resolution)
5983 // A constructor inherited from class type C that has a first parameter
5984 // of type "reference to P" (including such a constructor instantiated
5985 // from a template) is excluded from the set of candidate functions when
5986 // constructing an object of type cv D if the argument list has exactly
5987 // one argument and D is reference-related to P and P is reference-related
5988 // to C.
5989 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5990 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5991 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5992 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5993 QualType C = Context.getRecordType(Constructor->getParent());
5994 QualType D = Context.getRecordType(Shadow->getParent());
5995 SourceLocation Loc = Args.front()->getExprLoc();
5996 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5997 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5998 Candidate.Viable = false;
5999 Candidate.FailureKind = ovl_fail_inhctor_slice;
6000 return;
6001 }
6002 }
John McCall578a1f82014-12-14 01:46:53 +00006003 }
6004
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006005 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006006
6007 // (C++ 13.3.2p2): A candidate function having fewer than m
6008 // parameters is viable only if it has an ellipsis in its parameter
6009 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006010 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00006011 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006012 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006013 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006014 return;
6015 }
6016
6017 // (C++ 13.3.2p2): A candidate function having more than m parameters
6018 // is viable only if the (m+1)st parameter has a default argument
6019 // (8.3.6). For the purposes of overload resolution, the
6020 // parameter list is truncated on the right, so that there are
6021 // exactly m parameters.
6022 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006023 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006024 // Not enough arguments.
6025 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006026 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006027 return;
6028 }
6029
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006030 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006031 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006032 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006033 // Skip the check for callers that are implicit members, because in this
6034 // case we may not yet know what the member's target is; the target is
6035 // inferred for the member automatically, based on the bases and fields of
6036 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006037 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006038 Candidate.Viable = false;
6039 Candidate.FailureKind = ovl_fail_bad_target;
6040 return;
6041 }
6042
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006043 // Determine the implicit conversion sequences for each of the
6044 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006045 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006046 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6047 // We already formed a conversion sequence for this parameter during
6048 // template argument deduction.
6049 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006050 // (C++ 13.3.2p3): for F to be a viable function, there shall
6051 // exist for each argument an implicit conversion sequence
6052 // (13.3.3.1) that converts that argument to the corresponding
6053 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006054 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006055 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006056 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006058 /*InOverloadResolution=*/true,
6059 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006060 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006061 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006062 if (Candidate.Conversions[ArgIdx].isBad()) {
6063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006064 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006065 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006066 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006067 } else {
6068 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6069 // argument for which there is no corresponding parameter is
6070 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006071 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006072 }
6073 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006074
6075 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6076 Candidate.Viable = false;
6077 Candidate.FailureKind = ovl_fail_enable_if;
6078 Candidate.DeductionFailure.Data = FailedAttr;
6079 return;
6080 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006081
6082 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6083 Candidate.Viable = false;
6084 Candidate.FailureKind = ovl_fail_ext_disabled;
6085 return;
6086 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006087}
6088
Manman Rend2a3cd72016-04-07 19:30:20 +00006089ObjCMethodDecl *
6090Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6091 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6092 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006093 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006094
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006095 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6096 bool Match = true;
6097 ObjCMethodDecl *Method = Methods[b];
6098 unsigned NumNamedArgs = Sel.getNumArgs();
6099 // Method might have more arguments than selector indicates. This is due
6100 // to addition of c-style arguments in method.
6101 if (Method->param_size() > NumNamedArgs)
6102 NumNamedArgs = Method->param_size();
6103 if (Args.size() < NumNamedArgs)
6104 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006105
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006106 for (unsigned i = 0; i < NumNamedArgs; i++) {
6107 // We can't do any type-checking on a type-dependent argument.
6108 if (Args[i]->isTypeDependent()) {
6109 Match = false;
6110 break;
6111 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006112
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006113 ParmVarDecl *param = Method->parameters()[i];
6114 Expr *argExpr = Args[i];
6115 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006116
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006117 // Strip the unbridged-cast placeholder expression off unless it's
6118 // a consumed argument.
6119 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6120 !param->hasAttr<CFConsumedAttr>())
6121 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006122
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006123 // If the parameter is __unknown_anytype, move on to the next method.
6124 if (param->getType() == Context.UnknownAnyTy) {
6125 Match = false;
6126 break;
6127 }
George Burgess IV45461812015-10-11 20:13:20 +00006128
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006129 ImplicitConversionSequence ConversionState
6130 = TryCopyInitialization(*this, argExpr, param->getType(),
6131 /*SuppressUserConversions*/false,
6132 /*InOverloadResolution=*/true,
6133 /*AllowObjCWritebackConversion=*/
6134 getLangOpts().ObjCAutoRefCount,
6135 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006136 // This function looks for a reasonably-exact match, so we consider
6137 // incompatible pointer conversions to be a failure here.
6138 if (ConversionState.isBad() ||
6139 (ConversionState.isStandard() &&
6140 ConversionState.Standard.Second ==
6141 ICK_Incompatible_Pointer_Conversion)) {
6142 Match = false;
6143 break;
6144 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006145 }
6146 // Promote additional arguments to variadic methods.
6147 if (Match && Method->isVariadic()) {
6148 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6149 if (Args[i]->isTypeDependent()) {
6150 Match = false;
6151 break;
6152 }
6153 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6154 nullptr);
6155 if (Arg.isInvalid()) {
6156 Match = false;
6157 break;
6158 }
6159 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006160 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006161 // Check for extra arguments to non-variadic methods.
6162 if (Args.size() != NumNamedArgs)
6163 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006164 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6165 // Special case when selectors have no argument. In this case, select
6166 // one with the most general result type of 'id'.
6167 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6168 QualType ReturnT = Methods[b]->getReturnType();
6169 if (ReturnT->isObjCIdType())
6170 return Methods[b];
6171 }
6172 }
6173 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006174
6175 if (Match)
6176 return Method;
6177 }
6178 return nullptr;
6179}
6180
George Burgess IV2a6150d2015-10-16 01:17:38 +00006181// specific_attr_iterator iterates over enable_if attributes in reverse, and
6182// enable_if is order-sensitive. As a result, we need to reverse things
6183// sometimes. Size of 4 elements is arbitrary.
6184static SmallVector<EnableIfAttr *, 4>
6185getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6186 SmallVector<EnableIfAttr *, 4> Result;
6187 if (!Function->hasAttrs())
6188 return Result;
6189
6190 const auto &FuncAttrs = Function->getAttrs();
6191 for (Attr *Attr : FuncAttrs)
6192 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6193 Result.push_back(EnableIf);
6194
6195 std::reverse(Result.begin(), Result.end());
6196 return Result;
6197}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006198
George Burgess IV177399e2017-01-09 04:12:14 +00006199static bool
6200convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6201 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6202 bool MissingImplicitThis, Expr *&ConvertedThis,
6203 SmallVectorImpl<Expr *> &ConvertedArgs) {
6204 if (ThisArg) {
6205 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6206 assert(!isa<CXXConstructorDecl>(Method) &&
6207 "Shouldn't have `this` for ctors!");
6208 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6209 ExprResult R = S.PerformObjectArgumentInitialization(
6210 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6211 if (R.isInvalid())
6212 return false;
6213 ConvertedThis = R.get();
6214 } else {
6215 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6216 (void)MD;
6217 assert((MissingImplicitThis || MD->isStatic() ||
6218 isa<CXXConstructorDecl>(MD)) &&
6219 "Expected `this` for non-ctor instance methods");
6220 }
6221 ConvertedThis = nullptr;
6222 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006223
George Burgess IV458b3f32016-08-12 04:19:35 +00006224 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006225 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006226 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6227
Nick Lewyckye283c552015-08-25 22:33:16 +00006228 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006229 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006230 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006231 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6232 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006233 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006234
George Burgess IV177399e2017-01-09 04:12:14 +00006235 if (R.isInvalid())
6236 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006237
George Burgess IVe96abf72016-02-24 22:31:14 +00006238 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006239 }
6240
George Burgess IV177399e2017-01-09 04:12:14 +00006241 if (Trap.hasErrorOccurred())
6242 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006243
Nick Lewyckye283c552015-08-25 22:33:16 +00006244 // Push default arguments if needed.
6245 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6246 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6247 ParmVarDecl *P = Function->getParamDecl(i);
Ilya Biryukov1a1dffd2018-03-09 14:43:29 +00006248 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6249 ? P->getUninstantiatedDefaultArg()
6250 : P->getDefaultArg();
6251 // This can only happen in code completion, i.e. when PartialOverloading
6252 // is true.
6253 if (!DefArg)
6254 return false;
6255 ExprResult R =
6256 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6257 S.Context, Function->getParamDecl(i)),
6258 SourceLocation(), DefArg);
George Burgess IV177399e2017-01-09 04:12:14 +00006259 if (R.isInvalid())
6260 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006261 ConvertedArgs.push_back(R.get());
6262 }
6263
George Burgess IV177399e2017-01-09 04:12:14 +00006264 if (Trap.hasErrorOccurred())
6265 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006266 }
George Burgess IV177399e2017-01-09 04:12:14 +00006267 return true;
6268}
6269
6270EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6271 bool MissingImplicitThis) {
6272 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6273 getOrderedEnableIfAttrs(Function);
6274 if (EnableIfAttrs.empty())
6275 return nullptr;
6276
6277 SFINAETrap Trap(*this);
6278 SmallVector<Expr *, 16> ConvertedArgs;
6279 // FIXME: We should look into making enable_if late-parsed.
6280 Expr *DiscardedThis;
6281 if (!convertArgsForAvailabilityChecks(
6282 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6283 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6284 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006285
George Burgess IV2a6150d2015-10-16 01:17:38 +00006286 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006287 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006288 // FIXME: This doesn't consider value-dependent cases, because doing so is
6289 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006290 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006291 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006292 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006293
6294 if (!Result.isInt() || !Result.getInt().getBoolValue())
6295 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006296 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006297 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006298}
6299
George Burgess IV177399e2017-01-09 04:12:14 +00006300template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006301static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006302 bool ArgDependent, SourceLocation Loc,
6303 CheckFn &&IsSuccessful) {
6304 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006305 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006306 if (ArgDependent == DIA->getArgDependent())
6307 Attrs.push_back(DIA);
6308 }
6309
6310 // Common case: No diagnose_if attributes, so we can quit early.
6311 if (Attrs.empty())
6312 return false;
6313
6314 auto WarningBegin = std::stable_partition(
6315 Attrs.begin(), Attrs.end(),
6316 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6317
George Burgess IV177399e2017-01-09 04:12:14 +00006318 // Note that diagnose_if attributes are late-parsed, so they appear in the
6319 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006320 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6321 IsSuccessful);
6322 if (ErrAttr != WarningBegin) {
6323 const DiagnoseIfAttr *DIA = *ErrAttr;
6324 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6325 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6326 << DIA->getParent() << DIA->getCond()->getSourceRange();
6327 return true;
6328 }
George Burgess IV177399e2017-01-09 04:12:14 +00006329
George Burgess IVce6284b2017-01-28 02:19:40 +00006330 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6331 if (IsSuccessful(DIA)) {
6332 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6333 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6334 << DIA->getParent() << DIA->getCond()->getSourceRange();
6335 }
6336
6337 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006338}
6339
George Burgess IVce6284b2017-01-28 02:19:40 +00006340bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6341 const Expr *ThisArg,
6342 ArrayRef<const Expr *> Args,
6343 SourceLocation Loc) {
6344 return diagnoseDiagnoseIfAttrsWith(
6345 *this, Function, /*ArgDependent=*/true, Loc,
6346 [&](const DiagnoseIfAttr *DIA) {
6347 APValue Result;
6348 // It's sane to use the same Args for any redecl of this function, since
6349 // EvaluateWithSubstitution only cares about the position of each
6350 // argument in the arg list, not the ParmVarDecl* it maps to.
6351 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006352 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006353 return false;
6354 return Result.isInt() && Result.getInt().getBoolValue();
6355 });
George Burgess IV177399e2017-01-09 04:12:14 +00006356}
6357
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006358bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006359 SourceLocation Loc) {
6360 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006361 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006362 [&](const DiagnoseIfAttr *DIA) {
6363 bool Result;
6364 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6365 Result;
6366 });
George Burgess IV177399e2017-01-09 04:12:14 +00006367}
6368
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006369/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006370/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006371void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006372 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006373 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006374 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006375 bool SuppressUserConversions,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006376 bool PartialOverloading,
6377 bool FirstArgumentIsBase) {
John McCall4c4c1df2010-01-26 03:27:55 +00006378 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006379 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6380 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006381 ArrayRef<Expr *> FunctionArgs = Args;
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006382 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6383 QualType ObjectType;
6384 Expr::Classification ObjectClassification;
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006385 if (Args.size() > 0) {
6386 if (Expr *E = Args[0]) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006387 // Use the explicit base to restrict the lookup:
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006388 ObjectType = E->getType();
6389 ObjectClassification = E->Classify(Context);
6390 } // .. else there is an implit base.
6391 FunctionArgs = Args.slice(1);
6392 }
John McCalla0296f72010-03-19 07:35:19 +00006393 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006394 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006395 ObjectClassification, FunctionArgs, CandidateSet,
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006396 SuppressUserConversions, PartialOverloading);
6397 } else {
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006398 // Slice the first argument (which is the base) when we access
6399 // static method as non-static
6400 if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6401 !isa<CXXConstructorDecl>(FD)))) {
6402 assert(cast<CXXMethodDecl>(FD)->isStatic());
6403 FunctionArgs = Args.slice(1);
6404 }
6405 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006406 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006407 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006408 } else {
John McCalla0296f72010-03-19 07:35:19 +00006409 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006410 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006411 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6412 QualType ObjectType;
6413 Expr::Classification ObjectClassification;
6414 if (Expr *E = Args[0]) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006415 // Use the explicit base to restrict the lookup:
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006416 ObjectType = E->getType();
6417 ObjectClassification = E->Classify(Context);
6418 } // .. else there is an implit base.
George Burgess IV177399e2017-01-09 04:12:14 +00006419 AddMethodTemplateCandidate(
6420 FunTmpl, F.getPair(),
6421 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006422 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6423 Args.slice(1), CandidateSet, SuppressUserConversions,
6424 PartialOverloading);
6425 } else {
John McCalla0296f72010-03-19 07:35:19 +00006426 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006427 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006428 CandidateSet, SuppressUserConversions,
6429 PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006430 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006431 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006432 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006433}
6434
John McCallf0f1cf02009-11-17 07:50:12 +00006435/// AddMethodCandidate - Adds a named decl (which is some kind of
6436/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006437void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006438 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006439 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006440 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006441 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006442 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006443 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006444 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006445
6446 if (isa<UsingShadowDecl>(Decl))
6447 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448
John McCallf0f1cf02009-11-17 07:50:12 +00006449 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6450 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6451 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006452 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006453 /*ExplicitArgs*/ nullptr, ObjectType,
6454 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006455 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006456 } else {
John McCalla0296f72010-03-19 07:35:19 +00006457 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006458 ObjectType, ObjectClassification, Args, CandidateSet,
6459 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006460 }
6461}
6462
Douglas Gregor436424c2008-11-18 23:14:02 +00006463/// AddMethodCandidate - Adds the given C++ member function to the set
6464/// of candidate functions, using the given function call arguments
6465/// and the object argument (@c Object). For example, in a call
6466/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6467/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6468/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006469/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006470void
John McCalla0296f72010-03-19 07:35:19 +00006471Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006472 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006473 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006474 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006475 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006476 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006477 bool PartialOverloading,
6478 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006479 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006480 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006481 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006482 assert(!isa<CXXConstructorDecl>(Method) &&
6483 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006484
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006485 if (!CandidateSet.isNewCandidate(Method))
6486 return;
6487
Richard Smith8b86f2d2013-11-04 01:48:18 +00006488 // C++11 [class.copy]p23: [DR1402]
6489 // A defaulted move assignment operator that is defined as deleted is
6490 // ignored by overload resolution.
6491 if (Method->isDefaulted() && Method->isDeleted() &&
6492 Method->isMoveAssignmentOperator())
6493 return;
6494
Douglas Gregor27381f32009-11-23 12:27:39 +00006495 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006496 EnterExpressionEvaluationContext Unevaluated(
6497 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006498
Douglas Gregor436424c2008-11-18 23:14:02 +00006499 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006500 OverloadCandidate &Candidate =
6501 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006502 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006503 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006504 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006505 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006506 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006507
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006508 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006509
6510 // (C++ 13.3.2p2): A candidate function having fewer than m
6511 // parameters is viable only if it has an ellipsis in its parameter
6512 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006513 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6514 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006515 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006516 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006517 return;
6518 }
6519
6520 // (C++ 13.3.2p2): A candidate function having more than m parameters
6521 // is viable only if the (m+1)st parameter has a default argument
6522 // (8.3.6). For the purposes of overload resolution, the
6523 // parameter list is truncated on the right, so that there are
6524 // exactly m parameters.
6525 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006526 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006527 // Not enough arguments.
6528 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006529 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006530 return;
6531 }
6532
6533 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006534
John McCall6e9f8f62009-12-03 04:06:58 +00006535 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006536 // The implicit object argument is ignored.
6537 Candidate.IgnoreObjectArgument = true;
6538 else {
6539 // Determine the implicit conversion sequence for the object
6540 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006541 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6542 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6543 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006544 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006545 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006546 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006547 return;
6548 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006549 }
6550
Eli Bendersky291a57e2014-09-25 23:59:08 +00006551 // (CUDA B.1): Check for invalid calls between targets.
6552 if (getLangOpts().CUDA)
6553 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006554 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006555 Candidate.Viable = false;
6556 Candidate.FailureKind = ovl_fail_bad_target;
6557 return;
6558 }
6559
Douglas Gregor436424c2008-11-18 23:14:02 +00006560 // Determine the implicit conversion sequences for each of the
6561 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006562 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006563 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6564 // We already formed a conversion sequence for this parameter during
6565 // template argument deduction.
6566 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006567 // (C++ 13.3.2p3): for F to be a viable function, there shall
6568 // exist for each argument an implicit conversion sequence
6569 // (13.3.3.1) that converts that argument to the corresponding
6570 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006571 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006572 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006573 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006574 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006575 /*InOverloadResolution=*/true,
6576 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006577 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006578 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006579 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006580 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006581 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006582 }
6583 } else {
6584 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6585 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006586 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006587 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006588 }
6589 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006590
6591 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6592 Candidate.Viable = false;
6593 Candidate.FailureKind = ovl_fail_enable_if;
6594 Candidate.DeductionFailure.Data = FailedAttr;
6595 return;
6596 }
Erich Keane281d20b2018-01-08 21:34:17 +00006597
6598 if (Method->isMultiVersion() &&
6599 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6600 Candidate.Viable = false;
6601 Candidate.FailureKind = ovl_non_default_multiversion_function;
6602 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006603}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604
Douglas Gregor97628d62009-08-21 00:16:32 +00006605/// \brief Add a C++ member function template as a candidate to the candidate
6606/// set, using template argument deduction to produce an appropriate member
6607/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006608void
Douglas Gregor97628d62009-08-21 00:16:32 +00006609Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006610 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006611 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006612 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006613 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006614 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006615 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006616 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006617 bool SuppressUserConversions,
6618 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006619 if (!CandidateSet.isNewCandidate(MethodTmpl))
6620 return;
6621
Douglas Gregor97628d62009-08-21 00:16:32 +00006622 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006623 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006624 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006625 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006626 // candidate functions in the usual way.113) A given name can refer to one
6627 // or more function templates and also to a set of overloaded non-template
6628 // functions. In such a case, the candidate functions generated from each
6629 // function template are combined with the set of non-template candidate
6630 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006631 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006632 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006633 ConversionSequenceList Conversions;
6634 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6635 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6636 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6637 return CheckNonDependentConversions(
6638 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6639 SuppressUserConversions, ActingContext, ObjectType,
6640 ObjectClassification);
6641 })) {
6642 OverloadCandidate &Candidate =
6643 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006644 Candidate.FoundDecl = FoundDecl;
6645 Candidate.Function = MethodTmpl->getTemplatedDecl();
6646 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006647 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006648 Candidate.IgnoreObjectArgument =
6649 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6650 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006651 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006652 if (Result == TDK_NonDependentConversionFailure)
6653 Candidate.FailureKind = ovl_fail_bad_conversion;
6654 else {
6655 Candidate.FailureKind = ovl_fail_bad_deduction;
6656 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6657 Info);
6658 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006659 return;
6660 }
Mike Stump11289f42009-09-09 15:08:12 +00006661
Douglas Gregor97628d62009-08-21 00:16:32 +00006662 // Add the function template specialization produced by template argument
6663 // deduction as a candidate.
6664 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006665 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006666 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006667 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006668 ActingContext, ObjectType, ObjectClassification, Args,
6669 CandidateSet, SuppressUserConversions, PartialOverloading,
6670 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006671}
6672
Douglas Gregor05155d82009-08-21 23:19:43 +00006673/// \brief Add a C++ function template specialization as a candidate
6674/// in the candidate set, using template argument deduction to produce
6675/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006676void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006677Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006678 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006679 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006680 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006681 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006682 bool SuppressUserConversions,
6683 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006684 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6685 return;
6686
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006687 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006688 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006689 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006690 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006691 // candidate functions in the usual way.113) A given name can refer to one
6692 // or more function templates and also to a set of overloaded non-template
6693 // functions. In such a case, the candidate functions generated from each
6694 // function template are combined with the set of non-template candidate
6695 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006696 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006697 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006698 ConversionSequenceList Conversions;
6699 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6700 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6701 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6702 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6703 Args, CandidateSet, Conversions,
6704 SuppressUserConversions);
6705 })) {
6706 OverloadCandidate &Candidate =
6707 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006708 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006709 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6710 Candidate.Viable = false;
6711 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006712 // Ignore the object argument if there is one, since we don't have an object
6713 // type.
6714 Candidate.IgnoreObjectArgument =
6715 isa<CXXMethodDecl>(Candidate.Function) &&
6716 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006717 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006718 if (Result == TDK_NonDependentConversionFailure)
6719 Candidate.FailureKind = ovl_fail_bad_conversion;
6720 else {
6721 Candidate.FailureKind = ovl_fail_bad_deduction;
6722 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6723 Info);
6724 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006725 return;
6726 }
Mike Stump11289f42009-09-09 15:08:12 +00006727
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006728 // Add the function template specialization produced by template argument
6729 // deduction as a candidate.
6730 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006731 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006732 SuppressUserConversions, PartialOverloading,
6733 /*AllowExplicit*/false, Conversions);
6734}
6735
6736/// Check that implicit conversion sequences can be formed for each argument
6737/// whose corresponding parameter has a non-dependent type, per DR1391's
6738/// [temp.deduct.call]p10.
6739bool Sema::CheckNonDependentConversions(
6740 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6741 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6742 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6743 CXXRecordDecl *ActingContext, QualType ObjectType,
6744 Expr::Classification ObjectClassification) {
6745 // FIXME: The cases in which we allow explicit conversions for constructor
6746 // arguments never consider calling a constructor template. It's not clear
6747 // that is correct.
6748 const bool AllowExplicit = false;
6749
6750 auto *FD = FunctionTemplate->getTemplatedDecl();
6751 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6752 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6753 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6754
6755 Conversions =
6756 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6757
6758 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006759 EnterExpressionEvaluationContext Unevaluated(
6760 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006761
6762 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6763 // require that, but this check should never result in a hard error, and
6764 // overload resolution is permitted to sidestep instantiations.
6765 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6766 !ObjectType.isNull()) {
6767 Conversions[0] = TryObjectArgumentInitialization(
6768 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6769 Method, ActingContext);
6770 if (Conversions[0].isBad())
6771 return true;
6772 }
6773
6774 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6775 ++I) {
6776 QualType ParamType = ParamTypes[I];
6777 if (!ParamType->isDependentType()) {
6778 Conversions[ThisConversions + I]
6779 = TryCopyInitialization(*this, Args[I], ParamType,
6780 SuppressUserConversions,
6781 /*InOverloadResolution=*/true,
6782 /*AllowObjCWritebackConversion=*/
6783 getLangOpts().ObjCAutoRefCount,
6784 AllowExplicit);
6785 if (Conversions[ThisConversions + I].isBad())
6786 return true;
6787 }
6788 }
6789
6790 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006791}
Mike Stump11289f42009-09-09 15:08:12 +00006792
Douglas Gregor4b60a152013-11-07 22:34:54 +00006793/// Determine whether this is an allowable conversion from the result
6794/// of an explicit conversion operator to the expected type, per C++
6795/// [over.match.conv]p1 and [over.match.ref]p1.
6796///
6797/// \param ConvType The return type of the conversion function.
6798///
6799/// \param ToType The type we are converting to.
6800///
6801/// \param AllowObjCPointerConversion Allow a conversion from one
6802/// Objective-C pointer to another.
6803///
6804/// \returns true if the conversion is allowable, false otherwise.
6805static bool isAllowableExplicitConversion(Sema &S,
6806 QualType ConvType, QualType ToType,
6807 bool AllowObjCPointerConversion) {
6808 QualType ToNonRefType = ToType.getNonReferenceType();
6809
6810 // Easy case: the types are the same.
6811 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6812 return true;
6813
6814 // Allow qualification conversions.
6815 bool ObjCLifetimeConversion;
6816 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6817 ObjCLifetimeConversion))
6818 return true;
6819
6820 // If we're not allowed to consider Objective-C pointer conversions,
6821 // we're done.
6822 if (!AllowObjCPointerConversion)
6823 return false;
6824
6825 // Is this an Objective-C pointer conversion?
6826 bool IncompatibleObjC = false;
6827 QualType ConvertedType;
6828 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6829 IncompatibleObjC);
6830}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006831
Douglas Gregora1f013e2008-11-07 22:36:19 +00006832/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006833/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006834/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006835/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006836/// (which may or may not be the same type as the type that the
6837/// conversion function produces).
6838void
6839Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006840 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006841 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006842 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006843 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006844 bool AllowObjCConversionOnExplicit,
6845 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006846 assert(!Conversion->getDescribedFunctionTemplate() &&
6847 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006848 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006849 if (!CandidateSet.isNewCandidate(Conversion))
6850 return;
6851
Richard Smith2a7d4812013-05-04 07:00:32 +00006852 // If the conversion function has an undeduced return type, trigger its
6853 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006854 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006855 if (DeduceReturnType(Conversion, From->getExprLoc()))
6856 return;
6857 ConvType = Conversion->getConversionType().getNonReferenceType();
6858 }
6859
Richard Smith67ef14f2017-09-26 18:37:55 +00006860 // If we don't allow any conversion of the result type, ignore conversion
6861 // functions that don't convert to exactly (possibly cv-qualified) T.
6862 if (!AllowResultConversion &&
6863 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6864 return;
6865
Richard Smith089c3162013-09-21 21:55:46 +00006866 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6867 // operator is only a candidate if its return type is the target type or
6868 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006869 if (Conversion->isExplicit() &&
6870 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006871 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006872 return;
6873
Douglas Gregor27381f32009-11-23 12:27:39 +00006874 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006875 EnterExpressionEvaluationContext Unevaluated(
6876 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006877
Douglas Gregora1f013e2008-11-07 22:36:19 +00006878 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006879 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006880 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006881 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006882 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006883 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006884 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006885 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006886 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006887 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006888 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006889
Douglas Gregor6affc782010-08-19 15:37:02 +00006890 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891 // For conversion functions, the function is considered to be a member of
6892 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006893 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006894 //
6895 // Determine the implicit conversion sequence for the implicit
6896 // object parameter.
6897 QualType ImplicitParamType = From->getType();
6898 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6899 ImplicitParamType = FromPtrType->getPointeeType();
6900 CXXRecordDecl *ConversionContext
6901 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902
Richard Smith0f59cb32015-12-18 21:45:41 +00006903 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6904 *this, CandidateSet.getLocation(), From->getType(),
6905 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006906
John McCall0d1da222010-01-12 00:44:57 +00006907 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006908 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006909 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006910 return;
6911 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006912
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006913 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006914 // derived to base as such conversions are given Conversion Rank. They only
6915 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6916 QualType FromCanon
6917 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6918 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006919 if (FromCanon == ToCanon ||
6920 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006921 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006922 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006923 return;
6924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
Douglas Gregora1f013e2008-11-07 22:36:19 +00006926 // To determine what the conversion from the result of calling the
6927 // conversion function to the type we're eventually trying to
6928 // convert to (ToType), we need to synthesize a call to the
6929 // conversion function and attempt copy initialization from it. This
6930 // makes sure that we get the right semantics with respect to
6931 // lvalues/rvalues and the type. Fortunately, we can allocate this
6932 // call on the stack and we don't need its arguments to be
6933 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006934 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006935 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006936 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6937 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006938 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006939 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006940
Richard Smith48d24642011-07-13 22:53:21 +00006941 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006942 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006943 Candidate.Viable = false;
6944 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6945 return;
6946 }
6947
Richard Smith48d24642011-07-13 22:53:21 +00006948 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006949
Mike Stump11289f42009-09-09 15:08:12 +00006950 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006951 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6952 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006953 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006954 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006955 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006956 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006957 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006958 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006959 /*InOverloadResolution=*/false,
6960 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006961
John McCall0d1da222010-01-12 00:44:57 +00006962 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006963 case ImplicitConversionSequence::StandardConversion:
6964 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006966 // C++ [over.ics.user]p3:
6967 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006969 // shall have exact match rank.
6970 if (Conversion->getPrimaryTemplate() &&
6971 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6972 Candidate.Viable = false;
6973 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006974 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
Douglas Gregorcba72b12011-01-21 05:18:22 +00006977 // C++0x [dcl.init.ref]p5:
6978 // In the second case, if the reference is an rvalue reference and
6979 // the second standard conversion sequence of the user-defined
6980 // conversion sequence includes an lvalue-to-rvalue conversion, the
6981 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006983 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6984 Candidate.Viable = false;
6985 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006986 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006987 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006988 break;
6989
6990 case ImplicitConversionSequence::BadConversion:
6991 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006992 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006993 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006994
6995 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006996 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006997 "Can only end up with a standard conversion sequence or failure");
6998 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006999
Craig Topper5fc8fc22014-08-27 06:28:36 +00007000 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007001 Candidate.Viable = false;
7002 Candidate.FailureKind = ovl_fail_enable_if;
7003 Candidate.DeductionFailure.Data = FailedAttr;
7004 return;
7005 }
Erich Keane281d20b2018-01-08 21:34:17 +00007006
7007 if (Conversion->isMultiVersion() &&
7008 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7009 Candidate.Viable = false;
7010 Candidate.FailureKind = ovl_non_default_multiversion_function;
7011 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007012}
7013
Douglas Gregor05155d82009-08-21 23:19:43 +00007014/// \brief Adds a conversion function template specialization
7015/// candidate to the overload set, using template argument deduction
7016/// to deduce the template arguments of the conversion function
7017/// template from the type that we are converting to (C++
7018/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00007019void
Douglas Gregor05155d82009-08-21 23:19:43 +00007020Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00007021 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007022 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00007023 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00007024 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00007025 bool AllowObjCConversionOnExplicit,
7026 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007027 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7028 "Only conversion function templates permitted here");
7029
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007030 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7031 return;
7032
Craig Toppere6706e42012-09-19 02:26:47 +00007033 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007034 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00007035 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00007036 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00007037 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00007038 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007039 Candidate.FoundDecl = FoundDecl;
7040 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7041 Candidate.Viable = false;
7042 Candidate.FailureKind = ovl_fail_bad_deduction;
7043 Candidate.IsSurrogate = false;
7044 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00007045 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007047 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00007048 return;
7049 }
Mike Stump11289f42009-09-09 15:08:12 +00007050
Douglas Gregor05155d82009-08-21 23:19:43 +00007051 // Add the conversion function template specialization produced by
7052 // template argument deduction as a candidate.
7053 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007054 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007055 CandidateSet, AllowObjCConversionOnExplicit,
7056 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007057}
7058
Douglas Gregorab7897a2008-11-19 22:57:39 +00007059/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7060/// converts the given @c Object to a function pointer via the
7061/// conversion function @c Conversion, and then attempts to call it
7062/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7063/// the type of function that we'll eventually be calling.
7064void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007065 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007066 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007067 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007068 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007069 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007070 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007071 if (!CandidateSet.isNewCandidate(Conversion))
7072 return;
7073
Douglas Gregor27381f32009-11-23 12:27:39 +00007074 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007075 EnterExpressionEvaluationContext Unevaluated(
7076 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007077
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007078 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007079 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007080 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007081 Candidate.Surrogate = Conversion;
7082 Candidate.Viable = true;
7083 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007084 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007085 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007086
7087 // Determine the implicit conversion sequence for the implicit
7088 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007089 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7090 *this, CandidateSet.getLocation(), Object->getType(),
7091 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007092 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007093 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007094 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007095 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007096 return;
7097 }
7098
7099 // The first conversion is actually a user-defined conversion whose
7100 // first conversion is ObjectInit's standard conversion (which is
7101 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007102 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007103 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007104 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007105 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007106 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007107 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007108 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007109 = Candidate.Conversions[0].UserDefined.Before;
7110 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7111
Mike Stump11289f42009-09-09 15:08:12 +00007112 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007113 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007114
7115 // (C++ 13.3.2p2): A candidate function having fewer than m
7116 // parameters is viable only if it has an ellipsis in its parameter
7117 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007118 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007119 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007120 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007121 return;
7122 }
7123
7124 // Function types don't have any default arguments, so just check if
7125 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007126 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007127 // Not enough arguments.
7128 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007129 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007130 return;
7131 }
7132
7133 // Determine the implicit conversion sequences for each of the
7134 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007135 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007136 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007137 // (C++ 13.3.2p3): for F to be a viable function, there shall
7138 // exist for each argument an implicit conversion sequence
7139 // (13.3.3.1) that converts that argument to the corresponding
7140 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007141 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007142 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007143 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007144 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007145 /*InOverloadResolution=*/false,
7146 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007147 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007148 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007149 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007150 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007151 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007152 }
7153 } else {
7154 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7155 // argument for which there is no corresponding parameter is
7156 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007157 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007158 }
7159 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007160
Craig Topper5fc8fc22014-08-27 06:28:36 +00007161 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007162 Candidate.Viable = false;
7163 Candidate.FailureKind = ovl_fail_enable_if;
7164 Candidate.DeductionFailure.Data = FailedAttr;
7165 return;
7166 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007167}
7168
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007169/// \brief Add overload candidates for overloaded operators that are
7170/// member functions.
7171///
7172/// Add the overloaded operator candidates that are member functions
7173/// for the operator Op that was used in an operator expression such
7174/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7175/// CandidateSet will store the added overload candidates. (C++
7176/// [over.match.oper]).
7177void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7178 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007179 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007180 OverloadCandidateSet& CandidateSet,
7181 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007182 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7183
7184 // C++ [over.match.oper]p3:
7185 // For a unary operator @ with an operand of a type whose
7186 // cv-unqualified version is T1, and for a binary operator @ with
7187 // a left operand of a type whose cv-unqualified version is T1 and
7188 // a right operand of a type whose cv-unqualified version is T2,
7189 // three sets of candidate functions, designated member
7190 // candidates, non-member candidates and built-in candidates, are
7191 // constructed as follows:
7192 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007193
Richard Smith0feaf0c2013-04-20 12:41:22 +00007194 // -- If T1 is a complete class type or a class currently being
7195 // defined, the set of member candidates is the result of the
7196 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7197 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007198 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007199 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007200 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007201 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007202 // If the type is neither complete nor being defined, bail out now.
7203 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007204 return;
Mike Stump11289f42009-09-09 15:08:12 +00007205
John McCall27b18f82009-11-17 02:14:36 +00007206 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7207 LookupQualifiedName(Operators, T1Rec->getDecl());
7208 Operators.suppressDiagnostics();
7209
Mike Stump11289f42009-09-09 15:08:12 +00007210 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007211 OperEnd = Operators.end();
7212 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007213 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007214 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007215 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007216 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007217 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007218}
7219
Douglas Gregora11693b2008-11-12 17:17:38 +00007220/// AddBuiltinCandidate - Add a candidate for a built-in
7221/// operator. ResultTy and ParamTys are the result and parameter types
7222/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007223/// arguments being passed to the candidate. IsAssignmentOperator
7224/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007225/// operator. NumContextualBoolArguments is the number of arguments
7226/// (at the beginning of the argument list) that will be contextually
7227/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007228void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007229 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007230 bool IsAssignmentOperator,
7231 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007232 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007233 EnterExpressionEvaluationContext Unevaluated(
7234 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007235
Douglas Gregora11693b2008-11-12 17:17:38 +00007236 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007237 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007238 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7239 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007240 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007241 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007242 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007243
7244 // Determine the implicit conversion sequences for each of the
7245 // arguments.
7246 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007247 Candidate.ExplicitCallArguments = Args.size();
7248 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007249 // C++ [over.match.oper]p4:
7250 // For the built-in assignment operators, conversions of the
7251 // left operand are restricted as follows:
7252 // -- no temporaries are introduced to hold the left operand, and
7253 // -- no user-defined conversions are applied to the left
7254 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007255 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007256 //
7257 // We block these conversions by turning off user-defined
7258 // conversions, since that is the only way that initialization of
7259 // a reference to a non-class type can occur from something that
7260 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007261 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007262 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007263 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007264 Candidate.Conversions[ArgIdx]
7265 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007266 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007267 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007268 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007269 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007270 /*InOverloadResolution=*/false,
7271 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007272 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007273 }
John McCall0d1da222010-01-12 00:44:57 +00007274 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007275 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007276 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007277 break;
7278 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007279 }
7280}
7281
Craig Toppercd7b0332013-07-01 06:29:40 +00007282namespace {
7283
Douglas Gregora11693b2008-11-12 17:17:38 +00007284/// BuiltinCandidateTypeSet - A set of types that will be used for the
7285/// candidate operator functions for built-in operators (C++
7286/// [over.built]). The types are separated into pointer types and
7287/// enumeration types.
7288class BuiltinCandidateTypeSet {
7289 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007290 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7291 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007292
7293 /// PointerTypes - The set of pointer types that will be used in the
7294 /// built-in candidates.
7295 TypeSet PointerTypes;
7296
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007297 /// MemberPointerTypes - The set of member pointer types that will be
7298 /// used in the built-in candidates.
7299 TypeSet MemberPointerTypes;
7300
Douglas Gregora11693b2008-11-12 17:17:38 +00007301 /// EnumerationTypes - The set of enumeration types that will be
7302 /// used in the built-in candidates.
7303 TypeSet EnumerationTypes;
7304
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007305 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007306 /// candidates.
7307 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007308
7309 /// \brief A flag indicating non-record types are viable candidates
7310 bool HasNonRecordTypes;
7311
7312 /// \brief A flag indicating whether either arithmetic or enumeration types
7313 /// were present in the candidate set.
7314 bool HasArithmeticOrEnumeralTypes;
7315
Douglas Gregor80af3132011-05-21 23:15:46 +00007316 /// \brief A flag indicating whether the nullptr type was present in the
7317 /// candidate set.
7318 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007319
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007320 /// Sema - The semantic analysis instance where we are building the
7321 /// candidate type set.
7322 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007323
Douglas Gregora11693b2008-11-12 17:17:38 +00007324 /// Context - The AST context in which we will build the type sets.
7325 ASTContext &Context;
7326
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007327 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7328 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007329 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007330
7331public:
7332 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007333 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007334
Mike Stump11289f42009-09-09 15:08:12 +00007335 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007336 : HasNonRecordTypes(false),
7337 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007338 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007339 SemaRef(SemaRef),
7340 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007341
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007343 SourceLocation Loc,
7344 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007345 bool AllowExplicitConversions,
7346 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007347
7348 /// pointer_begin - First pointer type found;
7349 iterator pointer_begin() { return PointerTypes.begin(); }
7350
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007351 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007352 iterator pointer_end() { return PointerTypes.end(); }
7353
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007354 /// member_pointer_begin - First member pointer type found;
7355 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7356
7357 /// member_pointer_end - Past the last member pointer type found;
7358 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7359
Douglas Gregora11693b2008-11-12 17:17:38 +00007360 /// enumeration_begin - First enumeration type found;
7361 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7362
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007363 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007364 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007365
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007366 iterator vector_begin() { return VectorTypes.begin(); }
7367 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007368
7369 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7370 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007371 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007372};
7373
Craig Toppercd7b0332013-07-01 06:29:40 +00007374} // end anonymous namespace
7375
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007376/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007377/// the set of pointer types along with any more-qualified variants of
7378/// that type. For example, if @p Ty is "int const *", this routine
7379/// will add "int const *", "int const volatile *", "int const
7380/// restrict *", and "int const volatile restrict *" to the set of
7381/// pointer types. Returns true if the add of @p Ty itself succeeded,
7382/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007383///
7384/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007385bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007386BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7387 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007388
Douglas Gregora11693b2008-11-12 17:17:38 +00007389 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007390 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007391 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007392
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007393 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007394 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007395 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007396 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007397 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7398 PointeeTy = PTy->getPointeeType();
7399 buildObjCPtr = true;
7400 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007401 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007402 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007403
Sebastian Redl4990a632009-11-18 20:39:26 +00007404 // Don't add qualified variants of arrays. For one, they're not allowed
7405 // (the qualifier would sink to the element type), and for another, the
7406 // only overload situation where it matters is subscript or pointer +- int,
7407 // and those shouldn't have qualifier variants anyway.
7408 if (PointeeTy->isArrayType())
7409 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007410
John McCall8ccfcb52009-09-24 19:53:00 +00007411 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007412 bool hasVolatile = VisibleQuals.hasVolatile();
7413 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414
John McCall8ccfcb52009-09-24 19:53:00 +00007415 // Iterate through all strict supersets of BaseCVR.
7416 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7417 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007418 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007419 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007420
Douglas Gregor5bee2582012-06-04 00:15:09 +00007421 // Skip over restrict if no restrict found anywhere in the types, or if
7422 // the type cannot be restrict-qualified.
7423 if ((CVR & Qualifiers::Restrict) &&
7424 (!hasRestrict ||
7425 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7426 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007427
Douglas Gregor5bee2582012-06-04 00:15:09 +00007428 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007429 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007430
Douglas Gregor5bee2582012-06-04 00:15:09 +00007431 // Build qualified pointer type.
7432 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007433 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007434 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007435 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007436 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007437
Douglas Gregor5bee2582012-06-04 00:15:09 +00007438 // Insert qualified pointer type.
7439 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007440 }
7441
7442 return true;
7443}
7444
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007445/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7446/// to the set of pointer types along with any more-qualified variants of
7447/// that type. For example, if @p Ty is "int const *", this routine
7448/// will add "int const *", "int const volatile *", "int const
7449/// restrict *", and "int const volatile restrict *" to the set of
7450/// pointer types. Returns true if the add of @p Ty itself succeeded,
7451/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007452///
7453/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007454bool
7455BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7456 QualType Ty) {
7457 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007458 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007459 return false;
7460
John McCall8ccfcb52009-09-24 19:53:00 +00007461 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7462 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007463
John McCall8ccfcb52009-09-24 19:53:00 +00007464 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007465 // Don't add qualified variants of arrays. For one, they're not allowed
7466 // (the qualifier would sink to the element type), and for another, the
7467 // only overload situation where it matters is subscript or pointer +- int,
7468 // and those shouldn't have qualifier variants anyway.
7469 if (PointeeTy->isArrayType())
7470 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007471 const Type *ClassTy = PointerTy->getClass();
7472
7473 // Iterate through all strict supersets of the pointee type's CVR
7474 // qualifiers.
7475 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7476 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7477 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007478
John McCall8ccfcb52009-09-24 19:53:00 +00007479 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007480 MemberPointerTypes.insert(
7481 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007482 }
7483
7484 return true;
7485}
7486
Douglas Gregora11693b2008-11-12 17:17:38 +00007487/// AddTypesConvertedFrom - Add each of the types to which the type @p
7488/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007489/// primarily interested in pointer types and enumeration types. We also
7490/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007491/// AllowUserConversions is true if we should look at the conversion
7492/// functions of a class type, and AllowExplicitConversions if we
7493/// should also include the explicit conversion functions of a class
7494/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007495void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007496BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007497 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007498 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007499 bool AllowExplicitConversions,
7500 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007501 // Only deal with canonical types.
7502 Ty = Context.getCanonicalType(Ty);
7503
7504 // Look through reference types; they aren't part of the type of an
7505 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007506 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007507 Ty = RefTy->getPointeeType();
7508
John McCall33ddac02011-01-19 10:06:00 +00007509 // If we're dealing with an array type, decay to the pointer.
7510 if (Ty->isArrayType())
7511 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7512
7513 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007514 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007515
Chandler Carruth00a38332010-12-13 01:44:01 +00007516 // Flag if we ever add a non-record type.
7517 const RecordType *TyRec = Ty->getAs<RecordType>();
7518 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7519
Chandler Carruth00a38332010-12-13 01:44:01 +00007520 // Flag if we encounter an arithmetic type.
7521 HasArithmeticOrEnumeralTypes =
7522 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7523
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007524 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7525 PointerTypes.insert(Ty);
7526 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007527 // Insert our type, and its more-qualified variants, into the set
7528 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007529 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007530 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007531 } else if (Ty->isMemberPointerType()) {
7532 // Member pointers are far easier, since the pointee can't be converted.
7533 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7534 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007535 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007536 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007537 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007538 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007539 // We treat vector types as arithmetic types in many contexts as an
7540 // extension.
7541 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007542 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007543 } else if (Ty->isNullPtrType()) {
7544 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007545 } else if (AllowUserConversions && TyRec) {
7546 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007547 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007548 return;
Mike Stump11289f42009-09-09 15:08:12 +00007549
Chandler Carruth00a38332010-12-13 01:44:01 +00007550 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007551 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007552 if (isa<UsingShadowDecl>(D))
7553 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007554
Chandler Carruth00a38332010-12-13 01:44:01 +00007555 // Skip conversion function templates; they don't tell us anything
7556 // about which builtin types we can convert to.
7557 if (isa<FunctionTemplateDecl>(D))
7558 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007559
Chandler Carruth00a38332010-12-13 01:44:01 +00007560 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7561 if (AllowExplicitConversions || !Conv->isExplicit()) {
7562 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7563 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007564 }
7565 }
7566 }
7567}
7568
Douglas Gregor84605ae2009-08-24 13:43:27 +00007569/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7570/// the volatile- and non-volatile-qualified assignment operators for the
7571/// given type to the candidate set.
7572static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7573 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007574 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007575 OverloadCandidateSet &CandidateSet) {
7576 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007577
Douglas Gregor84605ae2009-08-24 13:43:27 +00007578 // T& operator=(T&, T)
7579 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7580 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007581 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007582 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007583
Douglas Gregor84605ae2009-08-24 13:43:27 +00007584 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7585 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007586 ParamTypes[0]
7587 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007588 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007589 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007590 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007591 }
7592}
Mike Stump11289f42009-09-09 15:08:12 +00007593
Sebastian Redl1054fae2009-10-25 17:03:50 +00007594/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7595/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007596static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7597 Qualifiers VRQuals;
7598 const RecordType *TyRec;
7599 if (const MemberPointerType *RHSMPType =
7600 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007601 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007602 else
7603 TyRec = ArgExpr->getType()->getAs<RecordType>();
7604 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007605 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007606 VRQuals.addVolatile();
7607 VRQuals.addRestrict();
7608 return VRQuals;
7609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007611 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007612 if (!ClassDecl->hasDefinition())
7613 return VRQuals;
7614
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007615 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007616 if (isa<UsingShadowDecl>(D))
7617 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7618 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007619 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7620 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7621 CanTy = ResTypeRef->getPointeeType();
7622 // Need to go down the pointer/mempointer chain and add qualifiers
7623 // as see them.
7624 bool done = false;
7625 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007626 if (CanTy.isRestrictQualified())
7627 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007628 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7629 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007630 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007631 CanTy->getAs<MemberPointerType>())
7632 CanTy = ResTypeMPtr->getPointeeType();
7633 else
7634 done = true;
7635 if (CanTy.isVolatileQualified())
7636 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007637 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7638 return VRQuals;
7639 }
7640 }
7641 }
7642 return VRQuals;
7643}
John McCall52872982010-11-13 05:51:15 +00007644
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007645namespace {
John McCall52872982010-11-13 05:51:15 +00007646
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007647/// \brief Helper class to manage the addition of builtin operator overload
7648/// candidates. It provides shared state and utility methods used throughout
7649/// the process, as well as a helper method to add each group of builtin
7650/// operator overloads from the standard to a candidate set.
7651class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007652 // Common instance state available to all overload candidate addition methods.
7653 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007654 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007655 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007656 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007657 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007658 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659
Hans Wennborg82371412017-11-15 17:11:53 +00007660 static constexpr int ArithmeticTypesCap = 24;
7661 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7662
7663 // Define some indices used to iterate over the arithemetic types in
7664 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
John McCall52872982010-11-13 05:51:15 +00007665 // types are that preserved by promotion (C++ [over.built]p2).
Hans Wennborg82371412017-11-15 17:11:53 +00007666 unsigned FirstIntegralType,
7667 LastIntegralType;
7668 unsigned FirstPromotedIntegralType,
7669 LastPromotedIntegralType;
7670 unsigned FirstPromotedArithmeticType,
7671 LastPromotedArithmeticType;
7672 unsigned NumArithmeticTypes;
John McCall52872982010-11-13 05:51:15 +00007673
Hans Wennborg82371412017-11-15 17:11:53 +00007674 void InitArithmeticTypes() {
7675 // Start of promoted types.
7676 FirstPromotedArithmeticType = 0;
7677 ArithmeticTypes.push_back(S.Context.FloatTy);
7678 ArithmeticTypes.push_back(S.Context.DoubleTy);
7679 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7680 if (S.Context.getTargetInfo().hasFloat128Type())
7681 ArithmeticTypes.push_back(S.Context.Float128Ty);
John McCall52872982010-11-13 05:51:15 +00007682
Hans Wennborg82371412017-11-15 17:11:53 +00007683 // Start of integral types.
7684 FirstIntegralType = ArithmeticTypes.size();
7685 FirstPromotedIntegralType = ArithmeticTypes.size();
7686 ArithmeticTypes.push_back(S.Context.IntTy);
7687 ArithmeticTypes.push_back(S.Context.LongTy);
7688 ArithmeticTypes.push_back(S.Context.LongLongTy);
7689 if (S.Context.getTargetInfo().hasInt128Type())
7690 ArithmeticTypes.push_back(S.Context.Int128Ty);
7691 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7692 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7693 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7694 if (S.Context.getTargetInfo().hasInt128Type())
7695 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7696 LastPromotedIntegralType = ArithmeticTypes.size();
7697 LastPromotedArithmeticType = ArithmeticTypes.size();
7698 // End of promoted types.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007699
Hans Wennborg82371412017-11-15 17:11:53 +00007700 ArithmeticTypes.push_back(S.Context.BoolTy);
7701 ArithmeticTypes.push_back(S.Context.CharTy);
7702 ArithmeticTypes.push_back(S.Context.WCharTy);
7703 ArithmeticTypes.push_back(S.Context.Char16Ty);
7704 ArithmeticTypes.push_back(S.Context.Char32Ty);
7705 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7706 ArithmeticTypes.push_back(S.Context.ShortTy);
7707 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7708 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7709 LastIntegralType = ArithmeticTypes.size();
7710 NumArithmeticTypes = ArithmeticTypes.size();
7711 // End of integral types.
7712 // FIXME: What about complex? What about half?
7713
7714 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7715 "Enough inline storage for all arithmetic types.");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007716 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007718 /// \brief Helper method to factor out the common pattern of adding overloads
7719 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007720 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007721 bool HasVolatile,
7722 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007723 QualType ParamTypes[2] = {
7724 S.Context.getLValueReferenceType(CandidateTy),
7725 S.Context.IntTy
7726 };
7727
7728 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007729 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007730
7731 // Use a heuristic to reduce number of builtin candidates in the set:
7732 // add volatile version only if there are conversions to a volatile type.
7733 if (HasVolatile) {
7734 ParamTypes[0] =
7735 S.Context.getLValueReferenceType(
7736 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007737 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007739
Douglas Gregor5bee2582012-06-04 00:15:09 +00007740 // Add restrict version only if there are conversions to a restrict type
7741 // and our candidate type is a non-restrict-qualified pointer.
7742 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7743 !CandidateTy.isRestrictQualified()) {
7744 ParamTypes[0]
7745 = S.Context.getLValueReferenceType(
7746 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007747 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007748
Douglas Gregor5bee2582012-06-04 00:15:09 +00007749 if (HasVolatile) {
7750 ParamTypes[0]
7751 = S.Context.getLValueReferenceType(
7752 S.Context.getCVRQualifiedType(CandidateTy,
7753 (Qualifiers::Volatile |
7754 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007755 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007756 }
7757 }
7758
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007759 }
7760
7761public:
7762 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007763 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007765 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007767 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007768 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007770 HasArithmeticOrEnumeralCandidateType(
7771 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007772 CandidateTypes(CandidateTypes),
7773 CandidateSet(CandidateSet) {
Hans Wennborg82371412017-11-15 17:11:53 +00007774
7775 InitArithmeticTypes();
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007776 }
7777
7778 // C++ [over.built]p3:
7779 //
7780 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7781 // is either volatile or empty, there exist candidate operator
7782 // functions of the form
7783 //
7784 // VQ T& operator++(VQ T&);
7785 // T operator++(VQ T&, int);
7786 //
7787 // C++ [over.built]p4:
7788 //
7789 // For every pair (T, VQ), where T is an arithmetic type other
7790 // than bool, and VQ is either volatile or empty, there exist
7791 // candidate operator functions of the form
7792 //
7793 // VQ T& operator--(VQ T&);
7794 // T operator--(VQ T&, int);
7795 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007796 if (!HasArithmeticOrEnumeralCandidateType)
7797 return;
7798
Jan Korousd74ebe22018-04-11 13:36:29 +00007799 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7800 const auto TypeOfT = ArithmeticTypes[Arith];
7801 if (Op == OO_MinusMinus && TypeOfT == S.Context.BoolTy)
7802 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007803 addPlusPlusMinusMinusStyleOverloads(
Jan Korousd74ebe22018-04-11 13:36:29 +00007804 TypeOfT,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007805 VisibleTypeConversionsQuals.hasVolatile(),
7806 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007807 }
7808 }
7809
7810 // C++ [over.built]p5:
7811 //
7812 // For every pair (T, VQ), where T is a cv-qualified or
7813 // cv-unqualified object type, and VQ is either volatile or
7814 // empty, there exist candidate operator functions of the form
7815 //
7816 // T*VQ& operator++(T*VQ&);
7817 // T*VQ& operator--(T*VQ&);
7818 // T* operator++(T*VQ&, int);
7819 // T* operator--(T*VQ&, int);
7820 void addPlusPlusMinusMinusPointerOverloads() {
7821 for (BuiltinCandidateTypeSet::iterator
7822 Ptr = CandidateTypes[0].pointer_begin(),
7823 PtrEnd = CandidateTypes[0].pointer_end();
7824 Ptr != PtrEnd; ++Ptr) {
7825 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007826 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007827 continue;
7828
7829 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007830 (!(*Ptr).isVolatileQualified() &&
7831 VisibleTypeConversionsQuals.hasVolatile()),
7832 (!(*Ptr).isRestrictQualified() &&
7833 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007834 }
7835 }
7836
7837 // C++ [over.built]p6:
7838 // For every cv-qualified or cv-unqualified object type T, there
7839 // exist candidate operator functions of the form
7840 //
7841 // T& operator*(T*);
7842 //
7843 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007844 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007845 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 // T& operator*(T*);
7847 void addUnaryStarPointerOverloads() {
7848 for (BuiltinCandidateTypeSet::iterator
7849 Ptr = CandidateTypes[0].pointer_begin(),
7850 PtrEnd = CandidateTypes[0].pointer_end();
7851 Ptr != PtrEnd; ++Ptr) {
7852 QualType ParamTy = *Ptr;
7853 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007854 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7855 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007856
Douglas Gregor02824322011-01-26 19:30:28 +00007857 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7858 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7859 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860
George Burgess IVc07c3892017-06-08 18:19:25 +00007861 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007862 }
7863 }
7864
7865 // C++ [over.built]p9:
7866 // For every promoted arithmetic type T, there exist candidate
7867 // operator functions of the form
7868 //
7869 // T operator+(T);
7870 // T operator-(T);
7871 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007872 if (!HasArithmeticOrEnumeralCandidateType)
7873 return;
7874
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007875 for (unsigned Arith = FirstPromotedArithmeticType;
7876 Arith < LastPromotedArithmeticType; ++Arith) {
Hans Wennborg82371412017-11-15 17:11:53 +00007877 QualType ArithTy = ArithmeticTypes[Arith];
George Burgess IVc07c3892017-06-08 18:19:25 +00007878 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 }
7880
7881 // Extension: We also add these operators for vector types.
7882 for (BuiltinCandidateTypeSet::iterator
7883 Vec = CandidateTypes[0].vector_begin(),
7884 VecEnd = CandidateTypes[0].vector_end();
7885 Vec != VecEnd; ++Vec) {
7886 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007887 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 }
7889 }
7890
7891 // C++ [over.built]p8:
7892 // For every type T, there exist candidate operator functions of
7893 // the form
7894 //
7895 // T* operator+(T*);
7896 void addUnaryPlusPointerOverloads() {
7897 for (BuiltinCandidateTypeSet::iterator
7898 Ptr = CandidateTypes[0].pointer_begin(),
7899 PtrEnd = CandidateTypes[0].pointer_end();
7900 Ptr != PtrEnd; ++Ptr) {
7901 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007902 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007903 }
7904 }
7905
7906 // C++ [over.built]p10:
7907 // For every promoted integral type T, there exist candidate
7908 // operator functions of the form
7909 //
7910 // T operator~(T);
7911 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007912 if (!HasArithmeticOrEnumeralCandidateType)
7913 return;
7914
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007915 for (unsigned Int = FirstPromotedIntegralType;
7916 Int < LastPromotedIntegralType; ++Int) {
Hans Wennborg82371412017-11-15 17:11:53 +00007917 QualType IntTy = ArithmeticTypes[Int];
George Burgess IVc07c3892017-06-08 18:19:25 +00007918 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007919 }
7920
7921 // Extension: We also add this operator for vector types.
7922 for (BuiltinCandidateTypeSet::iterator
7923 Vec = CandidateTypes[0].vector_begin(),
7924 VecEnd = CandidateTypes[0].vector_end();
7925 Vec != VecEnd; ++Vec) {
7926 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007927 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007928 }
7929 }
7930
7931 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007932 // For every pointer to member type T or type std::nullptr_t, there
7933 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007934 //
7935 // bool operator==(T,T);
7936 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007937 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007938 /// Set of (canonical) types that we've already handled.
7939 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7940
Richard Smithe54c3072013-05-05 15:51:06 +00007941 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007942 for (BuiltinCandidateTypeSet::iterator
7943 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7944 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7945 MemPtr != MemPtrEnd;
7946 ++MemPtr) {
7947 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007948 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007949 continue;
7950
7951 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007952 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007953 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007954
7955 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7956 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7957 if (AddedTypes.insert(NullPtrTy).second) {
7958 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007960 }
7961 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007962 }
7963 }
7964
7965 // C++ [over.built]p15:
7966 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007967 // For every T, where T is an enumeration type or a pointer type,
7968 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007969 //
7970 // bool operator<(T, T);
7971 // bool operator>(T, T);
7972 // bool operator<=(T, T);
7973 // bool operator>=(T, T);
7974 // bool operator==(T, T);
7975 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007976 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007977 // C++ [over.match.oper]p3:
7978 // [...]the built-in candidates include all of the candidate operator
7979 // functions defined in 13.6 that, compared to the given operator, [...]
7980 // do not have the same parameter-type-list as any non-template non-member
7981 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007982 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007983 // Note that in practice, this only affects enumeration types because there
7984 // aren't any built-in candidates of record type, and a user-defined operator
7985 // must have an operand of record or enumeration type. Also, the only other
7986 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007987 // cannot be overloaded for enumeration types, so this is the only place
7988 // where we must suppress candidates like this.
7989 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7990 UserDefinedBinaryOperators;
7991
Richard Smithe54c3072013-05-05 15:51:06 +00007992 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007993 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7994 CandidateTypes[ArgIdx].enumeration_end()) {
7995 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7996 CEnd = CandidateSet.end();
7997 C != CEnd; ++C) {
7998 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7999 continue;
8000
Eli Friedman14f082b2012-09-18 21:52:24 +00008001 if (C->Function->isFunctionTemplateSpecialization())
8002 continue;
8003
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008004 QualType FirstParamType =
8005 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8006 QualType SecondParamType =
8007 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8008
8009 // Skip if either parameter isn't of enumeral type.
8010 if (!FirstParamType->isEnumeralType() ||
8011 !SecondParamType->isEnumeralType())
8012 continue;
8013
8014 // Add this operator to the set of known user-defined operators.
8015 UserDefinedBinaryOperators.insert(
8016 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8017 S.Context.getCanonicalType(SecondParamType)));
8018 }
8019 }
8020 }
8021
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022 /// Set of (canonical) types that we've already handled.
8023 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8024
Richard Smithe54c3072013-05-05 15:51:06 +00008025 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 for (BuiltinCandidateTypeSet::iterator
8027 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8028 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8029 Ptr != PtrEnd; ++Ptr) {
8030 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008031 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 continue;
8033
8034 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008035 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008036 }
8037 for (BuiltinCandidateTypeSet::iterator
8038 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8039 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8040 Enum != EnumEnd; ++Enum) {
8041 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8042
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008043 // Don't add the same builtin candidate twice, or if a user defined
8044 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008045 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008046 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8047 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008048 continue;
8049
8050 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008051 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 }
8053 }
8054 }
8055
8056 // C++ [over.built]p13:
8057 //
8058 // For every cv-qualified or cv-unqualified object type T
8059 // there exist candidate operator functions of the form
8060 //
8061 // T* operator+(T*, ptrdiff_t);
8062 // T& operator[](T*, ptrdiff_t); [BELOW]
8063 // T* operator-(T*, ptrdiff_t);
8064 // T* operator+(ptrdiff_t, T*);
8065 // T& operator[](ptrdiff_t, T*); [BELOW]
8066 //
8067 // C++ [over.built]p14:
8068 //
8069 // For every T, where T is a pointer to object type, there
8070 // exist candidate operator functions of the form
8071 //
8072 // ptrdiff_t operator-(T, T);
8073 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8074 /// Set of (canonical) types that we've already handled.
8075 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8076
8077 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008078 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008079 S.Context.getPointerDiffType(),
8080 S.Context.getPointerDiffType(),
8081 };
8082 for (BuiltinCandidateTypeSet::iterator
8083 Ptr = CandidateTypes[Arg].pointer_begin(),
8084 PtrEnd = CandidateTypes[Arg].pointer_end();
8085 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008086 QualType PointeeTy = (*Ptr)->getPointeeType();
8087 if (!PointeeTy->isObjectType())
8088 continue;
8089
Eric Christopher9207a522015-08-21 16:24:01 +00008090 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008091 if (Arg == 0 || Op == OO_Plus) {
8092 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8093 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008094 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008095 }
8096 if (Op == OO_Minus) {
8097 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008098 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008099 continue;
8100
8101 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008102 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 }
8104 }
8105 }
8106 }
8107
8108 // C++ [over.built]p12:
8109 //
8110 // For every pair of promoted arithmetic types L and R, there
8111 // exist candidate operator functions of the form
8112 //
8113 // LR operator*(L, R);
8114 // LR operator/(L, R);
8115 // LR operator+(L, R);
8116 // LR operator-(L, R);
8117 // bool operator<(L, R);
8118 // bool operator>(L, R);
8119 // bool operator<=(L, R);
8120 // bool operator>=(L, R);
8121 // bool operator==(L, R);
8122 // bool operator!=(L, R);
8123 //
8124 // where LR is the result of the usual arithmetic conversions
8125 // between types L and R.
8126 //
8127 // C++ [over.built]p24:
8128 //
8129 // For every pair of promoted arithmetic types L and R, there exist
8130 // candidate operator functions of the form
8131 //
8132 // LR operator?(bool, L, R);
8133 //
8134 // where LR is the result of the usual arithmetic conversions
8135 // between types L and R.
8136 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008137 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008138 if (!HasArithmeticOrEnumeralCandidateType)
8139 return;
8140
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008141 for (unsigned Left = FirstPromotedArithmeticType;
8142 Left < LastPromotedArithmeticType; ++Left) {
8143 for (unsigned Right = FirstPromotedArithmeticType;
8144 Right < LastPromotedArithmeticType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008145 QualType LandR[2] = { ArithmeticTypes[Left],
8146 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008147 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008148 }
8149 }
8150
8151 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8152 // conditional operator for vector types.
8153 for (BuiltinCandidateTypeSet::iterator
8154 Vec1 = CandidateTypes[0].vector_begin(),
8155 Vec1End = CandidateTypes[0].vector_end();
8156 Vec1 != Vec1End; ++Vec1) {
8157 for (BuiltinCandidateTypeSet::iterator
8158 Vec2 = CandidateTypes[1].vector_begin(),
8159 Vec2End = CandidateTypes[1].vector_end();
8160 Vec2 != Vec2End; ++Vec2) {
8161 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008162 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 }
8164 }
8165 }
8166
8167 // C++ [over.built]p17:
8168 //
8169 // For every pair of promoted integral types L and R, there
8170 // exist candidate operator functions of the form
8171 //
8172 // LR operator%(L, R);
8173 // LR operator&(L, R);
8174 // LR operator^(L, R);
8175 // LR operator|(L, R);
8176 // L operator<<(L, R);
8177 // L operator>>(L, R);
8178 //
8179 // where LR is the result of the usual arithmetic conversions
8180 // between types L and R.
8181 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008182 if (!HasArithmeticOrEnumeralCandidateType)
8183 return;
8184
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008185 for (unsigned Left = FirstPromotedIntegralType;
8186 Left < LastPromotedIntegralType; ++Left) {
8187 for (unsigned Right = FirstPromotedIntegralType;
8188 Right < LastPromotedIntegralType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008189 QualType LandR[2] = { ArithmeticTypes[Left],
8190 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008191 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 }
8193 }
8194 }
8195
8196 // C++ [over.built]p20:
8197 //
8198 // For every pair (T, VQ), where T is an enumeration or
8199 // pointer to member type and VQ is either volatile or
8200 // empty, there exist candidate operator functions of the form
8201 //
8202 // VQ T& operator=(VQ T&, T);
8203 void addAssignmentMemberPointerOrEnumeralOverloads() {
8204 /// Set of (canonical) types that we've already handled.
8205 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8206
8207 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8208 for (BuiltinCandidateTypeSet::iterator
8209 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8210 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8211 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008212 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213 continue;
8214
Richard Smithe54c3072013-05-05 15:51:06 +00008215 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 }
8217
8218 for (BuiltinCandidateTypeSet::iterator
8219 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8220 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8221 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008222 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008223 continue;
8224
Richard Smithe54c3072013-05-05 15:51:06 +00008225 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 }
8227 }
8228 }
8229
8230 // C++ [over.built]p19:
8231 //
8232 // For every pair (T, VQ), where T is any type and VQ is either
8233 // volatile or empty, there exist candidate operator functions
8234 // of the form
8235 //
8236 // T*VQ& operator=(T*VQ&, T*);
8237 //
8238 // C++ [over.built]p21:
8239 //
8240 // For every pair (T, VQ), where T is a cv-qualified or
8241 // cv-unqualified object type and VQ is either volatile or
8242 // empty, there exist candidate operator functions of the form
8243 //
8244 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8245 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8246 void addAssignmentPointerOverloads(bool isEqualOp) {
8247 /// Set of (canonical) types that we've already handled.
8248 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8249
8250 for (BuiltinCandidateTypeSet::iterator
8251 Ptr = CandidateTypes[0].pointer_begin(),
8252 PtrEnd = CandidateTypes[0].pointer_end();
8253 Ptr != PtrEnd; ++Ptr) {
8254 // If this is operator=, keep track of the builtin candidates we added.
8255 if (isEqualOp)
8256 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008257 else if (!(*Ptr)->getPointeeType()->isObjectType())
8258 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008259
8260 // non-volatile version
8261 QualType ParamTypes[2] = {
8262 S.Context.getLValueReferenceType(*Ptr),
8263 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8264 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008265 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008266 /*IsAssigmentOperator=*/ isEqualOp);
8267
Douglas Gregor5bee2582012-06-04 00:15:09 +00008268 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8269 VisibleTypeConversionsQuals.hasVolatile();
8270 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008271 // volatile version
8272 ParamTypes[0] =
8273 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008274 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008275 /*IsAssigmentOperator=*/isEqualOp);
8276 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008277
Douglas Gregor5bee2582012-06-04 00:15:09 +00008278 if (!(*Ptr).isRestrictQualified() &&
8279 VisibleTypeConversionsQuals.hasRestrict()) {
8280 // restrict version
8281 ParamTypes[0]
8282 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008283 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008284 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008285
Douglas Gregor5bee2582012-06-04 00:15:09 +00008286 if (NeedVolatile) {
8287 // volatile restrict version
8288 ParamTypes[0]
8289 = S.Context.getLValueReferenceType(
8290 S.Context.getCVRQualifiedType(*Ptr,
8291 (Qualifiers::Volatile |
8292 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008293 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008294 /*IsAssigmentOperator=*/isEqualOp);
8295 }
8296 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008297 }
8298
8299 if (isEqualOp) {
8300 for (BuiltinCandidateTypeSet::iterator
8301 Ptr = CandidateTypes[1].pointer_begin(),
8302 PtrEnd = CandidateTypes[1].pointer_end();
8303 Ptr != PtrEnd; ++Ptr) {
8304 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008305 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008306 continue;
8307
Chandler Carruth8e543b32010-12-12 08:17:55 +00008308 QualType ParamTypes[2] = {
8309 S.Context.getLValueReferenceType(*Ptr),
8310 *Ptr,
8311 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008312
8313 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008314 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 /*IsAssigmentOperator=*/true);
8316
Douglas Gregor5bee2582012-06-04 00:15:09 +00008317 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8318 VisibleTypeConversionsQuals.hasVolatile();
8319 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008320 // volatile version
8321 ParamTypes[0] =
8322 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008323 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008324 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008326
Douglas Gregor5bee2582012-06-04 00:15:09 +00008327 if (!(*Ptr).isRestrictQualified() &&
8328 VisibleTypeConversionsQuals.hasRestrict()) {
8329 // restrict version
8330 ParamTypes[0]
8331 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008332 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008333 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008334
Douglas Gregor5bee2582012-06-04 00:15:09 +00008335 if (NeedVolatile) {
8336 // volatile restrict version
8337 ParamTypes[0]
8338 = S.Context.getLValueReferenceType(
8339 S.Context.getCVRQualifiedType(*Ptr,
8340 (Qualifiers::Volatile |
8341 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008342 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008343 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008344 }
8345 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 }
8347 }
8348 }
8349
8350 // C++ [over.built]p18:
8351 //
8352 // For every triple (L, VQ, R), where L is an arithmetic type,
8353 // VQ is either volatile or empty, and R is a promoted
8354 // arithmetic type, there exist candidate operator functions of
8355 // the form
8356 //
8357 // VQ L& operator=(VQ L&, R);
8358 // VQ L& operator*=(VQ L&, R);
8359 // VQ L& operator/=(VQ L&, R);
8360 // VQ L& operator+=(VQ L&, R);
8361 // VQ L& operator-=(VQ L&, R);
8362 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008363 if (!HasArithmeticOrEnumeralCandidateType)
8364 return;
8365
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008366 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8367 for (unsigned Right = FirstPromotedArithmeticType;
8368 Right < LastPromotedArithmeticType; ++Right) {
8369 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008370 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008371
8372 // Add this built-in operator as a candidate (VQ is empty).
8373 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008374 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 /*IsAssigmentOperator=*/isEqualOp);
8377
8378 // Add this built-in operator as a candidate (VQ is 'volatile').
8379 if (VisibleTypeConversionsQuals.hasVolatile()) {
8380 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008381 S.Context.getVolatileType(ArithmeticTypes[Left]);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008383 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008384 /*IsAssigmentOperator=*/isEqualOp);
8385 }
8386 }
8387 }
8388
8389 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8390 for (BuiltinCandidateTypeSet::iterator
8391 Vec1 = CandidateTypes[0].vector_begin(),
8392 Vec1End = CandidateTypes[0].vector_end();
8393 Vec1 != Vec1End; ++Vec1) {
8394 for (BuiltinCandidateTypeSet::iterator
8395 Vec2 = CandidateTypes[1].vector_begin(),
8396 Vec2End = CandidateTypes[1].vector_end();
8397 Vec2 != Vec2End; ++Vec2) {
8398 QualType ParamTypes[2];
8399 ParamTypes[1] = *Vec2;
8400 // Add this built-in operator as a candidate (VQ is empty).
8401 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008402 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403 /*IsAssigmentOperator=*/isEqualOp);
8404
8405 // Add this built-in operator as a candidate (VQ is 'volatile').
8406 if (VisibleTypeConversionsQuals.hasVolatile()) {
8407 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8408 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008409 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008410 /*IsAssigmentOperator=*/isEqualOp);
8411 }
8412 }
8413 }
8414 }
8415
8416 // C++ [over.built]p22:
8417 //
8418 // For every triple (L, VQ, R), where L is an integral type, VQ
8419 // is either volatile or empty, and R is a promoted integral
8420 // type, there exist candidate operator functions of the form
8421 //
8422 // VQ L& operator%=(VQ L&, R);
8423 // VQ L& operator<<=(VQ L&, R);
8424 // VQ L& operator>>=(VQ L&, R);
8425 // VQ L& operator&=(VQ L&, R);
8426 // VQ L& operator^=(VQ L&, R);
8427 // VQ L& operator|=(VQ L&, R);
8428 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008429 if (!HasArithmeticOrEnumeralCandidateType)
8430 return;
8431
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008432 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8433 for (unsigned Right = FirstPromotedIntegralType;
8434 Right < LastPromotedIntegralType; ++Right) {
8435 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008436 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437
8438 // Add this built-in operator as a candidate (VQ is empty).
8439 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008440 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008442 if (VisibleTypeConversionsQuals.hasVolatile()) {
8443 // Add this built-in operator as a candidate (VQ is 'volatile').
Hans Wennborg82371412017-11-15 17:11:53 +00008444 ParamTypes[0] = ArithmeticTypes[Left];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008445 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8446 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008447 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008448 }
8449 }
8450 }
8451 }
8452
8453 // C++ [over.operator]p23:
8454 //
8455 // There also exist candidate operator functions of the form
8456 //
8457 // bool operator!(bool);
8458 // bool operator&&(bool, bool);
8459 // bool operator||(bool, bool);
8460 void addExclaimOverload() {
8461 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008462 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008463 /*IsAssignmentOperator=*/false,
8464 /*NumContextualBoolArguments=*/1);
8465 }
8466 void addAmpAmpOrPipePipeOverload() {
8467 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008469 /*IsAssignmentOperator=*/false,
8470 /*NumContextualBoolArguments=*/2);
8471 }
8472
8473 // C++ [over.built]p13:
8474 //
8475 // For every cv-qualified or cv-unqualified object type T there
8476 // exist candidate operator functions of the form
8477 //
8478 // T* operator+(T*, ptrdiff_t); [ABOVE]
8479 // T& operator[](T*, ptrdiff_t);
8480 // T* operator-(T*, ptrdiff_t); [ABOVE]
8481 // T* operator+(ptrdiff_t, T*); [ABOVE]
8482 // T& operator[](ptrdiff_t, T*);
8483 void addSubscriptOverloads() {
8484 for (BuiltinCandidateTypeSet::iterator
8485 Ptr = CandidateTypes[0].pointer_begin(),
8486 PtrEnd = CandidateTypes[0].pointer_end();
8487 Ptr != PtrEnd; ++Ptr) {
8488 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8489 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008490 if (!PointeeType->isObjectType())
8491 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008492
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008493 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008494 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008495 }
8496
8497 for (BuiltinCandidateTypeSet::iterator
8498 Ptr = CandidateTypes[1].pointer_begin(),
8499 PtrEnd = CandidateTypes[1].pointer_end();
8500 Ptr != PtrEnd; ++Ptr) {
8501 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8502 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008503 if (!PointeeType->isObjectType())
8504 continue;
8505
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008506 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008507 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008508 }
8509 }
8510
8511 // C++ [over.built]p11:
8512 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8513 // C1 is the same type as C2 or is a derived class of C2, T is an object
8514 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8515 // there exist candidate operator functions of the form
8516 //
8517 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8518 //
8519 // where CV12 is the union of CV1 and CV2.
8520 void addArrowStarOverloads() {
8521 for (BuiltinCandidateTypeSet::iterator
8522 Ptr = CandidateTypes[0].pointer_begin(),
8523 PtrEnd = CandidateTypes[0].pointer_end();
8524 Ptr != PtrEnd; ++Ptr) {
8525 QualType C1Ty = (*Ptr);
8526 QualType C1;
8527 QualifierCollector Q1;
8528 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8529 if (!isa<RecordType>(C1))
8530 continue;
8531 // heuristic to reduce number of builtin candidates in the set.
8532 // Add volatile/restrict version only if there are conversions to a
8533 // volatile/restrict type.
8534 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8535 continue;
8536 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8537 continue;
8538 for (BuiltinCandidateTypeSet::iterator
8539 MemPtr = CandidateTypes[1].member_pointer_begin(),
8540 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8541 MemPtr != MemPtrEnd; ++MemPtr) {
8542 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8543 QualType C2 = QualType(mptr->getClass(), 0);
8544 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008545 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008546 break;
8547 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8548 // build CV12 T&
8549 QualType T = mptr->getPointeeType();
8550 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8551 T.isVolatileQualified())
8552 continue;
8553 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8554 T.isRestrictQualified())
8555 continue;
8556 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008557 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008558 }
8559 }
8560 }
8561
8562 // Note that we don't consider the first argument, since it has been
8563 // contextually converted to bool long ago. The candidates below are
8564 // therefore added as binary.
8565 //
8566 // C++ [over.built]p25:
8567 // For every type T, where T is a pointer, pointer-to-member, or scoped
8568 // enumeration type, there exist candidate operator functions of the form
8569 //
8570 // T operator?(bool, T, T);
8571 //
8572 void addConditionalOperatorOverloads() {
8573 /// Set of (canonical) types that we've already handled.
8574 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8575
8576 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8577 for (BuiltinCandidateTypeSet::iterator
8578 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8579 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8580 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008581 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008582 continue;
8583
8584 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008585 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008586 }
8587
8588 for (BuiltinCandidateTypeSet::iterator
8589 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8590 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8591 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008592 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008593 continue;
8594
8595 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008597 }
8598
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008599 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008600 for (BuiltinCandidateTypeSet::iterator
8601 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8602 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8603 Enum != EnumEnd; ++Enum) {
8604 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8605 continue;
8606
David Blaikie82e95a32014-11-19 07:49:47 +00008607 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008608 continue;
8609
8610 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008611 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008612 }
8613 }
8614 }
8615 }
8616};
8617
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008618} // end anonymous namespace
8619
8620/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8621/// operator overloads to the candidate set (C++ [over.built]), based
8622/// on the operator @p Op and the arguments given. For example, if the
8623/// operator is a binary '+', this routine might add "int
8624/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008625void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8626 SourceLocation OpLoc,
8627 ArrayRef<Expr *> Args,
8628 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008629 // Find all of the types that the arguments can convert to, but only
8630 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008631 // that make use of these types. Also record whether we encounter non-record
8632 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008633 Qualifiers VisibleTypeConversionsQuals;
8634 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008635 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008636 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008637
8638 bool HasNonRecordCandidateType = false;
8639 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008640 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008641 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008642 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008643 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8644 OpLoc,
8645 true,
8646 (Op == OO_Exclaim ||
8647 Op == OO_AmpAmp ||
8648 Op == OO_PipePipe),
8649 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008650 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8651 CandidateTypes[ArgIdx].hasNonRecordTypes();
8652 HasArithmeticOrEnumeralCandidateType =
8653 HasArithmeticOrEnumeralCandidateType ||
8654 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008655 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008656
Chandler Carruth00a38332010-12-13 01:44:01 +00008657 // Exit early when no non-record types have been added to the candidate set
8658 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008659 //
8660 // We can't exit early for !, ||, or &&, since there we have always have
8661 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008662 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008663 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008664 return;
8665
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008666 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008667 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008668 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008669 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008670 CandidateTypes, CandidateSet);
8671
8672 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008673 switch (Op) {
8674 case OO_None:
8675 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008676 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008677
Chandler Carruth5184de02010-12-12 08:51:33 +00008678 case OO_New:
8679 case OO_Delete:
8680 case OO_Array_New:
8681 case OO_Array_Delete:
8682 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008683 llvm_unreachable(
8684 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008685
8686 case OO_Comma:
8687 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008688 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008689 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008690 // -- For the operator ',', the unary operator '&', the
8691 // operator '->', or the operator 'co_await', the
8692 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008693 break;
8694
8695 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008696 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008697 OpBuilder.addUnaryPlusPointerOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008698 LLVM_FALLTHROUGH;
Douglas Gregord08452f2008-11-19 15:42:04 +00008699
8700 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008701 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008702 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008703 } else {
8704 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008705 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008706 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008707 break;
8708
Chandler Carruth5184de02010-12-12 08:51:33 +00008709 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008710 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008711 OpBuilder.addUnaryStarPointerOverloads();
8712 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008713 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008714 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008715
Chandler Carruth5184de02010-12-12 08:51:33 +00008716 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008717 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008718 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008719
8720 case OO_PlusPlus:
8721 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008722 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8723 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008724 break;
8725
Douglas Gregor84605ae2009-08-24 13:43:27 +00008726 case OO_EqualEqual:
8727 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008728 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008729 LLVM_FALLTHROUGH;
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008730
Douglas Gregora11693b2008-11-12 17:17:38 +00008731 case OO_Less:
8732 case OO_Greater:
8733 case OO_LessEqual:
8734 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008735 OpBuilder.addRelationalPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008736 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008737 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008738
Richard Smithd30b23d2017-12-01 02:13:10 +00008739 case OO_Spaceship:
8740 llvm_unreachable("<=> expressions not supported yet");
8741
Douglas Gregora11693b2008-11-12 17:17:38 +00008742 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008743 case OO_Caret:
8744 case OO_Pipe:
8745 case OO_LessLess:
8746 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008747 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008748 break;
8749
Chandler Carruth5184de02010-12-12 08:51:33 +00008750 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008751 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008752 // C++ [over.match.oper]p3:
8753 // -- For the operator ',', the unary operator '&', or the
8754 // operator '->', the built-in candidates set is empty.
8755 break;
8756
8757 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8758 break;
8759
8760 case OO_Tilde:
8761 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8762 break;
8763
Douglas Gregora11693b2008-11-12 17:17:38 +00008764 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008765 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008766 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008767
8768 case OO_PlusEqual:
8769 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008770 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008771 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008772
8773 case OO_StarEqual:
8774 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008775 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008776 break;
8777
8778 case OO_PercentEqual:
8779 case OO_LessLessEqual:
8780 case OO_GreaterGreaterEqual:
8781 case OO_AmpEqual:
8782 case OO_CaretEqual:
8783 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008784 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008785 break;
8786
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008787 case OO_Exclaim:
8788 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008789 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008790
Douglas Gregora11693b2008-11-12 17:17:38 +00008791 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008792 case OO_PipePipe:
8793 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008794 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008795
8796 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008797 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008798 break;
8799
8800 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008801 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008802 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008803
8804 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008805 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008806 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008807 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008808 }
8809}
8810
Douglas Gregore254f902009-02-04 00:32:51 +00008811/// \brief Add function candidates found via argument-dependent lookup
8812/// to the set of overloading candidates.
8813///
8814/// This routine performs argument-dependent name lookup based on the
8815/// given function name (which may also be an operator name) and adds
8816/// all of the overload candidates found by ADL to the overload
8817/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008818void
Douglas Gregore254f902009-02-04 00:32:51 +00008819Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008820 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008821 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008822 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008823 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008824 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008825 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008826
John McCall91f61fc2010-01-26 06:04:06 +00008827 // FIXME: This approach for uniquing ADL results (and removing
8828 // redundant candidates from the set) relies on pointer-equality,
8829 // which means we need to key off the canonical decl. However,
8830 // always going back to the canonical decl might not get us the
8831 // right set of default arguments. What default arguments are
8832 // we supposed to consider on ADL candidates, anyway?
8833
Douglas Gregorcabea402009-09-22 15:41:20 +00008834 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008835 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008836
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008837 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008838 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8839 CandEnd = CandidateSet.end();
8840 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008841 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008842 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008843 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008844 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008845 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008846
8847 // For each of the ADL candidates we found, add it to the overload
8848 // set.
John McCall8fe68082010-01-26 07:16:45 +00008849 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008850 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008851 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008852 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008853 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008854
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008855 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8856 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008857 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008858 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008859 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008860 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008861 }
Douglas Gregore254f902009-02-04 00:32:51 +00008862}
8863
George Burgess IV3dc166912016-05-10 01:59:34 +00008864namespace {
8865enum class Comparison { Equal, Better, Worse };
8866}
8867
8868/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8869/// overload resolution.
8870///
8871/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8872/// Cand1's first N enable_if attributes have precisely the same conditions as
8873/// Cand2's first N enable_if attributes (where N = the number of enable_if
8874/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8875///
8876/// Note that you can have a pair of candidates such that Cand1's enable_if
8877/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8878/// worse than Cand1's.
8879static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8880 const FunctionDecl *Cand2) {
8881 // Common case: One (or both) decls don't have enable_if attrs.
8882 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8883 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8884 if (!Cand1Attr || !Cand2Attr) {
8885 if (Cand1Attr == Cand2Attr)
8886 return Comparison::Equal;
8887 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8888 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008889
8890 // FIXME: The next several lines are just
8891 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8892 // instead of reverse order which is how they're stored in the AST.
8893 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8894 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8895
George Burgess IV3dc166912016-05-10 01:59:34 +00008896 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8897 // has fewer enable_if attributes than Cand2.
8898 if (Cand1Attrs.size() < Cand2Attrs.size())
8899 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008900
8901 auto Cand1I = Cand1Attrs.begin();
8902 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8903 for (auto &Cand2A : Cand2Attrs) {
8904 Cand1ID.clear();
8905 Cand2ID.clear();
8906
8907 auto &Cand1A = *Cand1I++;
8908 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8909 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8910 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008911 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008912 }
8913
George Burgess IV3dc166912016-05-10 01:59:34 +00008914 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008915}
8916
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008917/// isBetterOverloadCandidate - Determines whether the first overload
8918/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00008919bool clang::isBetterOverloadCandidate(
8920 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8921 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008922 // Define viable functions to be better candidates than non-viable
8923 // functions.
8924 if (!Cand2.Viable)
8925 return Cand1.Viable;
8926 else if (!Cand1.Viable)
8927 return false;
8928
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008929 // C++ [over.match.best]p1:
8930 //
8931 // -- if F is a static member function, ICS1(F) is defined such
8932 // that ICS1(F) is neither better nor worse than ICS1(G) for
8933 // any function G, and, symmetrically, ICS1(G) is neither
8934 // better nor worse than ICS1(F).
8935 unsigned StartArg = 0;
8936 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8937 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008938
George Burgess IVfbad5b22016-09-07 20:03:19 +00008939 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8940 // We don't allow incompatible pointer conversions in C++.
8941 if (!S.getLangOpts().CPlusPlus)
8942 return ICS.isStandard() &&
8943 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8944
8945 // The only ill-formed conversion we allow in C++ is the string literal to
8946 // char* conversion, which is only considered ill-formed after C++11.
8947 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8948 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8949 };
8950
8951 // Define functions that don't require ill-formed conversions for a given
8952 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008953 unsigned NumArgs = Cand1.Conversions.size();
8954 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008955 bool HasBetterConversion = false;
8956 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8957 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8958 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8959 if (Cand1Bad != Cand2Bad) {
8960 if (Cand1Bad)
8961 return false;
8962 HasBetterConversion = true;
8963 }
8964 }
8965
8966 if (HasBetterConversion)
8967 return true;
8968
Douglas Gregord3cb3562009-07-07 23:38:56 +00008969 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008970 // A viable function F1 is defined to be a better function than another
8971 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008972 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008973 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008974 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008975 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008976 Cand2.Conversions[ArgIdx])) {
8977 case ImplicitConversionSequence::Better:
8978 // Cand1 has a better conversion sequence.
8979 HasBetterConversion = true;
8980 break;
8981
8982 case ImplicitConversionSequence::Worse:
8983 // Cand1 can't be better than Cand2.
8984 return false;
8985
8986 case ImplicitConversionSequence::Indistinguishable:
8987 // Do nothing.
8988 break;
8989 }
8990 }
8991
Mike Stump11289f42009-09-09 15:08:12 +00008992 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008993 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008994 if (HasBetterConversion)
8995 return true;
8996
Douglas Gregora1f013e2008-11-07 22:36:19 +00008997 // -- the context is an initialization by user-defined conversion
8998 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8999 // from the return type of F1 to the destination type (i.e.,
9000 // the type of the entity being initialized) is a better
9001 // conversion sequence than the standard conversion sequence
9002 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00009003 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9004 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009005 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009006 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009007 // First check whether we prefer one of the conversion functions over the
9008 // other. This only distinguishes the results in non-standard, extension
9009 // cases such as the conversion from a lambda closure type to a function
9010 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009011 ImplicitConversionSequence::CompareKind Result =
9012 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9013 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009014 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009015 Cand1.FinalConversion,
9016 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009017
Richard Smithec2748a2014-05-17 04:36:39 +00009018 if (Result != ImplicitConversionSequence::Indistinguishable)
9019 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009020
9021 // FIXME: Compare kind of reference binding if conversion functions
9022 // convert to a reference type used in direct reference binding, per
9023 // C++14 [over.match.best]p1 section 2 bullet 3.
9024 }
9025
Richard Smith51731362017-11-01 01:37:11 +00009026 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9027 // as combined with the resolution to CWG issue 243.
9028 //
9029 // When the context is initialization by constructor ([over.match.ctor] or
9030 // either phase of [over.match.list]), a constructor is preferred over
9031 // a conversion function.
9032 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9033 Cand1.Function && Cand2.Function &&
9034 isa<CXXConstructorDecl>(Cand1.Function) !=
9035 isa<CXXConstructorDecl>(Cand2.Function))
9036 return isa<CXXConstructorDecl>(Cand1.Function);
9037
Richard Smith6fdeaab2014-05-17 01:58:45 +00009038 // -- F1 is a non-template function and F2 is a function template
9039 // specialization, or, if not that,
9040 bool Cand1IsSpecialization = Cand1.Function &&
9041 Cand1.Function->getPrimaryTemplate();
9042 bool Cand2IsSpecialization = Cand2.Function &&
9043 Cand2.Function->getPrimaryTemplate();
9044 if (Cand1IsSpecialization != Cand2IsSpecialization)
9045 return Cand2IsSpecialization;
9046
9047 // -- F1 and F2 are function template specializations, and the function
9048 // template for F1 is more specialized than the template for F2
9049 // according to the partial ordering rules described in 14.5.5.2, or,
9050 // if not that,
9051 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9052 if (FunctionTemplateDecl *BetterTemplate
9053 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9054 Cand2.Function->getPrimaryTemplate(),
9055 Loc,
9056 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9057 : TPOC_Call,
9058 Cand1.ExplicitCallArguments,
9059 Cand2.ExplicitCallArguments))
9060 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009061 }
9062
Richard Smith5179eb72016-06-28 19:03:57 +00009063 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9064 // A derived-class constructor beats an (inherited) base class constructor.
9065 bool Cand1IsInherited =
9066 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9067 bool Cand2IsInherited =
9068 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9069 if (Cand1IsInherited != Cand2IsInherited)
9070 return Cand2IsInherited;
9071 else if (Cand1IsInherited) {
9072 assert(Cand2IsInherited);
9073 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9074 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9075 if (Cand1Class->isDerivedFrom(Cand2Class))
9076 return true;
9077 if (Cand2Class->isDerivedFrom(Cand1Class))
9078 return false;
9079 // Inherited from sibling base classes: still ambiguous.
9080 }
9081
Faisal Vali81b756e2017-10-22 14:45:08 +00009082 // Check C++17 tie-breakers for deduction guides.
9083 {
9084 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9085 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9086 if (Guide1 && Guide2) {
9087 // -- F1 is generated from a deduction-guide and F2 is not
9088 if (Guide1->isImplicit() != Guide2->isImplicit())
9089 return Guide2->isImplicit();
9090
9091 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9092 if (Guide1->isCopyDeductionCandidate())
9093 return true;
9094 }
9095 }
Richard Smith67ef14f2017-09-26 18:37:55 +00009096
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009097 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009098 if (Cand1.Function && Cand2.Function) {
9099 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9100 if (Cmp != Comparison::Equal)
9101 return Cmp == Comparison::Better;
9102 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009103
Justin Lebar25c4a812016-03-29 16:24:16 +00009104 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009105 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9106 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9107 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9108 }
9109
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009110 bool HasPS1 = Cand1.Function != nullptr &&
9111 functionHasPassObjectSizeParams(Cand1.Function);
9112 bool HasPS2 = Cand2.Function != nullptr &&
9113 functionHasPassObjectSizeParams(Cand2.Function);
9114 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009115}
9116
Richard Smith2dbe4042015-11-04 19:26:32 +00009117/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009118/// name lookup and overload resolution. This applies when the same internal/no
9119/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009120/// the same header). In such a case, we don't consider the declarations to
9121/// declare the same entity, but we also don't want lookups with both
9122/// declarations visible to be ambiguous in some cases (this happens when using
9123/// a modularized libstdc++).
9124bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9125 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009126 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9127 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9128 if (!VA || !VB)
9129 return false;
9130
9131 // The declarations must be declaring the same name as an internal linkage
9132 // entity in different modules.
9133 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9134 VB->getDeclContext()->getRedeclContext()) ||
9135 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9136 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9137 VA->isExternallyVisible() || VB->isExternallyVisible())
9138 return false;
9139
9140 // Check that the declarations appear to be equivalent.
9141 //
9142 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9143 // For constants and functions, we should check the initializer or body is
9144 // the same. For non-constant variables, we shouldn't allow it at all.
9145 if (Context.hasSameType(VA->getType(), VB->getType()))
9146 return true;
9147
9148 // Enum constants within unnamed enumerations will have different types, but
9149 // may still be similar enough to be interchangeable for our purposes.
9150 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9151 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9152 // Only handle anonymous enums. If the enumerations were named and
9153 // equivalent, they would have been merged to the same type.
9154 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9155 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9156 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9157 !Context.hasSameType(EnumA->getIntegerType(),
9158 EnumB->getIntegerType()))
9159 return false;
9160 // Allow this only if the value is the same for both enumerators.
9161 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9162 }
9163 }
9164
9165 // Nothing else is sufficiently similar.
9166 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009167}
9168
9169void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9170 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9171 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9172
9173 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9174 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9175 << !M << (M ? M->getFullModuleName() : "");
9176
9177 for (auto *E : Equiv) {
9178 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9179 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9180 << !M << (M ? M->getFullModuleName() : "");
9181 }
Richard Smith896c66e2015-10-21 07:13:52 +00009182}
9183
Mike Stump11289f42009-09-09 15:08:12 +00009184/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009185/// within an overload candidate set.
9186///
James Dennettffad8b72012-06-22 08:10:18 +00009187/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009188/// which overload resolution occurs.
9189///
James Dennettffad8b72012-06-22 08:10:18 +00009190/// \param Best If overload resolution was successful or found a deleted
9191/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009192///
9193/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009194OverloadingResult
9195OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009196 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009197 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9198 std::transform(begin(), end(), std::back_inserter(Candidates),
9199 [](OverloadCandidate &Cand) { return &Cand; });
9200
Justin Lebar66a2ab92016-08-10 00:40:43 +00009201 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9202 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009203 // compilation mode only one call variant is viable. We need to
9204 // exclude non-viable overload candidates from consideration based
9205 // only on their host/device attributes. Specifically, if one
9206 // candidate call is WrongSide and the other is SameSide, we ignore
9207 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009208 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009209 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9210 bool ContainsSameSideCandidate =
9211 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9212 return Cand->Function &&
9213 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9214 Sema::CFP_SameSide;
9215 });
9216 if (ContainsSameSideCandidate) {
9217 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9218 return Cand->Function &&
9219 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9220 Sema::CFP_WrongSide;
9221 };
George Burgess IV8684b032017-01-04 19:16:29 +00009222 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009223 }
9224 }
9225
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009226 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009227 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009228 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009229 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009230 if (Best == end() ||
9231 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009232 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009233
9234 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009235 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009236 return OR_No_Viable_Function;
9237
Richard Smith2dbe4042015-11-04 19:26:32 +00009238 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009240 // Make sure that this function is better than every other viable
9241 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009242 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009243 if (Cand->Viable && Cand != Best &&
9244 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009245 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9246 Cand->Function)) {
9247 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009248 continue;
9249 }
9250
John McCall5c32be02010-08-24 20:38:10 +00009251 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009252 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009253 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009254 }
Mike Stump11289f42009-09-09 15:08:12 +00009255
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009256 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009257 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009258 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009259 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009260 return OR_Deleted;
9261
Richard Smith2dbe4042015-11-04 19:26:32 +00009262 if (!EquivalentCands.empty())
9263 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9264 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009266 return OR_Success;
9267}
9268
John McCall53262c92010-01-12 02:15:36 +00009269namespace {
9270
9271enum OverloadCandidateKind {
9272 oc_function,
9273 oc_method,
9274 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009275 oc_function_template,
9276 oc_method_template,
9277 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009278 oc_implicit_default_constructor,
9279 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009280 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009281 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009282 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009283 oc_inherited_constructor,
9284 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009285};
9286
George Burgess IVd66d37c2016-10-28 21:42:06 +00009287static OverloadCandidateKind
9288ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9289 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009290 bool isTemplate = false;
9291
9292 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9293 isTemplate = true;
9294 Description = S.getTemplateArgumentBindingsText(
9295 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9296 }
John McCallfd0b2f82010-01-06 09:43:14 +00009297
9298 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009299 if (!Ctor->isImplicit()) {
9300 if (isa<ConstructorUsingShadowDecl>(Found))
9301 return isTemplate ? oc_inherited_constructor_template
9302 : oc_inherited_constructor;
9303 else
9304 return isTemplate ? oc_constructor_template : oc_constructor;
9305 }
Sebastian Redl08905022011-02-05 19:23:19 +00009306
Alexis Hunt119c10e2011-05-25 23:16:36 +00009307 if (Ctor->isDefaultConstructor())
9308 return oc_implicit_default_constructor;
9309
9310 if (Ctor->isMoveConstructor())
9311 return oc_implicit_move_constructor;
9312
9313 assert(Ctor->isCopyConstructor() &&
9314 "unexpected sort of implicit constructor");
9315 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009316 }
9317
9318 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9319 // This actually gets spelled 'candidate function' for now, but
9320 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009321 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009322 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009323
Alexis Hunt119c10e2011-05-25 23:16:36 +00009324 if (Meth->isMoveAssignmentOperator())
9325 return oc_implicit_move_assignment;
9326
Douglas Gregor12695102012-02-10 08:36:38 +00009327 if (Meth->isCopyAssignmentOperator())
9328 return oc_implicit_copy_assignment;
9329
9330 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9331 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009332 }
9333
John McCalle1ac8d12010-01-13 00:25:19 +00009334 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009335}
9336
Richard Smith5179eb72016-06-28 19:03:57 +00009337void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9338 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9339 // set.
9340 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9341 S.Diag(FoundDecl->getLocation(),
9342 diag::note_ovl_candidate_inherited_constructor)
9343 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009344}
9345
John McCall53262c92010-01-12 02:15:36 +00009346} // end anonymous namespace
9347
George Burgess IV5f21c712015-10-12 19:57:04 +00009348static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9349 const FunctionDecl *FD) {
9350 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9351 bool AlwaysTrue;
9352 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9353 return false;
9354 if (!AlwaysTrue)
9355 return false;
9356 }
9357 return true;
9358}
9359
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009360/// \brief Returns true if we can take the address of the function.
9361///
9362/// \param Complain - If true, we'll emit a diagnostic
9363/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9364/// we in overload resolution?
9365/// \param Loc - The location of the statement we're complaining about. Ignored
9366/// if we're not complaining, or if we're in overload resolution.
9367static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9368 bool Complain,
9369 bool InOverloadResolution,
9370 SourceLocation Loc) {
9371 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9372 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009373 if (InOverloadResolution)
9374 S.Diag(FD->getLocStart(),
9375 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9376 else
9377 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9378 }
9379 return false;
9380 }
9381
George Burgess IV21081362016-07-24 23:12:40 +00009382 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9383 return P->hasAttr<PassObjectSizeAttr>();
9384 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009385 if (I == FD->param_end())
9386 return true;
9387
9388 if (Complain) {
9389 // Add one to ParamNo because it's user-facing
9390 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9391 if (InOverloadResolution)
9392 S.Diag(FD->getLocation(),
9393 diag::note_ovl_candidate_has_pass_object_size_params)
9394 << ParamNo;
9395 else
9396 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9397 << FD << ParamNo;
9398 }
9399 return false;
9400}
9401
9402static bool checkAddressOfCandidateIsAvailable(Sema &S,
9403 const FunctionDecl *FD) {
9404 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9405 /*InOverloadResolution=*/true,
9406 /*Loc=*/SourceLocation());
9407}
9408
9409bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9410 bool Complain,
9411 SourceLocation Loc) {
9412 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9413 /*InOverloadResolution=*/false,
9414 Loc);
9415}
9416
John McCall53262c92010-01-12 02:15:36 +00009417// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009418void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9419 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009420 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9421 return;
Erich Keane281d20b2018-01-08 21:34:17 +00009422 if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9423 return;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009424
John McCalle1ac8d12010-01-13 00:25:19 +00009425 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009426 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009427 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009428 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009429
9430 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009431 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009432 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009433}
9434
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009435// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009436// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009437void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9438 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009439 assert(OverloadedExpr->getType() == Context.OverloadTy);
9440
9441 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9442 OverloadExpr *OvlExpr = Ovl.Expression;
9443
9444 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009445 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009446 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009447 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009448 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009449 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009450 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009451 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009452 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009453 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009454 }
9455 }
9456}
9457
John McCall0d1da222010-01-12 00:44:57 +00009458/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9459/// "lead" diagnostic; it will be given two arguments, the source and
9460/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009461void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9462 Sema &S,
9463 SourceLocation CaretLoc,
9464 const PartialDiagnostic &PDiag) const {
9465 S.Diag(CaretLoc, PDiag)
9466 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009467 // FIXME: The note limiting machinery is borrowed from
9468 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9469 // refactoring here.
9470 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9471 unsigned CandsShown = 0;
9472 AmbiguousConversionSequence::const_iterator I, E;
9473 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9474 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9475 break;
9476 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009477 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009478 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009479 if (I != E)
9480 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009481}
9482
Richard Smith17c00b42014-11-12 01:24:00 +00009483static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009484 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009485 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9486 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009487 assert(Cand->Function && "for now, candidate must be a function");
9488 FunctionDecl *Fn = Cand->Function;
9489
9490 // There's a conversion slot for the object argument if this is a
9491 // non-constructor method. Note that 'I' corresponds the
9492 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009493 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009494 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009495 if (I == 0)
9496 isObjectArgument = true;
9497 else
9498 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009499 }
9500
John McCalle1ac8d12010-01-13 00:25:19 +00009501 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009502 OverloadCandidateKind FnKind =
9503 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009504
John McCall6a61b522010-01-13 09:16:55 +00009505 Expr *FromExpr = Conv.Bad.FromExpr;
9506 QualType FromTy = Conv.Bad.getFromType();
9507 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009508
John McCallfb7ad0f2010-02-02 02:42:52 +00009509 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009510 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009511 Expr *E = FromExpr->IgnoreParens();
9512 if (isa<UnaryOperator>(E))
9513 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009514 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009515
9516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9517 << (unsigned) FnKind << FnDesc
9518 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9519 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009520 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009521 return;
9522 }
9523
John McCall6d174642010-01-23 08:10:49 +00009524 // Do some hand-waving analysis to see if the non-viability is due
9525 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009526 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9527 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9528 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9529 CToTy = RT->getPointeeType();
9530 else {
9531 // TODO: detect and diagnose the full richness of const mismatches.
9532 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009533 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9534 CFromTy = FromPT->getPointeeType();
9535 CToTy = ToPT->getPointeeType();
9536 }
John McCall47000992010-01-14 03:28:57 +00009537 }
9538
9539 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9540 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009541 Qualifiers FromQs = CFromTy.getQualifiers();
9542 Qualifiers ToQs = CToTy.getQualifiers();
9543
9544 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9546 << (unsigned) FnKind << FnDesc
9547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9548 << FromTy
Yaxun Liub34ec822017-04-11 17:24:23 +00009549 << FromQs.getAddressSpaceAttributePrintValue()
9550 << ToQs.getAddressSpaceAttributePrintValue()
John McCall47000992010-01-14 03:28:57 +00009551 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009552 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009553 return;
9554 }
9555
John McCall31168b02011-06-15 23:02:42 +00009556 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009558 << (unsigned) FnKind << FnDesc
9559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9560 << FromTy
9561 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9562 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009563 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009564 return;
9565 }
9566
Douglas Gregoraec25842011-04-26 23:16:46 +00009567 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9569 << (unsigned) FnKind << FnDesc
9570 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9571 << FromTy
9572 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9573 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009574 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009575 return;
9576 }
9577
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009578 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9580 << (unsigned) FnKind << FnDesc
9581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9582 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009583 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009584 return;
9585 }
9586
John McCall47000992010-01-14 03:28:57 +00009587 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9588 assert(CVR && "unexpected qualifiers mismatch");
9589
9590 if (isObjectArgument) {
9591 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9592 << (unsigned) FnKind << FnDesc
9593 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9594 << FromTy << (CVR - 1);
9595 } else {
9596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9597 << (unsigned) FnKind << FnDesc
9598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9599 << FromTy << (CVR - 1) << I+1;
9600 }
Richard Smith5179eb72016-06-28 19:03:57 +00009601 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009602 return;
9603 }
9604
Sebastian Redla72462c2011-09-24 17:48:32 +00009605 // Special diagnostic for failure to convert an initializer list, since
9606 // telling the user that it has type void is not useful.
9607 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9608 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9609 << (unsigned) FnKind << FnDesc
9610 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9611 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009612 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009613 return;
9614 }
9615
John McCall6d174642010-01-23 08:10:49 +00009616 // Diagnose references or pointers to incomplete types differently,
9617 // since it's far from impossible that the incompleteness triggered
9618 // the failure.
9619 QualType TempFromTy = FromTy.getNonReferenceType();
9620 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9621 TempFromTy = PTy->getPointeeType();
9622 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009623 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009624 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9625 << (unsigned) FnKind << FnDesc
9626 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009627 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9628 << (unsigned) (Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009629
Richard Smith5179eb72016-06-28 19:03:57 +00009630 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009631 return;
9632 }
9633
Douglas Gregor56f2e342010-06-30 23:01:39 +00009634 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009635 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009636 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9637 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9638 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9639 FromPtrTy->getPointeeType()) &&
9640 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9641 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009642 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009643 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009644 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009645 }
9646 } else if (const ObjCObjectPointerType *FromPtrTy
9647 = FromTy->getAs<ObjCObjectPointerType>()) {
9648 if (const ObjCObjectPointerType *ToPtrTy
9649 = ToTy->getAs<ObjCObjectPointerType>())
9650 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9651 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9652 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9653 FromPtrTy->getPointeeType()) &&
9654 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009655 BaseToDerivedConversion = 2;
9656 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009657 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9658 !FromTy->isIncompleteType() &&
9659 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009660 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009661 BaseToDerivedConversion = 3;
9662 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9663 ToTy.getNonReferenceType().getCanonicalType() ==
9664 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9666 << (unsigned) FnKind << FnDesc
9667 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9668 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009669 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009670 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009671 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009673
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009674 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009675 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009676 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009677 << (unsigned) FnKind << FnDesc
9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009679 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009680 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009681 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009682 return;
9683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009684
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009685 if (isa<ObjCObjectPointerType>(CFromTy) &&
9686 isa<PointerType>(CToTy)) {
9687 Qualifiers FromQs = CFromTy.getQualifiers();
9688 Qualifiers ToQs = CToTy.getQualifiers();
9689 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9690 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9691 << (unsigned) FnKind << FnDesc
9692 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9693 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009694 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009695 return;
9696 }
9697 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009698
9699 if (TakingCandidateAddress &&
9700 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9701 return;
9702
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009703 // Emit the generic diagnostic and, optionally, add the hints to it.
9704 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9705 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009706 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009707 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9708 << (unsigned) (Cand->Fix.Kind);
9709
9710 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009711 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9712 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009713 FDiag << *HI;
9714 S.Diag(Fn->getLocation(), FDiag);
9715
Richard Smith5179eb72016-06-28 19:03:57 +00009716 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009717}
9718
Larisse Voufo98b20f12013-07-19 23:00:19 +00009719/// Additional arity mismatch diagnosis specific to a function overload
9720/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9721/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009722static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9723 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009724 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009725 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009726
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009727 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009728 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009729 // right number of arguments, because only overloaded operators have
9730 // the weird behavior of overloading member and non-member functions.
9731 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009732 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009733 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009734 return true;
9735
9736 if (NumArgs < MinParams) {
9737 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9738 (Cand->FailureKind == ovl_fail_bad_deduction &&
9739 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9740 } else {
9741 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9742 (Cand->FailureKind == ovl_fail_bad_deduction &&
9743 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9744 }
9745
9746 return false;
9747}
9748
9749/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009750static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9751 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009752 assert(isa<FunctionDecl>(D) &&
9753 "The templated declaration should at least be a function"
9754 " when diagnosing bad template argument deduction due to too many"
9755 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009756
Larisse Voufo98b20f12013-07-19 23:00:19 +00009757 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009758
Larisse Voufo98b20f12013-07-19 23:00:19 +00009759 // TODO: treat calls to a missing default constructor as a special case
9760 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9761 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009762
John McCall6a61b522010-01-13 09:16:55 +00009763 // at least / at most / exactly
9764 unsigned mode, modeCount;
9765 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009766 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9767 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009768 mode = 0; // "at least"
9769 else
9770 mode = 2; // "exactly"
9771 modeCount = MinParams;
9772 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009773 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009774 mode = 1; // "at most"
9775 else
9776 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009777 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009778 }
9779
9780 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009781 OverloadCandidateKind FnKind =
9782 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009783
Richard Smith10ff50d2012-05-11 05:16:41 +00009784 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9785 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009786 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9787 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009788 else
9789 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009790 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9791 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009792 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009793}
9794
Larisse Voufo98b20f12013-07-19 23:00:19 +00009795/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009796static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9797 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009798 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009799 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009800}
Larisse Voufo47c08452013-07-19 22:53:23 +00009801
Richard Smith17c00b42014-11-12 01:24:00 +00009802static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009803 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9804 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009805 llvm_unreachable("Unsupported: Getting the described template declaration"
9806 " for bad deduction diagnosis");
9807}
9808
9809/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009810static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009811 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009812 unsigned NumArgs,
9813 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009814 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009815 NamedDecl *ParamD;
9816 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9817 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9818 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009819 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009820 case Sema::TDK_Success:
9821 llvm_unreachable("TDK_success while diagnosing bad deduction");
9822
9823 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009824 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009825 S.Diag(Templated->getLocation(),
9826 diag::note_ovl_candidate_incomplete_deduction)
9827 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009828 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009829 return;
9830 }
9831
John McCall42d7d192010-08-05 09:05:08 +00009832 case Sema::TDK_Underqualified: {
9833 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9834 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9835
Larisse Voufo98b20f12013-07-19 23:00:19 +00009836 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009837
9838 // Param will have been canonicalized, but it should just be a
9839 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009840 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009841 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009842 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009843 assert(S.Context.hasSameType(Param, NonCanonParam));
9844
9845 // Arg has also been canonicalized, but there's nothing we can do
9846 // about that. It also doesn't matter as much, because it won't
9847 // have any template parameters in it (because deduction isn't
9848 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009849 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009850
Larisse Voufo98b20f12013-07-19 23:00:19 +00009851 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9852 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009853 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009854 return;
9855 }
9856
9857 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009858 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009859 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009860 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009861 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009862 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9863 // Deduction might have failed because we deduced arguments of two
9864 // different types for a non-type template parameter.
9865 // FIXME: Use a different TDK value for this.
9866 QualType T1 =
9867 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9868 QualType T2 =
9869 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9870 if (!S.Context.hasSameType(T1, T2)) {
9871 S.Diag(Templated->getLocation(),
9872 diag::note_ovl_candidate_inconsistent_deduction_types)
9873 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9874 << *DeductionFailure.getSecondArg() << T2;
9875 MaybeEmitInheritedConstructorNote(S, Found);
9876 return;
9877 }
9878
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009879 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009880 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009881 which = 2;
9882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009883
Larisse Voufo98b20f12013-07-19 23:00:19 +00009884 S.Diag(Templated->getLocation(),
9885 diag::note_ovl_candidate_inconsistent_deduction)
9886 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9887 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009888 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009889 return;
9890 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009891
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009892 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009893 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009894 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009895 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009896 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009897 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009898 else {
9899 int index = 0;
9900 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9901 index = TTP->getIndex();
9902 else if (NonTypeTemplateParmDecl *NTTP
9903 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9904 index = NTTP->getIndex();
9905 else
9906 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009907 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009908 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009909 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009910 }
Richard Smith5179eb72016-06-28 19:03:57 +00009911 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009912 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009913
Douglas Gregor02eb4832010-05-08 18:13:28 +00009914 case Sema::TDK_TooManyArguments:
9915 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009916 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009917 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009918
9919 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009920 S.Diag(Templated->getLocation(),
9921 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009922 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009923 return;
9924
9925 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009926 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009927 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009928 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009929 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009930 TemplateArgString = " ";
9931 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009932 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009933 }
9934
Richard Smith6f8d2c62012-05-09 05:17:00 +00009935 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009936 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009937 if (PDiag && PDiag->second.getDiagID() ==
9938 diag::err_typename_nested_not_found_enable_if) {
9939 // FIXME: Use the source range of the condition, and the fully-qualified
9940 // name of the enable_if template. These are both present in PDiag.
9941 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9942 << "'enable_if'" << TemplateArgString;
9943 return;
9944 }
9945
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009946 // We found a specific requirement that disabled the enable_if.
9947 if (PDiag && PDiag->second.getDiagID() ==
9948 diag::err_typename_nested_not_found_requirement) {
9949 S.Diag(Templated->getLocation(),
9950 diag::note_ovl_candidate_disabled_by_requirement)
9951 << PDiag->second.getStringArg(0) << TemplateArgString;
9952 return;
9953 }
9954
Richard Smith9ca64612012-05-07 09:03:25 +00009955 // Format the SFINAE diagnostic into the argument string.
9956 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9957 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009958 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009959 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009960 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009961 SFINAEArgString = ": ";
9962 R = SourceRange(PDiag->first, PDiag->first);
9963 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9964 }
9965
Larisse Voufo98b20f12013-07-19 23:00:19 +00009966 S.Diag(Templated->getLocation(),
9967 diag::note_ovl_candidate_substitution_failure)
9968 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009969 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009970 return;
9971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009972
Richard Smithc92d2062017-01-05 23:02:44 +00009973 case Sema::TDK_DeducedMismatch:
9974 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009975 // Format the template argument list into the argument string.
9976 SmallString<128> TemplateArgString;
9977 if (TemplateArgumentList *Args =
9978 DeductionFailure.getTemplateArgumentList()) {
9979 TemplateArgString = " ";
9980 TemplateArgString += S.getTemplateArgumentBindingsText(
9981 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9982 }
9983
9984 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9985 << (*DeductionFailure.getCallArgIndex() + 1)
9986 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009987 << TemplateArgString
9988 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009989 break;
9990 }
9991
Richard Trieue3732352013-04-08 21:11:40 +00009992 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009993 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009994 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9995 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009996 if (FirstTA.getKind() == TemplateArgument::Template &&
9997 SecondTA.getKind() == TemplateArgument::Template) {
9998 TemplateName FirstTN = FirstTA.getAsTemplate();
9999 TemplateName SecondTN = SecondTA.getAsTemplate();
10000 if (FirstTN.getKind() == TemplateName::Template &&
10001 SecondTN.getKind() == TemplateName::Template) {
10002 if (FirstTN.getAsTemplateDecl()->getName() ==
10003 SecondTN.getAsTemplateDecl()->getName()) {
10004 // FIXME: This fixes a bad diagnostic where both templates are named
10005 // the same. This particular case is a bit difficult since:
10006 // 1) It is passed as a string to the diagnostic printer.
10007 // 2) The diagnostic printer only attempts to find a better
10008 // name for types, not decls.
10009 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010010 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010011 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10012 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10013 return;
10014 }
10015 }
10016 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010017
10018 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10019 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10020 return;
10021
Faisal Vali2b391ab2013-09-26 19:54:12 +000010022 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010023 // call operator, and if so, emit a prettier and more informative
10024 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +000010025 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010026 S.Diag(Templated->getLocation(),
10027 diag::note_ovl_candidate_non_deduced_mismatch)
10028 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010029 return;
Richard Trieue3732352013-04-08 21:11:40 +000010030 }
John McCall8b9ed552010-02-01 18:53:26 +000010031 // TODO: diagnose these individually, then kill off
10032 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010033 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010034 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010035 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010036 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010037 case Sema::TDK_CUDATargetMismatch:
10038 S.Diag(Templated->getLocation(),
10039 diag::note_cuda_ovl_candidate_target_mismatch);
10040 return;
John McCall8b9ed552010-02-01 18:53:26 +000010041 }
10042}
10043
Larisse Voufo98b20f12013-07-19 23:00:19 +000010044/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010045static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010046 unsigned NumArgs,
10047 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010048 unsigned TDK = Cand->DeductionFailure.Result;
10049 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10050 if (CheckArityMismatch(S, Cand, NumArgs))
10051 return;
10052 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010053 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010054 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010055}
10056
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010057/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010058static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010059 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10060 FunctionDecl *Callee = Cand->Function;
10061
10062 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10063 CalleeTarget = S.IdentifyCUDATarget(Callee);
10064
10065 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +000010066 OverloadCandidateKind FnKind =
10067 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010068
10069 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010070 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10071
10072 // This could be an implicit constructor for which we could not infer the
10073 // target due to a collsion. Diagnose that case.
10074 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10075 if (Meth != nullptr && Meth->isImplicit()) {
10076 CXXRecordDecl *ParentClass = Meth->getParent();
10077 Sema::CXXSpecialMember CSM;
10078
10079 switch (FnKind) {
10080 default:
10081 return;
10082 case oc_implicit_default_constructor:
10083 CSM = Sema::CXXDefaultConstructor;
10084 break;
10085 case oc_implicit_copy_constructor:
10086 CSM = Sema::CXXCopyConstructor;
10087 break;
10088 case oc_implicit_move_constructor:
10089 CSM = Sema::CXXMoveConstructor;
10090 break;
10091 case oc_implicit_copy_assignment:
10092 CSM = Sema::CXXCopyAssignment;
10093 break;
10094 case oc_implicit_move_assignment:
10095 CSM = Sema::CXXMoveAssignment;
10096 break;
10097 };
10098
10099 bool ConstRHS = false;
10100 if (Meth->getNumParams()) {
10101 if (const ReferenceType *RT =
10102 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10103 ConstRHS = RT->getPointeeType().isConstQualified();
10104 }
10105 }
10106
10107 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10108 /* ConstRHS */ ConstRHS,
10109 /* Diagnose */ true);
10110 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010111}
10112
Richard Smith17c00b42014-11-12 01:24:00 +000010113static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010114 FunctionDecl *Callee = Cand->Function;
10115 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10116
10117 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010118 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010119 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10120}
10121
Yaxun Liu5b746652016-12-18 05:18:55 +000010122static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10123 FunctionDecl *Callee = Cand->Function;
10124
10125 S.Diag(Callee->getLocation(),
10126 diag::note_ovl_candidate_disabled_by_extension);
10127}
10128
John McCall8b9ed552010-02-01 18:53:26 +000010129/// Generates a 'note' diagnostic for an overload candidate. We've
10130/// already generated a primary error at the call site.
10131///
10132/// It really does need to be a single diagnostic with its caret
10133/// pointed at the candidate declaration. Yes, this creates some
10134/// major challenges of technical writing. Yes, this makes pointing
10135/// out problems with specific arguments quite awkward. It's still
10136/// better than generating twenty screens of text for every failed
10137/// overload.
10138///
10139/// It would be great to be able to express per-candidate problems
10140/// more richly for those diagnostic clients that cared, but we'd
10141/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010142static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010143 unsigned NumArgs,
10144 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010145 FunctionDecl *Fn = Cand->Function;
10146
John McCall12f97bc2010-01-08 04:41:39 +000010147 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010148 if (Cand->Viable) {
10149 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10150 std::string FnDesc;
10151 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010152 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010153
George Burgess IV177399e2017-01-09 04:12:14 +000010154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10155 << FnKind << FnDesc
10156 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10157 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10158 return;
10159 }
John McCall12f97bc2010-01-08 04:41:39 +000010160
George Burgess IV177399e2017-01-09 04:12:14 +000010161 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010162 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010163 return;
10164 }
John McCall0d1da222010-01-12 00:44:57 +000010165
John McCall6a61b522010-01-13 09:16:55 +000010166 switch (Cand->FailureKind) {
10167 case ovl_fail_too_many_arguments:
10168 case ovl_fail_too_few_arguments:
10169 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010170
John McCall6a61b522010-01-13 09:16:55 +000010171 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010172 return DiagnoseBadDeduction(S, Cand, NumArgs,
10173 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010174
John McCall578a1f82014-12-14 01:46:53 +000010175 case ovl_fail_illegal_constructor: {
10176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10177 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010179 return;
10180 }
10181
John McCallfe796dd2010-01-23 05:17:32 +000010182 case ovl_fail_trivial_conversion:
10183 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010184 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010185 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010186
John McCall65eb8792010-02-25 01:37:24 +000010187 case ovl_fail_bad_conversion: {
10188 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010189 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010190 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010191 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010192
John McCall6a61b522010-01-13 09:16:55 +000010193 // FIXME: this currently happens when we're called from SemaInit
10194 // when user-conversion overload fails. Figure out how to handle
10195 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010196 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010197 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010198
10199 case ovl_fail_bad_target:
10200 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010201
10202 case ovl_fail_enable_if:
10203 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010204
Yaxun Liu5b746652016-12-18 05:18:55 +000010205 case ovl_fail_ext_disabled:
10206 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10207
Richard Smithf9c59b72017-01-08 21:45:44 +000010208 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010209 // It's generally not interesting to note copy/move constructors here.
10210 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10211 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010212 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010213 diag::note_ovl_candidate_inherited_constructor_slice)
10214 << (Fn->getPrimaryTemplate() ? 1 : 0)
10215 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010216 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10217 return;
10218
George Burgess IV7204ed92016-01-07 02:26:57 +000010219 case ovl_fail_addr_not_available: {
10220 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10221 (void)Available;
10222 assert(!Available);
10223 break;
10224 }
Erich Keane281d20b2018-01-08 21:34:17 +000010225 case ovl_non_default_multiversion_function:
10226 // Do nothing, these should simply be ignored.
10227 break;
John McCall65eb8792010-02-25 01:37:24 +000010228 }
John McCalld3224162010-01-08 00:58:21 +000010229}
10230
Richard Smith17c00b42014-11-12 01:24:00 +000010231static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010232 // Desugar the type of the surrogate down to a function type,
10233 // retaining as many typedefs as possible while still showing
10234 // the function type (and, therefore, its parameter types).
10235 QualType FnType = Cand->Surrogate->getConversionType();
10236 bool isLValueReference = false;
10237 bool isRValueReference = false;
10238 bool isPointer = false;
10239 if (const LValueReferenceType *FnTypeRef =
10240 FnType->getAs<LValueReferenceType>()) {
10241 FnType = FnTypeRef->getPointeeType();
10242 isLValueReference = true;
10243 } else if (const RValueReferenceType *FnTypeRef =
10244 FnType->getAs<RValueReferenceType>()) {
10245 FnType = FnTypeRef->getPointeeType();
10246 isRValueReference = true;
10247 }
10248 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10249 FnType = FnTypePtr->getPointeeType();
10250 isPointer = true;
10251 }
10252 // Desugar down to a function type.
10253 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10254 // Reconstruct the pointer/reference as appropriate.
10255 if (isPointer) FnType = S.Context.getPointerType(FnType);
10256 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10257 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10258
10259 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10260 << FnType;
10261}
10262
Richard Smith17c00b42014-11-12 01:24:00 +000010263static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10264 SourceLocation OpLoc,
10265 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010266 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010267 std::string TypeStr("operator");
10268 TypeStr += Opc;
10269 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010270 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010271 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010272 TypeStr += ")";
10273 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10274 } else {
10275 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010276 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010277 TypeStr += ")";
10278 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10279 }
10280}
10281
Richard Smith17c00b42014-11-12 01:24:00 +000010282static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10283 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010284 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010285 if (ICS.isBad()) break; // all meaningless after first invalid
10286 if (!ICS.isAmbiguous()) continue;
10287
Richard Smithc2bebe92016-05-11 20:37:46 +000010288 ICS.DiagnoseAmbiguousConversion(
10289 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010290 }
10291}
10292
Larisse Voufo98b20f12013-07-19 23:00:19 +000010293static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010294 if (Cand->Function)
10295 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010296 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010297 return Cand->Surrogate->getLocation();
10298 return SourceLocation();
10299}
10300
Larisse Voufo98b20f12013-07-19 23:00:19 +000010301static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010302 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010303 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010304 case Sema::TDK_NonDependentConversionFailure:
10305 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010306
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010307 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010308 case Sema::TDK_Incomplete:
10309 return 1;
10310
10311 case Sema::TDK_Underqualified:
10312 case Sema::TDK_Inconsistent:
10313 return 2;
10314
10315 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010316 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010317 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010318 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010319 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010320 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010321 return 3;
10322
10323 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010324 return 4;
10325
10326 case Sema::TDK_InvalidExplicitArguments:
10327 return 5;
10328
10329 case Sema::TDK_TooManyArguments:
10330 case Sema::TDK_TooFewArguments:
10331 return 6;
10332 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010333 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010334}
10335
Richard Smith17c00b42014-11-12 01:24:00 +000010336namespace {
John McCallad2587a2010-01-12 00:48:53 +000010337struct CompareOverloadCandidatesForDisplay {
10338 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010339 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010340 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010341 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010342
Richard Smith67ef14f2017-09-26 18:37:55 +000010343 CompareOverloadCandidatesForDisplay(
10344 Sema &S, SourceLocation Loc, size_t NArgs,
10345 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010346 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010347
10348 bool operator()(const OverloadCandidate *L,
10349 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010350 // Fast-path this check.
10351 if (L == R) return false;
10352
John McCall12f97bc2010-01-08 04:41:39 +000010353 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010354 if (L->Viable) {
10355 if (!R->Viable) return true;
10356
10357 // TODO: introduce a tri-valued comparison for overload
10358 // candidates. Would be more worthwhile if we had a sort
10359 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010360 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10361 return true;
10362 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10363 return false;
John McCallad2587a2010-01-12 00:48:53 +000010364 } else if (R->Viable)
10365 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010366
John McCall3712d9e2010-01-15 23:32:50 +000010367 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010368
John McCall3712d9e2010-01-15 23:32:50 +000010369 // Criteria by which we can sort non-viable candidates:
10370 if (!L->Viable) {
10371 // 1. Arity mismatches come after other candidates.
10372 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010373 L->FailureKind == ovl_fail_too_few_arguments) {
10374 if (R->FailureKind == ovl_fail_too_many_arguments ||
10375 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010376 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10377 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10378 if (LDist == RDist) {
10379 if (L->FailureKind == R->FailureKind)
10380 // Sort non-surrogates before surrogates.
10381 return !L->IsSurrogate && R->IsSurrogate;
10382 // Sort candidates requiring fewer parameters than there were
10383 // arguments given after candidates requiring more parameters
10384 // than there were arguments given.
10385 return L->FailureKind == ovl_fail_too_many_arguments;
10386 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010387 return LDist < RDist;
10388 }
John McCall3712d9e2010-01-15 23:32:50 +000010389 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010390 }
John McCall3712d9e2010-01-15 23:32:50 +000010391 if (R->FailureKind == ovl_fail_too_many_arguments ||
10392 R->FailureKind == ovl_fail_too_few_arguments)
10393 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010394
John McCallfe796dd2010-01-23 05:17:32 +000010395 // 2. Bad conversions come first and are ordered by the number
10396 // of bad conversions and quality of good conversions.
10397 if (L->FailureKind == ovl_fail_bad_conversion) {
10398 if (R->FailureKind != ovl_fail_bad_conversion)
10399 return true;
10400
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010401 // The conversion that can be fixed with a smaller number of changes,
10402 // comes first.
10403 unsigned numLFixes = L->Fix.NumConversionsFixed;
10404 unsigned numRFixes = R->Fix.NumConversionsFixed;
10405 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10406 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010407 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010408 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010409 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010410
John McCallfe796dd2010-01-23 05:17:32 +000010411 // If there's any ordering between the defined conversions...
10412 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010413 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010414
10415 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010416 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010417 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010418 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010419 L->Conversions[I],
10420 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010421 case ImplicitConversionSequence::Better:
10422 leftBetter++;
10423 break;
10424
10425 case ImplicitConversionSequence::Worse:
10426 leftBetter--;
10427 break;
10428
10429 case ImplicitConversionSequence::Indistinguishable:
10430 break;
10431 }
10432 }
10433 if (leftBetter > 0) return true;
10434 if (leftBetter < 0) return false;
10435
10436 } else if (R->FailureKind == ovl_fail_bad_conversion)
10437 return false;
10438
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010439 if (L->FailureKind == ovl_fail_bad_deduction) {
10440 if (R->FailureKind != ovl_fail_bad_deduction)
10441 return true;
10442
10443 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10444 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010445 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010446 } else if (R->FailureKind == ovl_fail_bad_deduction)
10447 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010448
John McCall3712d9e2010-01-15 23:32:50 +000010449 // TODO: others?
10450 }
10451
10452 // Sort everything else by location.
10453 SourceLocation LLoc = GetLocationForCandidate(L);
10454 SourceLocation RLoc = GetLocationForCandidate(R);
10455
10456 // Put candidates without locations (e.g. builtins) at the end.
10457 if (LLoc.isInvalid()) return false;
10458 if (RLoc.isInvalid()) return true;
10459
10460 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010461 }
10462};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010463}
John McCall12f97bc2010-01-08 04:41:39 +000010464
John McCallfe796dd2010-01-23 05:17:32 +000010465/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010466/// computes up to the first bad conversion. Produces the FixIt set if
10467/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010468static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10469 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010470 assert(!Cand->Viable);
10471
10472 // Don't do anything on failures other than bad conversion.
10473 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10474
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010475 // We only want the FixIts if all the arguments can be corrected.
10476 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010477 // Use a implicit copy initialization to check conversion fixes.
10478 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010479
Richard Smith6eedfe72017-01-09 08:01:21 +000010480 // Attempt to fix the bad conversion.
10481 unsigned ConvCount = Cand->Conversions.size();
10482 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10483 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010484 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010485 if (Cand->Conversions[ConvIdx].isInitialized() &&
10486 Cand->Conversions[ConvIdx].isBad()) {
10487 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010488 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010489 }
John McCallfe796dd2010-01-23 05:17:32 +000010490 }
10491
Douglas Gregoradc7a702010-04-16 17:45:54 +000010492 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010493 // operation somehow.
10494 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010495
Richard Smith14ead302017-01-10 20:19:21 +000010496 unsigned ConvIdx = 0;
10497 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010498
10499 if (Cand->IsSurrogate) {
10500 QualType ConvType
10501 = Cand->Surrogate->getConversionType().getNonReferenceType();
10502 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10503 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010504 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10505 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10506 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010507 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010508 ParamTypes =
10509 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010510 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010511 !isa<CXXConstructorDecl>(Cand->Function)) {
10512 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10513 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010514 }
Richard Smith14ead302017-01-10 20:19:21 +000010515 } else {
10516 // Builtin operator.
10517 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010518 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010519 }
10520
10521 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010522 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010523 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010524 // We've already checked this conversion.
10525 } else if (ArgIdx < ParamTypes.size()) {
10526 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010527 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10528 Args[ArgIdx]->getType());
10529 else {
10530 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010531 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010532 SuppressUserConversions,
10533 /*InOverloadResolution=*/true,
10534 /*AllowObjCWritebackConversion=*/
10535 S.getLangOpts().ObjCAutoRefCount);
10536 // Store the FixIt in the candidate if it exists.
10537 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10538 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10539 }
10540 } else
John McCallfe796dd2010-01-23 05:17:32 +000010541 Cand->Conversions[ConvIdx].setEllipsis();
10542 }
10543}
10544
Erich Keanec18cce42018-01-29 19:33:20 +000010545/// When overload resolution fails, prints diagnostic messages containing the
10546/// candidates in the candidate set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010547void OverloadCandidateSet::NoteCandidates(
10548 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10549 StringRef Opc, SourceLocation OpLoc,
10550 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010551 // Sort the candidates by viability and position. Sorting directly would
10552 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010553 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010554 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10555 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010556 if (!Filter(*Cand))
10557 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010558 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010559 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010560 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010561 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010562 if (Cand->Function || Cand->IsSurrogate)
10563 Cands.push_back(Cand);
10564 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10565 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010566 }
10567 }
10568
Mandeep Singh Grange66d2322017-11-14 00:22:24 +000010569 std::stable_sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010570 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010571
John McCall0d1da222010-01-12 00:44:57 +000010572 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010573
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010574 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010575 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010576 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010577 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10578 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010579
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010580 // Set an arbitrary limit on the number of candidate functions we'll spam
10581 // the user with. FIXME: This limit should depend on details of the
10582 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010583 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010584 break;
10585 }
10586 ++CandsShown;
10587
John McCalld3224162010-01-08 00:58:21 +000010588 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010589 NoteFunctionCandidate(S, Cand, Args.size(),
10590 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010591 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010592 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010593 else {
10594 assert(Cand->Viable &&
10595 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010596 // Generally we only see ambiguities including viable builtin
10597 // operators if overload resolution got screwed up by an
10598 // ambiguous user-defined conversion.
10599 //
10600 // FIXME: It's quite possible for different conversions to see
10601 // different ambiguities, though.
10602 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010603 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010604 ReportedAmbiguousConversions = true;
10605 }
John McCalld3224162010-01-08 00:58:21 +000010606
John McCall0d1da222010-01-12 00:44:57 +000010607 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010608 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010609 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010610 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010611
10612 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010613 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010614}
10615
Larisse Voufo98b20f12013-07-19 23:00:19 +000010616static SourceLocation
10617GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10618 return Cand->Specialization ? Cand->Specialization->getLocation()
10619 : SourceLocation();
10620}
10621
Richard Smith17c00b42014-11-12 01:24:00 +000010622namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010623struct CompareTemplateSpecCandidatesForDisplay {
10624 Sema &S;
10625 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10626
10627 bool operator()(const TemplateSpecCandidate *L,
10628 const TemplateSpecCandidate *R) {
10629 // Fast-path this check.
10630 if (L == R)
10631 return false;
10632
10633 // Assuming that both candidates are not matches...
10634
10635 // Sort by the ranking of deduction failures.
10636 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10637 return RankDeductionFailure(L->DeductionFailure) <
10638 RankDeductionFailure(R->DeductionFailure);
10639
10640 // Sort everything else by location.
10641 SourceLocation LLoc = GetLocationForCandidate(L);
10642 SourceLocation RLoc = GetLocationForCandidate(R);
10643
10644 // Put candidates without locations (e.g. builtins) at the end.
10645 if (LLoc.isInvalid())
10646 return false;
10647 if (RLoc.isInvalid())
10648 return true;
10649
10650 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10651 }
10652};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010653}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010654
10655/// Diagnose a template argument deduction failure.
10656/// We are treating these failures as overload failures due to bad
10657/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010658void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10659 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010660 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010661 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010662}
10663
10664void TemplateSpecCandidateSet::destroyCandidates() {
10665 for (iterator i = begin(), e = end(); i != e; ++i) {
10666 i->DeductionFailure.Destroy();
10667 }
10668}
10669
10670void TemplateSpecCandidateSet::clear() {
10671 destroyCandidates();
10672 Candidates.clear();
10673}
10674
10675/// NoteCandidates - When no template specialization match is found, prints
10676/// diagnostic messages containing the non-matching specializations that form
10677/// the candidate set.
10678/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10679/// OCD == OCD_AllCandidates and Cand->Viable == false.
10680void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10681 // Sort the candidates by position (assuming no candidate is a match).
10682 // Sorting directly would be prohibitive, so we make a set of pointers
10683 // and sort those.
10684 SmallVector<TemplateSpecCandidate *, 32> Cands;
10685 Cands.reserve(size());
10686 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10687 if (Cand->Specialization)
10688 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010689 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010690 // in general, want to list every possible builtin candidate.
10691 }
10692
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +000010693 llvm::sort(Cands.begin(), Cands.end(),
10694 CompareTemplateSpecCandidatesForDisplay(S));
Larisse Voufo98b20f12013-07-19 23:00:19 +000010695
10696 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10697 // for generalization purposes (?).
10698 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10699
10700 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10701 unsigned CandsShown = 0;
10702 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10703 TemplateSpecCandidate *Cand = *I;
10704
10705 // Set an arbitrary limit on the number of candidates we'll spam
10706 // the user with. FIXME: This limit should depend on details of the
10707 // candidate list.
10708 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10709 break;
10710 ++CandsShown;
10711
10712 assert(Cand->Specialization &&
10713 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010714 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010715 }
10716
10717 if (I != E)
10718 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10719}
10720
Douglas Gregorb491ed32011-02-19 21:32:49 +000010721// [PossiblyAFunctionType] --> [Return]
10722// NonFunctionType --> NonFunctionType
10723// R (A) --> R(A)
10724// R (*)(A) --> R (A)
10725// R (&)(A) --> R (A)
10726// R (S::*)(A) --> R (A)
10727QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10728 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010729 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010730 PossiblyAFunctionType->getAs<PointerType>())
10731 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010732 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010733 PossiblyAFunctionType->getAs<ReferenceType>())
10734 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010735 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010736 PossiblyAFunctionType->getAs<MemberPointerType>())
10737 Ret = MemTypePtr->getPointeeType();
10738 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010739 Context.getCanonicalType(Ret).getUnqualifiedType();
10740 return Ret;
10741}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010742
Richard Smith9095e5b2016-11-01 01:31:23 +000010743static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10744 bool Complain = true) {
10745 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10746 S.DeduceReturnType(FD, Loc, Complain))
10747 return true;
10748
10749 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010750 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +000010751 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10752 !S.ResolveExceptionSpec(Loc, FPT))
10753 return true;
10754
10755 return false;
10756}
10757
Richard Smith17c00b42014-11-12 01:24:00 +000010758namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010759// A helper class to help with address of function resolution
10760// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010761class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010762 Sema& S;
10763 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010764 const QualType& TargetType;
10765 QualType TargetFunctionType; // Extracted function type from target type
10766
Douglas Gregorb491ed32011-02-19 21:32:49 +000010767 bool Complain;
10768 //DeclAccessPair& ResultFunctionAccessPair;
10769 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010770
Douglas Gregorb491ed32011-02-19 21:32:49 +000010771 bool TargetTypeIsNonStaticMemberFunction;
10772 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010773 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010774 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010775
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010776 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010777 OverloadExpr *OvlExpr;
10778 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010779 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010780 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010781
Douglas Gregorb491ed32011-02-19 21:32:49 +000010782public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010783 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10784 const QualType &TargetType, bool Complain)
10785 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10786 Complain(Complain), Context(S.getASTContext()),
10787 TargetTypeIsNonStaticMemberFunction(
10788 !!TargetType->getAs<MemberPointerType>()),
10789 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010790 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010791 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010792 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10793 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010794 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010795 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010796
David Majnemera4f7c7a2013-08-01 06:13:59 +000010797 if (TargetFunctionType->isFunctionType()) {
10798 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10799 if (!UME->isImplicitAccess() &&
10800 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10801 StaticMemberFunctionFromBoundPointer = true;
10802 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10803 DeclAccessPair dap;
10804 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10805 OvlExpr, false, &dap)) {
10806 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10807 if (!Method->isStatic()) {
10808 // If the target type is a non-function type and the function found
10809 // is a non-static member function, pretend as if that was the
10810 // target, it's the only possible type to end up with.
10811 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010812
David Majnemera4f7c7a2013-08-01 06:13:59 +000010813 // And skip adding the function if its not in the proper form.
10814 // We'll diagnose this due to an empty set of functions.
10815 if (!OvlExprInfo.HasFormOfMemberPointer)
10816 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010817 }
10818
David Majnemera4f7c7a2013-08-01 06:13:59 +000010819 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010820 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010821 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010822 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010823
Douglas Gregorb491ed32011-02-19 21:32:49 +000010824 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010825 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010826
Douglas Gregorb491ed32011-02-19 21:32:49 +000010827 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10828 // C++ [over.over]p4:
10829 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010830 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010831 if (FoundNonTemplateFunction)
10832 EliminateAllTemplateMatches();
10833 else
10834 EliminateAllExceptMostSpecializedTemplate();
10835 }
10836 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010837
Justin Lebar25c4a812016-03-29 16:24:16 +000010838 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010839 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010840 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010841
10842 bool hasComplained() const { return HasComplained; }
10843
Douglas Gregorb491ed32011-02-19 21:32:49 +000010844private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010845 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10846 QualType Discard;
10847 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010848 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010849 }
10850
George Burgess IV6da4c202016-03-23 02:33:58 +000010851 /// \return true if A is considered a better overload candidate for the
10852 /// desired type than B.
10853 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10854 // If A doesn't have exactly the correct type, we don't want to classify it
10855 // as "better" than anything else. This way, the user is required to
10856 // disambiguate for us if there are multiple candidates and no exact match.
10857 return candidateHasExactlyCorrectType(A) &&
10858 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010859 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010860 }
10861
10862 /// \return true if we were able to eliminate all but one overload candidate,
10863 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010864 bool eliminiateSuboptimalOverloadCandidates() {
10865 // Same algorithm as overload resolution -- one pass to pick the "best",
10866 // another pass to be sure that nothing is better than the best.
10867 auto Best = Matches.begin();
10868 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10869 if (isBetterCandidate(I->second, Best->second))
10870 Best = I;
10871
10872 const FunctionDecl *BestFn = Best->second;
10873 auto IsBestOrInferiorToBest = [this, BestFn](
10874 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10875 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10876 };
10877
10878 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10879 // option, so we can potentially give the user a better error
10880 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10881 return false;
10882 Matches[0] = *Best;
10883 Matches.resize(1);
10884 return true;
10885 }
10886
Douglas Gregorb491ed32011-02-19 21:32:49 +000010887 bool isTargetTypeAFunction() const {
10888 return TargetFunctionType->isFunctionType();
10889 }
10890
10891 // [ToType] [Return]
10892
10893 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10894 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10895 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10896 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10897 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10898 }
10899
10900 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010901 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010902 const DeclAccessPair& CurAccessFunPair) {
10903 if (CXXMethodDecl *Method
10904 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10905 // Skip non-static function templates when converting to pointer, and
10906 // static when converting to member pointer.
10907 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10908 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010909 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010910 else if (TargetTypeIsNonStaticMemberFunction)
10911 return false;
10912
10913 // C++ [over.over]p2:
10914 // If the name is a function template, template argument deduction is
10915 // done (14.8.2.2), and if the argument deduction succeeds, the
10916 // resulting template argument list is used to generate a single
10917 // function template specialization, which is added to the set of
10918 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010919 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010920 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010921 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010922 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010923 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010924 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010925 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010926 // Make a note of the failed deduction for diagnostics.
10927 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010928 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010929 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010930 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010931 }
10932
Douglas Gregor19a41f12013-04-17 08:45:07 +000010933 // Template argument deduction ensures that we have an exact match or
10934 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010935 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010936 assert(S.isSameOrCompatibleFunctionType(
10937 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010938 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010939
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010940 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010941 return false;
10942
Douglas Gregorb491ed32011-02-19 21:32:49 +000010943 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10944 return true;
10945 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010946
10947 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010948 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010950 // Skip non-static functions when converting to pointer, and static
10951 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010952 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10953 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010954 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010955 else if (TargetTypeIsNonStaticMemberFunction)
10956 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010957
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010958 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010959 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010960 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010961 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010962 return false;
Erich Keane281d20b2018-01-08 21:34:17 +000010963 if (FunDecl->isMultiVersion()) {
10964 const auto *TA = FunDecl->getAttr<TargetAttr>();
10965 assert(TA && "Multiversioned functions require a target attribute");
10966 if (!TA->isDefaultVersion())
10967 return false;
10968 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010969
Richard Smith2a7d4812013-05-04 07:00:32 +000010970 // If any candidate has a placeholder return type, trigger its deduction
10971 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010972 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10973 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010974 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010975 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010976 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010977
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010978 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010979 return false;
10980
George Burgess IV6da4c202016-03-23 02:33:58 +000010981 // If we're in C, we need to support types that aren't exactly identical.
10982 if (!S.getLangOpts().CPlusPlus ||
10983 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010984 Matches.push_back(std::make_pair(
10985 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010986 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010987 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010988 }
Mike Stump11289f42009-09-09 15:08:12 +000010989 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010990
Douglas Gregorb491ed32011-02-19 21:32:49 +000010991 return false;
10992 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010993
Douglas Gregorb491ed32011-02-19 21:32:49 +000010994 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10995 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010996
Douglas Gregorb491ed32011-02-19 21:32:49 +000010997 // If the overload expression doesn't have the form of a pointer to
10998 // member, don't try to convert it to a pointer-to-member type.
10999 if (IsInvalidFormOfPointerToMemberFunction())
11000 return false;
11001
11002 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011003 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011004 I != E; ++I) {
11005 // Look through any using declarations to find the underlying function.
11006 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11007
11008 // C++ [over.over]p3:
11009 // Non-member functions and static member functions match
11010 // targets of type "pointer-to-function" or "reference-to-function."
11011 // Nonstatic member functions match targets of
11012 // type "pointer-to-member-function."
11013 // Note that according to DR 247, the containing class does not matter.
11014 if (FunctionTemplateDecl *FunctionTemplate
11015 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11016 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11017 Ret = true;
11018 }
11019 // If we have explicit template arguments supplied, skip non-templates.
11020 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11021 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11022 Ret = true;
11023 }
11024 assert(Ret || Matches.empty());
11025 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011026 }
11027
Douglas Gregorb491ed32011-02-19 21:32:49 +000011028 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011029 // [...] and any given function template specialization F1 is
11030 // eliminated if the set contains a second function template
11031 // specialization whose function template is more specialized
11032 // than the function template of F1 according to the partial
11033 // ordering rules of 14.5.5.2.
11034
11035 // The algorithm specified above is quadratic. We instead use a
11036 // two-pass algorithm (similar to the one used to identify the
11037 // best viable function in an overload set) that identifies the
11038 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011039
11040 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11041 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11042 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011043
Larisse Voufo98b20f12013-07-19 23:00:19 +000011044 // TODO: It looks like FailedCandidates does not serve much purpose
11045 // here, since the no_viable diagnostic has index 0.
11046 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011047 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011048 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011049 S.PDiag(diag::err_addr_ovl_ambiguous)
11050 << Matches[0].second->getDeclName(),
11051 S.PDiag(diag::note_ovl_candidate)
11052 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011053 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011054
Douglas Gregorb491ed32011-02-19 21:32:49 +000011055 if (Result != MatchesCopy.end()) {
11056 // Make it the first and only element
11057 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11058 Matches[0].second = cast<FunctionDecl>(*Result);
11059 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011060 } else
11061 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011063
Douglas Gregorb491ed32011-02-19 21:32:49 +000011064 void EliminateAllTemplateMatches() {
11065 // [...] any function template specializations in the set are
11066 // eliminated if the set also contains a non-template function, [...]
11067 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011068 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011069 ++I;
11070 else {
11071 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011072 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011073 }
11074 }
11075 }
11076
Artem Belevich94a55e82015-09-22 17:22:59 +000011077 void EliminateSuboptimalCudaMatches() {
11078 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11079 }
11080
Douglas Gregorb491ed32011-02-19 21:32:49 +000011081public:
11082 void ComplainNoMatchesFound() const {
11083 assert(Matches.empty());
11084 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11085 << OvlExpr->getName() << TargetFunctionType
11086 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011087 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011088 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11089 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011090 else {
11091 // We have some deduction failure messages. Use them to diagnose
11092 // the function templates, and diagnose the non-template candidates
11093 // normally.
11094 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11095 IEnd = OvlExpr->decls_end();
11096 I != IEnd; ++I)
11097 if (FunctionDecl *Fun =
11098 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011099 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011100 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011101 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011102 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11103 }
11104 }
11105
Douglas Gregorb491ed32011-02-19 21:32:49 +000011106 bool IsInvalidFormOfPointerToMemberFunction() const {
11107 return TargetTypeIsNonStaticMemberFunction &&
11108 !OvlExprInfo.HasFormOfMemberPointer;
11109 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011110
Douglas Gregorb491ed32011-02-19 21:32:49 +000011111 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11112 // TODO: Should we condition this on whether any functions might
11113 // have matched, or is it more appropriate to do that in callers?
11114 // TODO: a fixit wouldn't hurt.
11115 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11116 << TargetType << OvlExpr->getSourceRange();
11117 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011118
11119 bool IsStaticMemberFunctionFromBoundPointer() const {
11120 return StaticMemberFunctionFromBoundPointer;
11121 }
11122
11123 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11124 S.Diag(OvlExpr->getLocStart(),
11125 diag::err_invalid_form_pointer_member_function)
11126 << OvlExpr->getSourceRange();
11127 }
11128
Douglas Gregorb491ed32011-02-19 21:32:49 +000011129 void ComplainOfInvalidConversion() const {
11130 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11131 << OvlExpr->getName() << TargetType;
11132 }
11133
11134 void ComplainMultipleMatchesFound() const {
11135 assert(Matches.size() > 1);
11136 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11137 << OvlExpr->getName()
11138 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011139 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11140 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011141 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011142
11143 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11144
Douglas Gregorb491ed32011-02-19 21:32:49 +000011145 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011146
Douglas Gregorb491ed32011-02-19 21:32:49 +000011147 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011148 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011149 return Matches[0].second;
11150 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011151
Douglas Gregorb491ed32011-02-19 21:32:49 +000011152 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011153 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011154 return &Matches[0].first;
11155 }
11156};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011157}
Richard Smith17c00b42014-11-12 01:24:00 +000011158
Douglas Gregorb491ed32011-02-19 21:32:49 +000011159/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11160/// an overloaded function (C++ [over.over]), where @p From is an
11161/// expression with overloaded function type and @p ToType is the type
11162/// we're trying to resolve to. For example:
11163///
11164/// @code
11165/// int f(double);
11166/// int f(int);
11167///
11168/// int (*pfd)(double) = f; // selects f(double)
11169/// @endcode
11170///
11171/// This routine returns the resulting FunctionDecl if it could be
11172/// resolved, and NULL otherwise. When @p Complain is true, this
11173/// routine will emit diagnostics if there is an error.
11174FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011175Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11176 QualType TargetType,
11177 bool Complain,
11178 DeclAccessPair &FoundResult,
11179 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011180 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011181
11182 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11183 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011184 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011185 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011186 bool ShouldComplain = Complain && !Resolver.hasComplained();
11187 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011188 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11189 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11190 else
11191 Resolver.ComplainNoMatchesFound();
11192 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011193 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011194 Resolver.ComplainMultipleMatchesFound();
11195 else if (NumMatches == 1) {
11196 Fn = Resolver.getMatchingFunctionDecl();
11197 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011198 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11199 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011200 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011201 if (Complain) {
11202 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11203 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11204 else
11205 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11206 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011207 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011208
11209 if (pHadMultipleCandidates)
11210 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011211 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011212}
11213
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011214/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011215/// resolve that function to a single function that can have its address taken.
11216/// This will modify `Pair` iff it returns non-null.
11217///
11218/// This routine can only realistically succeed if all but one candidates in the
11219/// overload set for SrcExpr cannot have their addresses taken.
11220FunctionDecl *
11221Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11222 DeclAccessPair &Pair) {
11223 OverloadExpr::FindResult R = OverloadExpr::find(E);
11224 OverloadExpr *Ovl = R.Expression;
11225 FunctionDecl *Result = nullptr;
11226 DeclAccessPair DAP;
11227 // Don't use the AddressOfResolver because we're specifically looking for
11228 // cases where we have one overload candidate that lacks
11229 // enable_if/pass_object_size/...
11230 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11231 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11232 if (!FD)
11233 return nullptr;
11234
11235 if (!checkAddressOfFunctionIsAvailable(FD))
11236 continue;
11237
11238 // We have more than one result; quit.
11239 if (Result)
11240 return nullptr;
11241 DAP = I.getPair();
11242 Result = FD;
11243 }
11244
11245 if (Result)
11246 Pair = DAP;
11247 return Result;
11248}
11249
George Burgess IVbeca4a32016-06-08 00:34:22 +000011250/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11251/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11252/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011253/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011254///
11255/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11256/// Otherwise, returns true. This may emit diagnostics and return true.
11257bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011258 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011259 Expr *E = SrcExpr.get();
11260 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11261
11262 DeclAccessPair DAP;
11263 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11264 if (!Found)
11265 return false;
11266
11267 // Emitting multiple diagnostics for a function that is both inaccessible and
11268 // unavailable is consistent with our behavior elsewhere. So, always check
11269 // for both.
11270 DiagnoseUseOfDecl(Found, E->getExprLoc());
11271 CheckAddressOfMemberAccess(E, DAP);
11272 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011273 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011274 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11275 else
11276 SrcExpr = Fixed;
11277 return true;
11278}
11279
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011280/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011281/// resolve that overloaded function expression down to a single function.
11282///
11283/// This routine can only resolve template-ids that refer to a single function
11284/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011285/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011286/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011287///
11288/// If no template-ids are found, no diagnostics are emitted and NULL is
11289/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011290FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011291Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011292 bool Complain,
11293 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011294 // C++ [over.over]p1:
11295 // [...] [Note: any redundant set of parentheses surrounding the
11296 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011297 // C++ [over.over]p1:
11298 // [...] The overloaded function name can be preceded by the &
11299 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011300
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011301 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011302 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011304
11305 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011306 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011307 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011308
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011309 // Look through all of the overloaded functions, searching for one
11310 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011311 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011312 for (UnresolvedSetIterator I = ovl->decls_begin(),
11313 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011314 // C++0x [temp.arg.explicit]p3:
11315 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011316 // where deduction is not done, if a template argument list is
11317 // specified and it, along with any default template arguments,
11318 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011319 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011320 FunctionTemplateDecl *FunctionTemplate
11321 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011322
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011323 // C++ [over.over]p2:
11324 // If the name is a function template, template argument deduction is
11325 // done (14.8.2.2), and if the argument deduction succeeds, the
11326 // resulting template argument list is used to generate a single
11327 // function template specialization, which is added to the set of
11328 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011329 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011330 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011331 if (TemplateDeductionResult Result
11332 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011333 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011334 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011335 // Make a note of the failed deduction for diagnostics.
11336 // TODO: Actually use the failed-deduction info?
11337 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011338 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011339 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011340 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011341 }
11342
John McCall0009fcc2011-04-26 20:42:42 +000011343 assert(Specialization && "no specialization and no error?");
11344
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011345 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011346 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011347 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011348 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11349 << ovl->getName();
11350 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011351 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011352 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011353 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011354
John McCall0009fcc2011-04-26 20:42:42 +000011355 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011356 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011358
Richard Smith9095e5b2016-11-01 01:31:23 +000011359 if (Matched &&
11360 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011361 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011362
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011363 return Matched;
11364}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011365
John McCall50a2c2c2011-10-11 23:14:30 +000011366// Resolve and fix an overloaded expression that can be resolved
11367// because it identifies a single function template specialization.
11368//
Douglas Gregor1beec452011-03-12 01:48:56 +000011369// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011370//
11371// Return true if it was logically possible to so resolve the
11372// expression, regardless of whether or not it succeeded. Always
11373// returns true if 'complain' is set.
11374bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11375 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011376 bool complain, SourceRange OpRangeForComplaining,
11377 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011378 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011379 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011380
John McCall50a2c2c2011-10-11 23:14:30 +000011381 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011382
John McCall0009fcc2011-04-26 20:42:42 +000011383 DeclAccessPair found;
11384 ExprResult SingleFunctionExpression;
11385 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11386 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011387 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011388 SrcExpr = ExprError();
11389 return true;
11390 }
John McCall0009fcc2011-04-26 20:42:42 +000011391
11392 // It is only correct to resolve to an instance method if we're
11393 // resolving a form that's permitted to be a pointer to member.
11394 // Otherwise we'll end up making a bound member expression, which
11395 // is illegal in all the contexts we resolve like this.
11396 if (!ovl.HasFormOfMemberPointer &&
11397 isa<CXXMethodDecl>(fn) &&
11398 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011399 if (!complain) return false;
11400
11401 Diag(ovl.Expression->getExprLoc(),
11402 diag::err_bound_member_function)
11403 << 0 << ovl.Expression->getSourceRange();
11404
11405 // TODO: I believe we only end up here if there's a mix of
11406 // static and non-static candidates (otherwise the expression
11407 // would have 'bound member' type, not 'overload' type).
11408 // Ideally we would note which candidate was chosen and why
11409 // the static candidates were rejected.
11410 SrcExpr = ExprError();
11411 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011412 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011413
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011414 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011415 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011416 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011417
11418 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011419 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011420 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011421 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011422 if (SingleFunctionExpression.isInvalid()) {
11423 SrcExpr = ExprError();
11424 return true;
11425 }
11426 }
John McCall0009fcc2011-04-26 20:42:42 +000011427 }
11428
11429 if (!SingleFunctionExpression.isUsable()) {
11430 if (complain) {
11431 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11432 << ovl.Expression->getName()
11433 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011434 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011435 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011436 NoteAllOverloadCandidates(SrcExpr.get());
11437
11438 SrcExpr = ExprError();
11439 return true;
11440 }
11441
11442 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011443 }
11444
John McCall50a2c2c2011-10-11 23:14:30 +000011445 SrcExpr = SingleFunctionExpression;
11446 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011447}
11448
Douglas Gregorcabea402009-09-22 15:41:20 +000011449/// \brief Add a single candidate to the overload set.
11450static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011451 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011452 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011453 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011454 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011455 bool PartialOverloading,
11456 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011457 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011458 if (isa<UsingShadowDecl>(Callee))
11459 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11460
Douglas Gregorcabea402009-09-22 15:41:20 +000011461 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011462 if (ExplicitTemplateArgs) {
11463 assert(!KnownValid && "Explicit template arguments?");
11464 return;
11465 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011466 // Prevent ill-formed function decls to be added as overload candidates.
11467 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11468 return;
11469
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011470 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11471 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011472 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011473 return;
John McCalld14a8642009-11-21 08:51:07 +000011474 }
11475
11476 if (FunctionTemplateDecl *FuncTemplate
11477 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011478 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011479 ExplicitTemplateArgs, Args, CandidateSet,
11480 /*SuppressUsedConversions=*/false,
11481 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011482 return;
11483 }
11484
Richard Smith95ce4f62011-06-26 22:19:54 +000011485 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011486}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011487
Douglas Gregorcabea402009-09-22 15:41:20 +000011488/// \brief Add the overload candidates named by callee and/or found by argument
11489/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011490void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011491 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011492 OverloadCandidateSet &CandidateSet,
11493 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011494
11495#ifndef NDEBUG
11496 // Verify that ArgumentDependentLookup is consistent with the rules
11497 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011498 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011499 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11500 // and let Y be the lookup set produced by argument dependent
11501 // lookup (defined as follows). If X contains
11502 //
11503 // -- a declaration of a class member, or
11504 //
11505 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011506 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011507 //
11508 // -- a declaration that is neither a function or a function
11509 // template
11510 //
11511 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011512
John McCall57500772009-12-16 12:17:52 +000011513 if (ULE->requiresADL()) {
11514 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11515 E = ULE->decls_end(); I != E; ++I) {
11516 assert(!(*I)->getDeclContext()->isRecord());
11517 assert(isa<UsingShadowDecl>(*I) ||
11518 !(*I)->getDeclContext()->isFunctionOrMethod());
11519 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011520 }
11521 }
11522#endif
11523
John McCall57500772009-12-16 12:17:52 +000011524 // It would be nice to avoid this copy.
11525 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011526 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011527 if (ULE->hasExplicitTemplateArgs()) {
11528 ULE->copyTemplateArgumentsInto(TABuffer);
11529 ExplicitTemplateArgs = &TABuffer;
11530 }
11531
11532 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11533 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011534 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11535 CandidateSet, PartialOverloading,
11536 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011537
John McCall57500772009-12-16 12:17:52 +000011538 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011539 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011540 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011541 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011542}
John McCalld681c392009-12-16 08:11:27 +000011543
Richard Smith0603bbb2013-06-12 22:56:54 +000011544/// Determine whether a declaration with the specified name could be moved into
11545/// a different namespace.
11546static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11547 switch (Name.getCXXOverloadedOperator()) {
11548 case OO_New: case OO_Array_New:
11549 case OO_Delete: case OO_Array_Delete:
11550 return false;
11551
11552 default:
11553 return true;
11554 }
11555}
11556
Richard Smith998a5912011-06-05 22:42:48 +000011557/// Attempt to recover from an ill-formed use of a non-dependent name in a
11558/// template, where the non-dependent name was declared after the template
11559/// was defined. This is common in code written for a compilers which do not
11560/// correctly implement two-stage name lookup.
11561///
11562/// Returns true if a viable candidate was found and a diagnostic was issued.
11563static bool
11564DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11565 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011566 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011567 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011568 ArrayRef<Expr *> Args,
11569 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011570 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011571 return false;
11572
11573 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011574 if (DC->isTransparentContext())
11575 continue;
11576
Richard Smith998a5912011-06-05 22:42:48 +000011577 SemaRef.LookupQualifiedName(R, DC);
11578
11579 if (!R.empty()) {
11580 R.suppressDiagnostics();
11581
11582 if (isa<CXXRecordDecl>(DC)) {
11583 // Don't diagnose names we find in classes; we get much better
11584 // diagnostics for these from DiagnoseEmptyLookup.
11585 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011586 if (DoDiagnoseEmptyLookup)
11587 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011588 return false;
11589 }
11590
Richard Smith100b24a2014-04-17 01:52:14 +000011591 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011592 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11593 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011594 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011595 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011596
11597 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011598 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011599 // No viable functions. Don't bother the user with notes for functions
11600 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011601 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011602 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011603 }
Richard Smith998a5912011-06-05 22:42:48 +000011604
11605 // Find the namespaces where ADL would have looked, and suggest
11606 // declaring the function there instead.
11607 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11608 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011609 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011610 AssociatedNamespaces,
11611 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011612 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011613 if (canBeDeclaredInNamespace(R.getLookupName())) {
11614 DeclContext *Std = SemaRef.getStdNamespace();
11615 for (Sema::AssociatedNamespaceSet::iterator
11616 it = AssociatedNamespaces.begin(),
11617 end = AssociatedNamespaces.end(); it != end; ++it) {
11618 // Never suggest declaring a function within namespace 'std'.
11619 if (Std && Std->Encloses(*it))
11620 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011621
Richard Smith0603bbb2013-06-12 22:56:54 +000011622 // Never suggest declaring a function within a namespace with a
11623 // reserved name, like __gnu_cxx.
11624 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11625 if (NS &&
11626 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11627 continue;
11628
11629 SuggestedNamespaces.insert(*it);
11630 }
Richard Smith998a5912011-06-05 22:42:48 +000011631 }
11632
11633 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11634 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011635 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011636 SemaRef.Diag(Best->Function->getLocation(),
11637 diag::note_not_found_by_two_phase_lookup)
11638 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011639 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011640 SemaRef.Diag(Best->Function->getLocation(),
11641 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011642 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011643 } else {
11644 // FIXME: It would be useful to list the associated namespaces here,
11645 // but the diagnostics infrastructure doesn't provide a way to produce
11646 // a localized representation of a list of items.
11647 SemaRef.Diag(Best->Function->getLocation(),
11648 diag::note_not_found_by_two_phase_lookup)
11649 << R.getLookupName() << 2;
11650 }
11651
11652 // Try to recover by calling this function.
11653 return true;
11654 }
11655
11656 R.clear();
11657 }
11658
11659 return false;
11660}
11661
11662/// Attempt to recover from ill-formed use of a non-dependent operator in a
11663/// template, where the non-dependent operator was declared after the template
11664/// was defined.
11665///
11666/// Returns true if a viable candidate was found and a diagnostic was issued.
11667static bool
11668DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11669 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011670 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011671 DeclarationName OpName =
11672 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11673 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11674 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011675 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011676 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011677}
11678
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011679namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011680class BuildRecoveryCallExprRAII {
11681 Sema &SemaRef;
11682public:
11683 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11684 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11685 SemaRef.IsBuildingRecoveryCallExpr = true;
11686 }
11687
11688 ~BuildRecoveryCallExprRAII() {
11689 SemaRef.IsBuildingRecoveryCallExpr = false;
11690 }
11691};
11692
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011693}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011694
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011695static std::unique_ptr<CorrectionCandidateCallback>
11696MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11697 bool HasTemplateArgs, bool AllowTypoCorrection) {
11698 if (!AllowTypoCorrection)
11699 return llvm::make_unique<NoTypoCorrectionCCC>();
11700 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11701 HasTemplateArgs, ME);
11702}
11703
John McCalld681c392009-12-16 08:11:27 +000011704/// Attempts to recover from a call where no functions were found.
11705///
11706/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011707static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011708BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011709 UnresolvedLookupExpr *ULE,
11710 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011711 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011712 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011713 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011714 // Do not try to recover if it is already building a recovery call.
11715 // This stops infinite loops for template instantiations like
11716 //
11717 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11718 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11719 //
11720 if (SemaRef.IsBuildingRecoveryCallExpr)
11721 return ExprError();
11722 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011723
11724 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011725 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011726 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011727
John McCall57500772009-12-16 12:17:52 +000011728 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011729 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011730 if (ULE->hasExplicitTemplateArgs()) {
11731 ULE->copyTemplateArgumentsInto(TABuffer);
11732 ExplicitTemplateArgs = &TABuffer;
11733 }
11734
John McCalld681c392009-12-16 08:11:27 +000011735 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11736 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011737 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011738 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011739 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011740 ExplicitTemplateArgs, Args,
11741 &DoDiagnoseEmptyLookup) &&
11742 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11743 S, SS, R,
11744 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11745 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11746 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011747 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011748
John McCall57500772009-12-16 12:17:52 +000011749 assert(!R.empty() && "lookup results empty despite recovery");
11750
Richard Smith151c4562016-12-20 21:35:28 +000011751 // If recovery created an ambiguity, just bail out.
11752 if (R.isAmbiguous()) {
11753 R.suppressDiagnostics();
11754 return ExprError();
11755 }
11756
John McCall57500772009-12-16 12:17:52 +000011757 // Build an implicit member call if appropriate. Just drop the
11758 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011759 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011760 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011761 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11762 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011763 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011764 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011765 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011766 else
11767 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11768
11769 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011770 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011771
11772 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011773 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011774 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011775 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011776 MultiExprArg(Args.data(), Args.size()),
11777 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011778}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011779
Sam Panzer0f384432012-08-21 00:52:01 +000011780/// \brief Constructs and populates an OverloadedCandidateSet from
11781/// the given function.
11782/// \returns true when an the ExprResult output parameter has been set.
11783bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11784 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011785 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011786 SourceLocation RParenLoc,
11787 OverloadCandidateSet *CandidateSet,
11788 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011789#ifndef NDEBUG
11790 if (ULE->requiresADL()) {
11791 // To do ADL, we must have found an unqualified name.
11792 assert(!ULE->getQualifier() && "qualified name with ADL");
11793
11794 // We don't perform ADL for implicit declarations of builtins.
11795 // Verify that this was correctly set up.
11796 FunctionDecl *F;
11797 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11798 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11799 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011800 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011801
John McCall57500772009-12-16 12:17:52 +000011802 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011803 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011804 }
John McCall57500772009-12-16 12:17:52 +000011805#endif
11806
John McCall4124c492011-10-17 18:40:02 +000011807 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011808 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011809 *Result = ExprError();
11810 return true;
11811 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011812
John McCall57500772009-12-16 12:17:52 +000011813 // Add the functions denoted by the callee to the set of candidate
11814 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011815 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011816
Hans Wennborgb2747382015-06-12 21:23:23 +000011817 if (getLangOpts().MSVCCompat &&
11818 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011819 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11820
11821 OverloadCandidateSet::iterator Best;
11822 if (CandidateSet->empty() ||
11823 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11824 OR_No_Viable_Function) {
11825 // In Microsoft mode, if we are inside a template class member function then
11826 // create a type dependent CallExpr. The goal is to postpone name lookup
11827 // to instantiation time to be able to search into type dependent base
11828 // classes.
11829 CallExpr *CE = new (Context) CallExpr(
11830 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011831 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011832 CE->setValueDependent(true);
11833 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011834 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011835 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011836 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011837 }
John McCalld681c392009-12-16 08:11:27 +000011838
Hans Wennborg64937c62015-06-11 21:21:57 +000011839 if (CandidateSet->empty())
11840 return false;
11841
John McCall4124c492011-10-17 18:40:02 +000011842 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011843 return false;
11844}
John McCall4124c492011-10-17 18:40:02 +000011845
Sam Panzer0f384432012-08-21 00:52:01 +000011846/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11847/// the completed call expression. If overload resolution fails, emits
11848/// diagnostics and returns ExprError()
11849static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11850 UnresolvedLookupExpr *ULE,
11851 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011852 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011853 SourceLocation RParenLoc,
11854 Expr *ExecConfig,
11855 OverloadCandidateSet *CandidateSet,
11856 OverloadCandidateSet::iterator *Best,
11857 OverloadingResult OverloadResult,
11858 bool AllowTypoCorrection) {
11859 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011860 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011861 RParenLoc, /*EmptyLookup=*/true,
11862 AllowTypoCorrection);
11863
11864 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011865 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011866 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011867 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011868 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11869 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011870 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011871 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11872 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011873 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011874
Richard Smith998a5912011-06-05 22:42:48 +000011875 case OR_No_Viable_Function: {
11876 // Try to recover by looking for viable functions which the user might
11877 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011878 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011879 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011880 /*EmptyLookup=*/false,
11881 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011882 if (!Recovery.isInvalid())
11883 return Recovery;
11884
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011885 // If the user passes in a function that we can't take the address of, we
11886 // generally end up emitting really bad error messages. Here, we attempt to
11887 // emit better ones.
11888 for (const Expr *Arg : Args) {
11889 if (!Arg->getType()->isFunctionType())
11890 continue;
11891 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11892 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11893 if (FD &&
11894 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11895 Arg->getExprLoc()))
11896 return ExprError();
11897 }
11898 }
11899
11900 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11901 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011902 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011903 break;
Richard Smith998a5912011-06-05 22:42:48 +000011904 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011905
11906 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011907 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011908 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011909 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011910 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011911
Sam Panzer0f384432012-08-21 00:52:01 +000011912 case OR_Deleted: {
11913 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11914 << (*Best)->Function->isDeleted()
11915 << ULE->getName()
11916 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11917 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011918 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011919
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011920 // We emitted an error for the unavailable/deleted function call but keep
Sam Panzer0f384432012-08-21 00:52:01 +000011921 // the call in the AST.
11922 FunctionDecl *FDecl = (*Best)->Function;
11923 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011924 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11925 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011926 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011927 }
11928
Douglas Gregorb412e172010-07-25 18:17:45 +000011929 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011930 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011931}
11932
George Burgess IV7204ed92016-01-07 02:26:57 +000011933static void markUnaddressableCandidatesUnviable(Sema &S,
11934 OverloadCandidateSet &CS) {
11935 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11936 if (I->Viable &&
11937 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11938 I->Viable = false;
11939 I->FailureKind = ovl_fail_addr_not_available;
11940 }
11941 }
11942}
11943
Sam Panzer0f384432012-08-21 00:52:01 +000011944/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11945/// (which eventually refers to the declaration Func) and the call
11946/// arguments Args/NumArgs, attempt to resolve the function call down
11947/// to a specific function. If overload resolution succeeds, returns
11948/// the call expression produced by overload resolution.
11949/// Otherwise, emits diagnostics and returns ExprError.
11950ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11951 UnresolvedLookupExpr *ULE,
11952 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011953 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011954 SourceLocation RParenLoc,
11955 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011956 bool AllowTypoCorrection,
11957 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011958 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11959 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011960 ExprResult result;
11961
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011962 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11963 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011964 return result;
11965
George Burgess IV7204ed92016-01-07 02:26:57 +000011966 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11967 // functions that aren't addressible are considered unviable.
11968 if (CalleesAddressIsTaken)
11969 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11970
Sam Panzer0f384432012-08-21 00:52:01 +000011971 OverloadCandidateSet::iterator Best;
11972 OverloadingResult OverloadResult =
11973 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11974
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011975 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011976 RParenLoc, ExecConfig, &CandidateSet,
11977 &Best, OverloadResult,
11978 AllowTypoCorrection);
11979}
11980
John McCall4c4c1df2010-01-26 03:27:55 +000011981static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011982 return Functions.size() > 1 ||
11983 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11984}
11985
Douglas Gregor084d8552009-03-13 23:49:33 +000011986/// \brief Create a unary operation that may resolve to an overloaded
11987/// operator.
11988///
11989/// \param OpLoc The location of the operator itself (e.g., '*').
11990///
Craig Toppera92ffb02015-12-10 08:51:49 +000011991/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011992///
James Dennett18348b62012-06-22 08:52:37 +000011993/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011994/// considered by overload resolution. The caller needs to build this
11995/// set based on the context using, e.g.,
11996/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11997/// set should not contain any member functions; those will be added
11998/// by CreateOverloadedUnaryOp().
11999///
James Dennett91738ff2012-06-22 10:32:46 +000012000/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000012001ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000012002Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012003 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012004 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012005 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12006 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12007 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012008 // TODO: provide better source location info.
12009 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012010
John McCall4124c492011-10-17 18:40:02 +000012011 if (checkPlaceholderForOverload(*this, Input))
12012 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012013
Craig Topperc3ec1492014-05-26 06:22:03 +000012014 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012015 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012016
Douglas Gregor084d8552009-03-13 23:49:33 +000012017 // For post-increment and post-decrement, add the implicit '0' as
12018 // the second argument, so that we know this is a post-increment or
12019 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012020 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012021 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012022 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12023 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012024 NumArgs = 2;
12025 }
12026
Richard Smithe54c3072013-05-05 15:51:06 +000012027 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12028
Douglas Gregor084d8552009-03-13 23:49:33 +000012029 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012030 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012031 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
Aaron Ballmana5038552018-01-09 13:07:03 +000012032 VK_RValue, OK_Ordinary, OpLoc, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012033
Craig Topperc3ec1492014-05-26 06:22:03 +000012034 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012035 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012036 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012037 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012038 /*ADL*/ true, IsOverloaded(Fns),
12039 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012040 return new (Context)
12041 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012042 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012043 }
12044
12045 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012046 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012047
12048 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012049 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012050
12051 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012052 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012053
John McCall4c4c1df2010-01-26 03:27:55 +000012054 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000012055 if (PerformADL) {
12056 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12057 /*ExplicitTemplateArgs*/nullptr,
12058 CandidateSet);
12059 }
John McCall4c4c1df2010-01-26 03:27:55 +000012060
Douglas Gregor084d8552009-03-13 23:49:33 +000012061 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012062 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012063
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012064 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12065
Douglas Gregor084d8552009-03-13 23:49:33 +000012066 // Perform overload resolution.
12067 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012068 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012069 case OR_Success: {
12070 // We found a built-in operator or an overloaded operator.
12071 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012072
Douglas Gregor084d8552009-03-13 23:49:33 +000012073 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012074 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012075 // We matched an overloaded operator. Build a call to that
12076 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012077
Douglas Gregor084d8552009-03-13 23:49:33 +000012078 // Convert the arguments.
12079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012080 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012081
John Wiegley01296292011-04-08 18:41:53 +000012082 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012083 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012084 Best->FoundDecl, Method);
12085 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012086 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012087 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012088 } else {
12089 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012090 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012091 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012092 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012093 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012094 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012095 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012096 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012097 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012098 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012099 }
12100
Douglas Gregor084d8552009-03-13 23:49:33 +000012101 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012102 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012103 Base, HadMultipleCandidates,
12104 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012105 if (FnExpr.isInvalid())
12106 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012107
Richard Smithc1564702013-11-15 02:58:23 +000012108 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012109 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012110 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12111 ResultTy = ResultTy.getNonLValueExprType(Context);
12112
Eli Friedman030eee42009-11-18 03:58:17 +000012113 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012114 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012115 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012116 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012117
Alp Toker314cc812014-01-25 16:55:45 +000012118 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012119 return ExprError();
12120
George Burgess IVce6284b2017-01-28 02:19:40 +000012121 if (CheckFunctionCall(FnDecl, TheCall,
12122 FnDecl->getType()->castAs<FunctionProtoType>()))
12123 return ExprError();
12124
John McCallb268a282010-08-23 23:25:46 +000012125 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012126 } else {
12127 // We matched a built-in operator. Convert the arguments, then
12128 // break out so that we will build the appropriate built-in
12129 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012130 ExprResult InputRes = PerformImplicitConversion(
12131 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012132 if (InputRes.isInvalid())
12133 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012134 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012135 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012136 }
John Wiegley01296292011-04-08 18:41:53 +000012137 }
12138
12139 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012140 // This is an erroneous use of an operator which can be overloaded by
12141 // a non-member function. Check for non-member operators which were
12142 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012143 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012144 // FIXME: Recover by calling the found function.
12145 return ExprError();
12146
John Wiegley01296292011-04-08 18:41:53 +000012147 // No viable function; fall through to handling this as a
12148 // built-in operator, which will produce an error message for us.
12149 break;
12150
12151 case OR_Ambiguous:
12152 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12153 << UnaryOperator::getOpcodeStr(Opc)
12154 << Input->getType()
12155 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012156 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012157 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12158 return ExprError();
12159
12160 case OR_Deleted:
12161 Diag(OpLoc, diag::err_ovl_deleted_oper)
12162 << Best->Function->isDeleted()
12163 << UnaryOperator::getOpcodeStr(Opc)
12164 << getDeletedOrUnavailableSuffix(Best->Function)
12165 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012166 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012167 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012168 return ExprError();
12169 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012170
12171 // Either we found no viable overloaded operator or we matched a
12172 // built-in operator. In either case, fall through to trying to
12173 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012174 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012175}
12176
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012177/// \brief Create a binary operation that may resolve to an overloaded
12178/// operator.
12179///
12180/// \param OpLoc The location of the operator itself (e.g., '+').
12181///
Craig Toppera92ffb02015-12-10 08:51:49 +000012182/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012183///
James Dennett18348b62012-06-22 08:52:37 +000012184/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012185/// considered by overload resolution. The caller needs to build this
12186/// set based on the context using, e.g.,
12187/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12188/// set should not contain any member functions; those will be added
12189/// by CreateOverloadedBinOp().
12190///
12191/// \param LHS Left-hand argument.
12192/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012193ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012194Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012195 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012196 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012197 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012198 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012199 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012200
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012201 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12202 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12203
12204 // If either side is type-dependent, create an appropriate dependent
12205 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012206 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012207 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012208 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012209 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012210 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012211 return new (Context) BinaryOperator(
12212 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012213 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012214
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012215 return new (Context) CompoundAssignOperator(
12216 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12217 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012218 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012219 }
John McCall4c4c1df2010-01-26 03:27:55 +000012220
12221 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012222 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012223 // TODO: provide better source location info in DNLoc component.
12224 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012225 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012226 = UnresolvedLookupExpr::Create(Context, NamingClass,
12227 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012228 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012229 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012230 return new (Context)
12231 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012232 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012233 }
12234
John McCall4124c492011-10-17 18:40:02 +000012235 // Always do placeholder-like conversions on the RHS.
12236 if (checkPlaceholderForOverload(*this, Args[1]))
12237 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012238
John McCall526ab472011-10-25 17:37:35 +000012239 // Do placeholder-like conversion on the LHS; note that we should
12240 // not get here with a PseudoObject LHS.
12241 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012242 if (checkPlaceholderForOverload(*this, Args[0]))
12243 return ExprError();
12244
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012245 // If this is the assignment operator, we only perform overload resolution
12246 // if the left-hand side is a class or enumeration type. This is actually
12247 // a hack. The standard requires that we do overload resolution between the
12248 // various built-in candidates, but as DR507 points out, this can lead to
12249 // problems. So we do it this way, which pretty much follows what GCC does.
12250 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012251 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012252 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012253
John McCalle26a8722010-12-04 08:14:53 +000012254 // If this is the .* operator, which is not overloadable, just
12255 // create a built-in binary operator.
12256 if (Opc == BO_PtrMemD)
12257 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12258
Douglas Gregor084d8552009-03-13 23:49:33 +000012259 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012260 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012261
12262 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012263 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012264
12265 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012266 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012267
Richard Smith0daabd72014-09-23 20:31:39 +000012268 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12269 // performed for an assignment operator (nor for operator[] nor operator->,
12270 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012271 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012272 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12273 /*ExplicitTemplateArgs*/ nullptr,
12274 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012275
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012276 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012277 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012278
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012279 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12280
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012281 // Perform overload resolution.
12282 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012283 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012284 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012285 // We found a built-in operator or an overloaded operator.
12286 FunctionDecl *FnDecl = Best->Function;
12287
12288 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012289 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012290 // We matched an overloaded operator. Build a call to that
12291 // operator.
12292
12293 // Convert the arguments.
12294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012295 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012296 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012297
Chandler Carruth8e543b32010-12-12 08:17:55 +000012298 ExprResult Arg1 =
12299 PerformCopyInitialization(
12300 InitializedEntity::InitializeParameter(Context,
12301 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012302 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012303 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012304 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012305
John Wiegley01296292011-04-08 18:41:53 +000012306 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012307 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012308 Best->FoundDecl, Method);
12309 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012310 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012311 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012312 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012313 } else {
12314 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012315 ExprResult Arg0 = PerformCopyInitialization(
12316 InitializedEntity::InitializeParameter(Context,
12317 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012318 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012319 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012320 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012321
Chandler Carruth8e543b32010-12-12 08:17:55 +000012322 ExprResult Arg1 =
12323 PerformCopyInitialization(
12324 InitializedEntity::InitializeParameter(Context,
12325 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012326 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012327 if (Arg1.isInvalid())
12328 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012329 Args[0] = LHS = Arg0.getAs<Expr>();
12330 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012331 }
12332
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012333 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012334 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012335 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012336 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012337 if (FnExpr.isInvalid())
12338 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012339
Richard Smithc1564702013-11-15 02:58:23 +000012340 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012341 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012342 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12343 ResultTy = ResultTy.getNonLValueExprType(Context);
12344
John McCallb268a282010-08-23 23:25:46 +000012345 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012346 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012347 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012348 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012349
Alp Toker314cc812014-01-25 16:55:45 +000012350 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012351 FnDecl))
12352 return ExprError();
12353
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012354 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012355 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012356 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012357 if (isa<CXXMethodDecl>(FnDecl)) {
12358 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012359 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012360 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012361
12362 // Check for a self move.
12363 if (Op == OO_Equal)
12364 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12365
George Burgess IVce6284b2017-01-28 02:19:40 +000012366 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12367 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12368 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012369
John McCallb268a282010-08-23 23:25:46 +000012370 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012371 } else {
12372 // We matched a built-in operator. Convert the arguments, then
12373 // break out so that we will build the appropriate built-in
12374 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012375 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012376 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12377 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012378 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012379 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012380 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012381
John Wiegley01296292011-04-08 18:41:53 +000012382 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012383 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12384 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012385 if (ArgsRes1.isInvalid())
12386 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012387 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012388 break;
12389 }
12390 }
12391
Douglas Gregor66950a32009-09-30 21:46:01 +000012392 case OR_No_Viable_Function: {
12393 // C++ [over.match.oper]p9:
12394 // If the operator is the operator , [...] and there are no
12395 // viable functions, then the operator is assumed to be the
12396 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012397 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012398 break;
12399
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012400 // For class as left operand for assignment or compound assignment
Chandler Carruth8e543b32010-12-12 08:17:55 +000012401 // operator do not fall through to handling in built-in, but report that
12402 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012403 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012404 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012405 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012406 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12407 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012409 if (Args[0]->getType()->isIncompleteType()) {
12410 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12411 << Args[0]->getType()
12412 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12413 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012414 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012415 // This is an erroneous use of an operator which can be overloaded by
12416 // a non-member function. Check for non-member operators which were
12417 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012418 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012419 // FIXME: Recover by calling the found function.
12420 return ExprError();
12421
Douglas Gregor66950a32009-09-30 21:46:01 +000012422 // No viable function; try to create a built-in operation, which will
12423 // produce an error. Then, show the non-viable candidates.
12424 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012426 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012427 "C++ binary operator overloading is missing candidates!");
12428 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012429 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012430 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012431 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012432 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012433
12434 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012435 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012436 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012437 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012438 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012439 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012440 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012441 return ExprError();
12442
12443 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012444 if (isImplicitlyDeleted(Best->Function)) {
12445 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12446 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012447 << Context.getRecordType(Method->getParent())
12448 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012449
Richard Smithde1a4872012-12-28 12:23:24 +000012450 // The user probably meant to call this special member. Just
12451 // explain why it's deleted.
12452 NoteDeletedFunction(Method);
12453 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012454 } else {
12455 Diag(OpLoc, diag::err_ovl_deleted_oper)
12456 << Best->Function->isDeleted()
12457 << BinaryOperator::getOpcodeStr(Opc)
12458 << getDeletedOrUnavailableSuffix(Best->Function)
12459 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12460 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012461 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012462 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012463 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012464 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012465
Douglas Gregor66950a32009-09-30 21:46:01 +000012466 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012467 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012468}
12469
John McCalldadc5752010-08-24 06:29:42 +000012470ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012471Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12472 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012473 Expr *Base, Expr *Idx) {
12474 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012475 DeclarationName OpName =
12476 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12477
12478 // If either side is type-dependent, create an appropriate dependent
12479 // expression.
12480 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12481
Craig Topperc3ec1492014-05-26 06:22:03 +000012482 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012483 // CHECKME: no 'operator' keyword?
12484 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12485 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012486 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012487 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012488 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012489 /*ADL*/ true, /*Overloaded*/ false,
12490 UnresolvedSetIterator(),
12491 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012492 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012493
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012494 return new (Context)
12495 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012496 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012497 }
12498
John McCall4124c492011-10-17 18:40:02 +000012499 // Handle placeholders on both operands.
12500 if (checkPlaceholderForOverload(*this, Args[0]))
12501 return ExprError();
12502 if (checkPlaceholderForOverload(*this, Args[1]))
12503 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012504
Sebastian Redladba46e2009-10-29 20:17:01 +000012505 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012506 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012507
12508 // Subscript can only be overloaded as a member function.
12509
12510 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012511 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012512
12513 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012514 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012515
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012516 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12517
Sebastian Redladba46e2009-10-29 20:17:01 +000012518 // Perform overload resolution.
12519 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012520 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012521 case OR_Success: {
12522 // We found a built-in operator or an overloaded operator.
12523 FunctionDecl *FnDecl = Best->Function;
12524
12525 if (FnDecl) {
12526 // We matched an overloaded operator. Build a call to that
12527 // operator.
12528
John McCalla0296f72010-03-19 07:35:19 +000012529 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012530
Sebastian Redladba46e2009-10-29 20:17:01 +000012531 // Convert the arguments.
12532 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012533 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012534 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012535 Best->FoundDecl, Method);
12536 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012537 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012538 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012539
Anders Carlssona68e51e2010-01-29 18:37:50 +000012540 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012541 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012542 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012543 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012544 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012545 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012546 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012547 if (InputInit.isInvalid())
12548 return ExprError();
12549
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012550 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012551
Sebastian Redladba46e2009-10-29 20:17:01 +000012552 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012553 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12554 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012555 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012556 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012557 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012558 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012559 OpLocInfo.getLoc(),
12560 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012561 if (FnExpr.isInvalid())
12562 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012563
Richard Smithc1564702013-11-15 02:58:23 +000012564 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012565 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012566 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12567 ResultTy = ResultTy.getNonLValueExprType(Context);
12568
John McCallb268a282010-08-23 23:25:46 +000012569 CXXOperatorCallExpr *TheCall =
12570 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012571 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012572 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012573 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012574
Alp Toker314cc812014-01-25 16:55:45 +000012575 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012576 return ExprError();
12577
George Burgess IVce6284b2017-01-28 02:19:40 +000012578 if (CheckFunctionCall(Method, TheCall,
12579 Method->getType()->castAs<FunctionProtoType>()))
12580 return ExprError();
12581
John McCallb268a282010-08-23 23:25:46 +000012582 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012583 } else {
12584 // We matched a built-in operator. Convert the arguments, then
12585 // break out so that we will build the appropriate built-in
12586 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012587 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012588 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12589 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012590 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012591 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012592 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012593
12594 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012595 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12596 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012597 if (ArgsRes1.isInvalid())
12598 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012599 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012600
12601 break;
12602 }
12603 }
12604
12605 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012606 if (CandidateSet.empty())
12607 Diag(LLoc, diag::err_ovl_no_oper)
12608 << Args[0]->getType() << /*subscript*/ 0
12609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12610 else
12611 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12612 << Args[0]->getType()
12613 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012614 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012615 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012616 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012617 }
12618
12619 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012620 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012621 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012622 << Args[0]->getType() << Args[1]->getType()
12623 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012624 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012625 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012626 return ExprError();
12627
12628 case OR_Deleted:
12629 Diag(LLoc, diag::err_ovl_deleted_oper)
12630 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012631 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012632 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012633 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012634 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012635 return ExprError();
12636 }
12637
12638 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012639 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012640}
12641
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012642/// BuildCallToMemberFunction - Build a call to a member
12643/// function. MemExpr is the expression that refers to the member
12644/// function (and includes the object parameter), Args/NumArgs are the
12645/// arguments to the function call (not including the object
12646/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012647/// expression refers to a non-static member function or an overloaded
12648/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012649ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012650Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012651 SourceLocation LParenLoc,
12652 MultiExprArg Args,
12653 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012654 assert(MemExprE->getType() == Context.BoundMemberTy ||
12655 MemExprE->getType() == Context.OverloadTy);
12656
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012657 // Dig out the member expression. This holds both the object
12658 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012659 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012660
John McCall0009fcc2011-04-26 20:42:42 +000012661 // Determine whether this is a call to a pointer-to-member function.
12662 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12663 assert(op->getType() == Context.BoundMemberTy);
12664 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12665
12666 QualType fnType =
12667 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12668
12669 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12670 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012671 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012672
12673 // Check that the object type isn't more qualified than the
12674 // member function we're calling.
12675 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12676
12677 QualType objectType = op->getLHS()->getType();
12678 if (op->getOpcode() == BO_PtrMemI)
12679 objectType = objectType->castAs<PointerType>()->getPointeeType();
12680 Qualifiers objectQuals = objectType.getQualifiers();
12681
12682 Qualifiers difference = objectQuals - funcQuals;
12683 difference.removeObjCGCAttr();
12684 difference.removeAddressSpace();
12685 if (difference) {
12686 std::string qualsString = difference.getAsString();
12687 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12688 << fnType.getUnqualifiedType()
12689 << qualsString
12690 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12691 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012692
John McCall0009fcc2011-04-26 20:42:42 +000012693 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012694 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012695 resultType, valueKind, RParenLoc);
12696
Alp Toker314cc812014-01-25 16:55:45 +000012697 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012698 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012699 return ExprError();
12700
Craig Topperc3ec1492014-05-26 06:22:03 +000012701 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012702 return ExprError();
12703
Richard Trieu9be9c682013-06-22 02:30:38 +000012704 if (CheckOtherCall(call, proto))
12705 return ExprError();
12706
John McCall0009fcc2011-04-26 20:42:42 +000012707 return MaybeBindToTemporary(call);
12708 }
12709
David Majnemerced8bdf2015-02-25 17:36:15 +000012710 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12711 return new (Context)
12712 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12713
John McCall4124c492011-10-17 18:40:02 +000012714 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012715 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012716 return ExprError();
12717
John McCall10eae182009-11-30 22:42:35 +000012718 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012719 CXXMethodDecl *Method = nullptr;
12720 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12721 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012722 if (isa<MemberExpr>(NakedMemExpr)) {
12723 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012724 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012725 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012726 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012727 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012728 } else {
12729 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012730 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012731
John McCall6e9f8f62009-12-03 04:06:58 +000012732 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012733 Expr::Classification ObjectClassification
12734 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12735 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012736
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012737 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012738 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12739 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012740
John McCall2d74de92009-12-01 22:10:20 +000012741 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012742 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012743 if (UnresExpr->hasExplicitTemplateArgs()) {
12744 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12745 TemplateArgs = &TemplateArgsBuffer;
12746 }
12747
John McCall10eae182009-11-30 22:42:35 +000012748 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12749 E = UnresExpr->decls_end(); I != E; ++I) {
12750
John McCall6e9f8f62009-12-03 04:06:58 +000012751 NamedDecl *Func = *I;
12752 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12753 if (isa<UsingShadowDecl>(Func))
12754 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12755
Douglas Gregor02824322011-01-26 19:30:28 +000012756
Francois Pichet64225792011-01-18 05:04:39 +000012757 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012758 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012759 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012760 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012761 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012762 // If explicit template arguments were provided, we can't call a
12763 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012764 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012765 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012766
John McCalla0296f72010-03-19 07:35:19 +000012767 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012768 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012769 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012770 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012771 AddMethodTemplateCandidate(
12772 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012773 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012774 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012775 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012776 }
Mike Stump11289f42009-09-09 15:08:12 +000012777
John McCall10eae182009-11-30 22:42:35 +000012778 DeclarationName DeclName = UnresExpr->getMemberName();
12779
John McCall4124c492011-10-17 18:40:02 +000012780 UnbridgedCasts.restore();
12781
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012782 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012783 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012784 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012785 case OR_Success:
12786 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012787 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012788 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012789 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12790 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012791 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012792 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012793 // called on both.
12794 // FIXME: This would be more comprehensively addressed by modifying
12795 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12796 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012797 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012798 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12799 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012800 break;
12801
12802 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012803 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012804 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012805 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012807 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012808 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012809
12810 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012811 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012812 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012813 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012814 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012815 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012816
12817 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012818 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012819 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012820 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012821 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012822 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012824 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012825 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012826 }
12827
John McCall16df1e52010-03-30 21:47:33 +000012828 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012829
John McCall2d74de92009-12-01 22:10:20 +000012830 // If overload resolution picked a static member, build a
12831 // non-member call based on that function.
12832 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012833 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12834 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012835 }
12836
John McCall10eae182009-11-30 22:42:35 +000012837 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012838 }
12839
Alp Toker314cc812014-01-25 16:55:45 +000012840 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012841 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12842 ResultType = ResultType.getNonLValueExprType(Context);
12843
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012844 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012845 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012846 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012847 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012848
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012849 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012850 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012851 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012852 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012853
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012854 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012855 // We only need to do this if there was actually an overload; otherwise
12856 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012857 if (!Method->isStatic()) {
12858 ExprResult ObjectArg =
12859 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12860 FoundDecl, Method);
12861 if (ObjectArg.isInvalid())
12862 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012863 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012864 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012865
12866 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012867 const FunctionProtoType *Proto =
12868 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012869 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012870 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012871 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012872
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012873 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012874
Richard Smith55ce3522012-06-25 20:30:08 +000012875 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012876 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012877
George Burgess IVaea6ade2015-09-25 17:53:16 +000012878 // In the case the method to call was not selected by the overloading
12879 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012880 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012881 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012882 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012883 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012884 diag::err_ovl_no_viable_member_function_in_call)
12885 << Method << Method->getSourceRange();
12886 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012887 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012888 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12889 return ExprError();
12890 }
12891 }
12892
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012893 if ((isa<CXXConstructorDecl>(CurContext) ||
12894 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000012895 TheCall->getMethodDecl()->isPure()) {
12896 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12897
Davide Italianoccb37382015-07-14 23:36:10 +000012898 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12899 MemExpr->performsVirtualDispatch(getLangOpts())) {
12900 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012901 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12902 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12903 << MD->getParent()->getDeclName();
12904
12905 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012906 if (getLangOpts().AppleKext)
12907 Diag(MemExpr->getLocStart(),
12908 diag::note_pure_qualified_call_kext)
12909 << MD->getParent()->getDeclName()
12910 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012911 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012912 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012913
12914 if (CXXDestructorDecl *DD =
12915 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12916 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012917 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012918 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12919 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12920 MemExpr->getMemberLoc());
12921 }
12922
John McCallb268a282010-08-23 23:25:46 +000012923 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012924}
12925
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012926/// BuildCallToObjectOfClassType - Build a call to an object of class
12927/// type (C++ [over.call.object]), which can end up invoking an
12928/// overloaded function call operator (@c operator()) or performing a
12929/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012930ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012931Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012932 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012933 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012934 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012935 if (checkPlaceholderForOverload(*this, Obj))
12936 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012937 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012938
12939 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012940 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012941 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012942
Nico Weberb58e51c2014-11-19 05:21:39 +000012943 assert(Object.get()->getType()->isRecordType() &&
12944 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012945 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012946
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012947 // C++ [over.call.object]p1:
12948 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012949 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012950 // candidate functions includes at least the function call
12951 // operators of T. The function call operators of T are obtained by
12952 // ordinary lookup of the name operator() in the context of
12953 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012954 OverloadCandidateSet CandidateSet(LParenLoc,
12955 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012956 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012957
John Wiegley01296292011-04-08 18:41:53 +000012958 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012959 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012960 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012961
John McCall27b18f82009-11-17 02:14:36 +000012962 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12963 LookupQualifiedName(R, Record->getDecl());
12964 R.suppressDiagnostics();
12965
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012966 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012967 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012968 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012969 Object.get()->Classify(Context), Args, CandidateSet,
12970 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012972
Douglas Gregorab7897a2008-11-19 22:57:39 +000012973 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012974 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012975 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012976 //
12977 // operator conversion-type-id () cv-qualifier;
12978 //
12979 // where cv-qualifier is the same cv-qualification as, or a
12980 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012981 // denotes the type "pointer to function of (P1,...,Pn) returning
12982 // R", or the type "reference to pointer to function of
12983 // (P1,...,Pn) returning R", or the type "reference to function
12984 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012985 // is also considered as a candidate function. Similarly,
12986 // surrogate call functions are added to the set of candidate
12987 // functions for each conversion function declared in an
12988 // accessible base class provided the function is not hidden
12989 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012990 const auto &Conversions =
12991 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12992 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012993 NamedDecl *D = *I;
12994 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12995 if (isa<UsingShadowDecl>(D))
12996 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012997
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012998 // Skip over templated conversion functions; they aren't
12999 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000013000 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013001 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000013002
John McCall6e9f8f62009-12-03 04:06:58 +000013003 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013004 if (!Conv->isExplicit()) {
13005 // Strip the reference type (if any) and then the pointer type (if
13006 // any) to get down to what might be a function type.
13007 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13008 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13009 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013010
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013011 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13012 {
13013 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013014 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013015 }
13016 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013017 }
Mike Stump11289f42009-09-09 15:08:12 +000013018
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013019 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13020
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013021 // Perform overload resolution.
13022 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000013023 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +000013024 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013025 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013026 // Overload resolution succeeded; we'll build the appropriate call
13027 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013028 break;
13029
13030 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013031 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013032 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000013033 << Object.get()->getType() << /*call*/ 1
13034 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013035 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013036 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000013037 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013038 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013039 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013040 break;
13041
13042 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013043 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013044 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013045 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013046 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013047 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013048
13049 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013050 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000013051 diag::err_ovl_deleted_object_call)
13052 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013053 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013054 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000013055 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013056 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013057 break;
Mike Stump11289f42009-09-09 15:08:12 +000013058 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013059
Douglas Gregorb412e172010-07-25 18:17:45 +000013060 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013061 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013062
John McCall4124c492011-10-17 18:40:02 +000013063 UnbridgedCasts.restore();
13064
Craig Topperc3ec1492014-05-26 06:22:03 +000013065 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013066 // Since there is no function declaration, this is one of the
13067 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013068 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013069 = cast<CXXConversionDecl>(
13070 Best->Conversions[0].UserDefined.ConversionFunction);
13071
Craig Topperc3ec1492014-05-26 06:22:03 +000013072 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13073 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013074 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13075 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013076 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013077 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013078 // We selected one of the surrogate functions that converts the
13079 // object parameter to a function pointer. Perform the conversion
13080 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013081
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013082 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013083 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013084 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13085 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013086 if (Call.isInvalid())
13087 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013088 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013089 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13090 CK_UserDefinedConversion, Call.get(),
13091 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013092
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013093 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013094 }
13095
Craig Topperc3ec1492014-05-26 06:22:03 +000013096 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013097
Douglas Gregorab7897a2008-11-19 22:57:39 +000013098 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13099 // that calls this method, using Object for the implicit object
13100 // parameter and passing along the remaining arguments.
13101 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013102
13103 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013104 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013105 return ExprError();
13106
Chandler Carruth8e543b32010-12-12 08:17:55 +000013107 const FunctionProtoType *Proto =
13108 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013109
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013110 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013111
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013112 DeclarationNameInfo OpLocInfo(
13113 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13114 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013115 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013116 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013117 OpLocInfo.getLoc(),
13118 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013119 if (NewFn.isInvalid())
13120 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013121
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013122 // Build the full argument list for the method call (the implicit object
13123 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013124 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013125 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013126 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013127
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013128 // Once we've built TheCall, all of the expressions are properly
13129 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013130 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013131 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13132 ResultTy = ResultTy.getNonLValueExprType(Context);
13133
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013134 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013135 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013136 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013137
Alp Toker314cc812014-01-25 16:55:45 +000013138 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013139 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013140
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013141 // We may have default arguments. If so, we need to allocate more
13142 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013143 if (Args.size() < NumParams)
13144 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013145
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013146 bool IsError = false;
13147
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013148 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013149 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013150 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013151 Best->FoundDecl, Method);
13152 if (ObjRes.isInvalid())
13153 IsError = true;
13154 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013155 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013156 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013157
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013158 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013159 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013160 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013161 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013162 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013163
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013164 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013165
John McCalldadc5752010-08-24 06:29:42 +000013166 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013167 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013168 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013169 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013170 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013171
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013172 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013173 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013174 } else {
John McCalldadc5752010-08-24 06:29:42 +000013175 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013176 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13177 if (DefArg.isInvalid()) {
13178 IsError = true;
13179 break;
13180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013181
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013182 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013183 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013184
13185 TheCall->setArg(i + 1, Arg);
13186 }
13187
13188 // If this is a variadic call, handle args passed through "...".
13189 if (Proto->isVariadic()) {
13190 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013191 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013192 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13193 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013194 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013195 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013196 }
13197 }
13198
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013199 if (IsError) return true;
13200
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013201 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013202
Richard Smith55ce3522012-06-25 20:30:08 +000013203 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013204 return true;
13205
John McCalle172be52010-08-24 06:09:16 +000013206 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013207}
13208
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013209/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013210/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013211/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013212ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013213Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13214 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013215 assert(Base->getType()->isRecordType() &&
13216 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013217
John McCall4124c492011-10-17 18:40:02 +000013218 if (checkPlaceholderForOverload(*this, Base))
13219 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013220
John McCallbc077cf2010-02-08 23:07:23 +000013221 SourceLocation Loc = Base->getExprLoc();
13222
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013223 // C++ [over.ref]p1:
13224 //
13225 // [...] An expression x->m is interpreted as (x.operator->())->m
13226 // for a class object x of type T if T::operator->() exists and if
13227 // the operator is selected as the best match function by the
13228 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013229 DeclarationName OpName =
13230 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013231 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013232 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013233
John McCallbc077cf2010-02-08 23:07:23 +000013234 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013235 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013236 return ExprError();
13237
John McCall27b18f82009-11-17 02:14:36 +000013238 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13239 LookupQualifiedName(R, BaseRecord->getDecl());
13240 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013241
13242 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013243 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013244 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013245 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013246 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013247
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013248 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13249
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013250 // Perform overload resolution.
13251 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013252 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013253 case OR_Success:
13254 // Overload resolution succeeded; we'll build the call below.
13255 break;
13256
13257 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013258 if (CandidateSet.empty()) {
13259 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013260 if (NoArrowOperatorFound) {
13261 // Report this specific error to the caller instead of emitting a
13262 // diagnostic, as requested.
13263 *NoArrowOperatorFound = true;
13264 return ExprError();
13265 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013266 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13267 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013268 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013269 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013270 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013271 }
13272 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013273 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013274 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013276 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013277
13278 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013279 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13280 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013281 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013282 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013283
13284 case OR_Deleted:
13285 Diag(OpLoc, diag::err_ovl_deleted_oper)
13286 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013287 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013288 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013289 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013290 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013291 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013292 }
13293
Craig Topperc3ec1492014-05-26 06:22:03 +000013294 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013295
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013296 // Convert the object parameter.
13297 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013298 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013299 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013300 Best->FoundDecl, Method);
13301 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013302 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013303 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013304
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013305 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013306 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013307 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013308 if (FnExpr.isInvalid())
13309 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013310
Alp Toker314cc812014-01-25 16:55:45 +000013311 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013312 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13313 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013314 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013315 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013316 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013317
Alp Toker314cc812014-01-25 16:55:45 +000013318 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013319 return ExprError();
13320
13321 if (CheckFunctionCall(Method, TheCall,
13322 Method->getType()->castAs<FunctionProtoType>()))
13323 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013324
13325 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013326}
13327
Richard Smithbcc22fc2012-03-09 08:00:36 +000013328/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13329/// a literal operator described by the provided lookup results.
13330ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13331 DeclarationNameInfo &SuffixInfo,
13332 ArrayRef<Expr*> Args,
13333 SourceLocation LitEndLoc,
13334 TemplateArgumentListInfo *TemplateArgs) {
13335 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013336
Richard Smith100b24a2014-04-17 01:52:14 +000013337 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13338 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013339 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13340 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013341
Richard Smithbcc22fc2012-03-09 08:00:36 +000013342 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13343
Richard Smithbcc22fc2012-03-09 08:00:36 +000013344 // Perform overload resolution. This will usually be trivial, but might need
13345 // to perform substitutions for a literal operator template.
13346 OverloadCandidateSet::iterator Best;
13347 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13348 case OR_Success:
13349 case OR_Deleted:
13350 break;
13351
13352 case OR_No_Viable_Function:
13353 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13354 << R.getLookupName();
13355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13356 return ExprError();
13357
13358 case OR_Ambiguous:
13359 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13360 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13361 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013362 }
13363
Richard Smithbcc22fc2012-03-09 08:00:36 +000013364 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013365 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013366 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013367 SuffixInfo.getLoc(),
13368 SuffixInfo.getInfo());
13369 if (Fn.isInvalid())
13370 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013371
13372 // Check the argument types. This should almost always be a no-op, except
13373 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013374 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013375 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013376 ExprResult InputInit = PerformCopyInitialization(
13377 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13378 SourceLocation(), Args[ArgIdx]);
13379 if (InputInit.isInvalid())
13380 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013381 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013382 }
13383
Alp Toker314cc812014-01-25 16:55:45 +000013384 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013385 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13386 ResultTy = ResultTy.getNonLValueExprType(Context);
13387
Richard Smithc67fdd42012-03-07 08:35:16 +000013388 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013389 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013390 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013391 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13392
Alp Toker314cc812014-01-25 16:55:45 +000013393 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013394 return ExprError();
13395
Craig Topperc3ec1492014-05-26 06:22:03 +000013396 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013397 return ExprError();
13398
13399 return MaybeBindToTemporary(UDL);
13400}
13401
Sam Panzer0f384432012-08-21 00:52:01 +000013402/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13403/// given LookupResult is non-empty, it is assumed to describe a member which
13404/// will be invoked. Otherwise, the function will be found via argument
13405/// dependent lookup.
13406/// CallExpr is set to a valid expression and FRS_Success returned on success,
13407/// otherwise CallExpr is set to ExprError() and some non-success value
13408/// is returned.
13409Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013410Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13411 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013412 const DeclarationNameInfo &NameInfo,
13413 LookupResult &MemberLookup,
13414 OverloadCandidateSet *CandidateSet,
13415 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013416 Scope *S = nullptr;
13417
Richard Smith67ef14f2017-09-26 18:37:55 +000013418 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013419 if (!MemberLookup.empty()) {
13420 ExprResult MemberRef =
13421 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13422 /*IsPtr=*/false, CXXScopeSpec(),
13423 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013424 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013425 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013426 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013427 if (MemberRef.isInvalid()) {
13428 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013429 return FRS_DiagnosticIssued;
13430 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013431 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013432 if (CallExpr->isInvalid()) {
13433 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013434 return FRS_DiagnosticIssued;
13435 }
13436 } else {
13437 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013438 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013439 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013440 NestedNameSpecifierLoc(), NameInfo,
13441 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013442 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013443
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013444 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013445 CandidateSet, CallExpr);
13446 if (CandidateSet->empty() || CandidateSetError) {
13447 *CallExpr = ExprError();
13448 return FRS_NoViableFunction;
13449 }
13450 OverloadCandidateSet::iterator Best;
13451 OverloadingResult OverloadResult =
13452 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13453
13454 if (OverloadResult == OR_No_Viable_Function) {
13455 *CallExpr = ExprError();
13456 return FRS_NoViableFunction;
13457 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013458 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013459 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013460 OverloadResult,
13461 /*AllowTypoCorrection=*/false);
13462 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13463 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013464 return FRS_DiagnosticIssued;
13465 }
13466 }
13467 return FRS_Success;
13468}
13469
13470
Douglas Gregorcd695e52008-11-10 20:40:00 +000013471/// FixOverloadedFunctionReference - E is an expression that refers to
13472/// a C++ overloaded function (possibly with some parentheses and
13473/// perhaps a '&' around it). We have resolved the overloaded function
13474/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013475/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013476Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013477 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013478 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013479 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13480 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013481 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013482 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013483
Douglas Gregor51c538b2009-11-20 19:42:02 +000013484 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013485 }
13486
Douglas Gregor51c538b2009-11-20 19:42:02 +000013487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013488 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13489 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013490 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013491 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013492 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013493 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013494 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013495 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013496
13497 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013498 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013499 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013500 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013501 }
13502
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013503 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13504 if (!GSE->isResultDependent()) {
13505 Expr *SubExpr =
13506 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13507 if (SubExpr == GSE->getResultExpr())
13508 return GSE;
13509
13510 // Replace the resulting type information before rebuilding the generic
13511 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013512 ArrayRef<Expr *> A = GSE->getAssocExprs();
13513 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013514 unsigned ResultIdx = GSE->getResultIndex();
13515 AssocExprs[ResultIdx] = SubExpr;
13516
13517 return new (Context) GenericSelectionExpr(
13518 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13519 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13520 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13521 ResultIdx);
13522 }
13523 // Rather than fall through to the unreachable, return the original generic
13524 // selection expression.
13525 return GSE;
13526 }
13527
Douglas Gregor51c538b2009-11-20 19:42:02 +000013528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013529 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013530 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13532 if (Method->isStatic()) {
13533 // Do nothing: static member functions aren't any different
13534 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013535 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013536 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013537 // UnresolvedLookupExpr holding an overloaded member function
13538 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013539 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13540 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013541 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013542 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013543
John McCalld14a8642009-11-21 08:51:07 +000013544 assert(isa<DeclRefExpr>(SubExpr)
13545 && "fixed to something other than a decl ref");
13546 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13547 && "fixed to a member ref with no nested name qualifier");
13548
13549 // We have taken the address of a pointer to member
13550 // function. Perform the computation here so that we get the
13551 // appropriate pointer to member type.
13552 QualType ClassType
13553 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13554 QualType MemPtrType
13555 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013556 // Under the MS ABI, lock down the inheritance model now.
13557 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13558 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013559
John McCall7decc9e2010-11-18 06:31:45 +000013560 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13561 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013562 UnOp->getOperatorLoc(), false);
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013563 }
13564 }
John McCall16df1e52010-03-30 21:47:33 +000013565 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13566 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013567 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013568 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013569
John McCalle3027922010-08-25 11:45:40 +000013570 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013571 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013572 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013573 UnOp->getOperatorLoc(), false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013574 }
John McCalld14a8642009-11-21 08:51:07 +000013575
Richard Smith84a0b6d2016-10-18 23:39:12 +000013576 // C++ [except.spec]p17:
13577 // An exception-specification is considered to be needed when:
13578 // - in an expression the function is the unique lookup result or the
13579 // selected member of a set of overloaded functions
13580 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13581 ResolveExceptionSpec(E->getExprLoc(), FPT);
13582
John McCalld14a8642009-11-21 08:51:07 +000013583 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013584 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013585 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013586 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013587 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13588 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013589 }
13590
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013591 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13592 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013593 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013594 Fn,
John McCall113bee02012-03-10 09:33:50 +000013595 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013596 ULE->getNameLoc(),
13597 Fn->getType(),
13598 VK_LValue,
13599 Found.getDecl(),
13600 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013601 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013602 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13603 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013604 }
13605
John McCall10eae182009-11-30 22:42:35 +000013606 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013607 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013608 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013609 if (MemExpr->hasExplicitTemplateArgs()) {
13610 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13611 TemplateArgs = &TemplateArgsBuffer;
13612 }
John McCall6b51f282009-11-23 01:53:49 +000013613
John McCall2d74de92009-12-01 22:10:20 +000013614 Expr *Base;
13615
John McCall7decc9e2010-11-18 06:31:45 +000013616 // If we're filling in a static method where we used to have an
13617 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013618 if (MemExpr->isImplicitAccess()) {
13619 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013620 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13621 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013622 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013623 Fn,
John McCall113bee02012-03-10 09:33:50 +000013624 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013625 MemExpr->getMemberLoc(),
13626 Fn->getType(),
13627 VK_LValue,
13628 Found.getDecl(),
13629 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013630 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013631 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13632 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013633 } else {
13634 SourceLocation Loc = MemExpr->getMemberLoc();
13635 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013636 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013637 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013638 Base = new (Context) CXXThisExpr(Loc,
13639 MemExpr->getBaseType(),
13640 /*isImplicit=*/true);
13641 }
John McCall2d74de92009-12-01 22:10:20 +000013642 } else
John McCallc3007a22010-10-26 07:05:15 +000013643 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013644
John McCall4adb38c2011-04-27 00:36:17 +000013645 ExprValueKind valueKind;
13646 QualType type;
13647 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13648 valueKind = VK_LValue;
13649 type = Fn->getType();
13650 } else {
13651 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013652 type = Context.BoundMemberTy;
13653 }
13654
13655 MemberExpr *ME = MemberExpr::Create(
13656 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13657 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13658 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13659 OK_Ordinary);
13660 ME->setHadMultipleCandidates(true);
13661 MarkMemberReferenced(ME);
13662 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013664
John McCallc3007a22010-10-26 07:05:15 +000013665 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013666}
13667
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013668ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013669 DeclAccessPair Found,
13670 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013671 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013672}