blob: f36668f76140b1baa4c0577da6563409c2360ed6 [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() ||
Erich Keane2fcbe922018-06-12 13:59:32 +0000226 getFromType()->isMemberPointerType() ||
John McCall6d1116a2010-06-11 10:04:22 +0000227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000229 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234}
235
Douglas Gregor5c407d92008-10-23 00:40:37 +0000236/// isPointerConversionToVoidPointer - Determines whether this
237/// conversion is a conversion of a pointer to a void pointer. This is
238/// used as part of the ranking of standard conversion sequences (C++
239/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000240bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000241StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000242isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000243 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257}
258
Richard Smith66e05fe2012-01-18 05:21:49 +0000259/// Skip any implicit casts which could be either part of a narrowing conversion
260/// or after one in an implicit conversion.
261static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000268 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281}
282
283/// Check if this standard conversion sequence represents a narrowing
284/// conversion, according to C++11 [dcl.init.list]p7.
285///
286/// \param Ctx The AST context.
287/// \param Converted The result of applying this standard conversion sequence.
288/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000290/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291/// type of the expression prior to the narrowing conversion.
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000292/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293/// from floating point types to integral types should be ignored.
294NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
Richard Smith66e05fe2012-01-18 05:21:49 +0000310 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000311 // 'bool' is an integral type; dispatch to the right place to handle it.
312 case ICK_Boolean_Conversion:
313 if (FromType->isRealFloatingType())
314 goto FloatingIntegralConversion;
315 if (FromType->isIntegralOrUnscopedEnumerationType())
316 goto IntegralConversion;
317 // Boolean conversions can be from pointers and pointers to members
318 // [conv.bool], and those aren't considered narrowing conversions.
319 return NK_Not_Narrowing;
320
Richard Smith66e05fe2012-01-18 05:21:49 +0000321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000328 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
Mikhail Maltsev7b1a9502018-02-21 10:08:18 +0000331 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332 ToType->isRealFloatingType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000333 if (IgnoreFloatToIntegralConversion)
334 return NK_Not_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000335 llvm::APSInt IntConstantValue;
336 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000337 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000338
339 // If it's value-dependent, we can't tell whether it's narrowing.
340 if (Initializer->isValueDependent())
341 return NK_Dependent_Narrowing;
342
Simon Pilgrimf9409872017-06-01 18:13:02 +0000343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000344 // Convert the integer to the floating type.
345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347 llvm::APFloat::rmNearestTiesToEven);
348 // And back.
349 llvm::APSInt ConvertedValue = IntConstantValue;
350 bool ignored;
351 Result.convertToInteger(ConvertedValue,
352 llvm::APFloat::rmTowardZero, &ignored);
353 // If the resulting value is different, this was a narrowing conversion.
354 if (IntConstantValue != ConvertedValue) {
355 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000356 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000357 return NK_Constant_Narrowing;
358 }
359 } else {
360 // Variables are always narrowings.
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from long double to double or float, or from double to float, except
367 // where the source is a constant expression and the actual value after
368 // conversion is within the range of values that can be represented (even
369 // if it cannot be represented exactly), or
370 case ICK_Floating_Conversion:
371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373 // FromType is larger than ToType.
374 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
378 return NK_Dependent_Narrowing;
379
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381 // Constant!
382 assert(ConstantValue.isFloat());
383 llvm::APFloat FloatVal = ConstantValue.getFloat();
384 // Convert the source value into the target type.
385 bool ignored;
386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387 Ctx.getFloatTypeSemantics(ToType),
388 llvm::APFloat::rmNearestTiesToEven, &ignored);
389 // If there was no overflow, the source value is within the range of
390 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000391 if (ConvertStatus & llvm::APFloat::opOverflow) {
392 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000393 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000394 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000395 } else {
396 return NK_Variable_Narrowing;
397 }
398 }
399 return NK_Not_Narrowing;
400
401 // -- from an integer type or unscoped enumeration type to an integer type
402 // that cannot represent all the values of the original type, except where
403 // the source is a constant expression and the actual value after
404 // conversion will fit into the target type and will produce the original
405 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000406 case ICK_Integral_Conversion:
407 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000408 assert(FromType->isIntegralOrUnscopedEnumerationType());
409 assert(ToType->isIntegralOrUnscopedEnumerationType());
410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411 const unsigned FromWidth = Ctx.getIntWidth(FromType);
412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413 const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000416 (FromWidth == ToWidth && FromSigned != ToSigned) ||
417 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000418 // Not all values of FromType can be represented in ToType.
419 llvm::APSInt InitializerValue;
420 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000421
422 // If it's value-dependent, we can't tell whether it's narrowing.
423 if (Initializer->isValueDependent())
424 return NK_Dependent_Narrowing;
425
Richard Smith25a80d42012-06-13 01:07:41 +0000426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427 // Such conversions on variables are always narrowing.
428 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000429 }
430 bool Narrowing = false;
431 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000432 // Negative -> unsigned is narrowing. Otherwise, more bits is never
433 // narrowing.
434 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000436 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000437 // Add a bit to the InitializerValue so we don't have to worry about
438 // signed vs. unsigned comparisons.
439 InitializerValue = InitializerValue.extend(
440 InitializerValue.getBitWidth() + 1);
441 // Convert the initializer to and from the target width and signed-ness.
442 llvm::APSInt ConvertedValue = InitializerValue;
443 ConvertedValue = ConvertedValue.trunc(ToWidth);
444 ConvertedValue.setIsSigned(ToSigned);
445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446 ConvertedValue.setIsSigned(InitializerValue.isSigned());
447 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000448 if (ConvertedValue != InitializerValue)
449 Narrowing = true;
450 }
451 if (Narrowing) {
452 ConstantType = Initializer->getType();
453 ConstantValue = APValue(InitializerValue);
454 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000455 }
456 }
457 return NK_Not_Narrowing;
458 }
459
460 default:
461 // Other kinds of conversions are not narrowings.
462 return NK_Not_Narrowing;
463 }
464}
465
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000466/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000468LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 bool PrintedSomething = false;
471 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 PrintedSomething = true;
474 }
475
476 if (Second != ICK_Identity) {
477 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481
482 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000486 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000487 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000488 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 PrintedSomething = true;
490 }
491
492 if (Third != ICK_Identity) {
493 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000494 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 PrintedSomething = true;
498 }
499
500 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 }
503}
504
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000513 if (ConversionFunction)
514 OS << '\'' << *ConversionFunction << '\'';
515 else
516 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 }
521}
522
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000525void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000526 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000527 if (isStdInitializerListElement())
528 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 switch (ConversionKind) {
530 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000536 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537 break;
538 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000539 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 break;
John McCall0d1da222010-01-12 00:44:57 +0000541 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000542 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000543 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 break;
547 }
548
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000549 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550}
551
John McCall0d1da222010-01-12 00:44:57 +0000552void AmbiguousConversionSequence::construct() {
553 new (&conversions()) ConversionSet();
554}
555
556void AmbiguousConversionSequence::destruct() {
557 conversions().~ConversionSet();
558}
559
560void
561AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562 FromTypePtr = O.FromTypePtr;
563 ToTypePtr = O.ToTypePtr;
564 new (&conversions()) ConversionSet(O.conversions());
565}
566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000568 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000569 // template argument information.
570 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 TemplateArgument FirstArg;
572 TemplateArgument SecondArg;
573 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000574 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000575 // template parameter and template argument information.
576 struct DFIParamWithArguments : DFIArguments {
577 TemplateParameter Param;
578 };
Richard Smith9b534542015-12-31 02:02:54 +0000579 // Structure used by DeductionFailureInfo to store template argument
580 // information and the index of the problematic call argument.
581 struct DFIDeducedMismatchArgs : DFIArguments {
582 TemplateArgumentList *TemplateArgs;
583 unsigned CallArgIndex;
584 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000585}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000587/// Convert from Sema's representation of template deduction information
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000589DeductionFailureInfo
590clang::MakeDeductionFailureInfo(ASTContext &Context,
591 Sema::TemplateDeductionResult TDK,
592 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000593 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000595 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000597 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000598 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000601 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000602 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000603 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 Result.Data = Info.Param.getOpaqueValue();
609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Richard Smithc92d2062017-01-05 23:02:44 +0000611 case Sema::TDK_DeducedMismatch:
612 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000613 // FIXME: Should allocate from normal heap so that we can free this later.
614 auto *Saved = new (Context) DFIDeducedMismatchArgs;
615 Saved->FirstArg = Info.FirstArg;
616 Saved->SecondArg = Info.SecondArg;
617 Saved->TemplateArgs = Info.take();
618 Saved->CallArgIndex = Info.CallArgIndex;
619 Result.Data = Saved;
620 break;
621 }
622
Richard Smith44ecdbd2013-01-31 05:19:49 +0000623 case Sema::TDK_NonDeducedMismatch: {
624 // FIXME: Should allocate from normal heap so that we can free this later.
625 DFIArguments *Saved = new (Context) DFIArguments;
626 Saved->FirstArg = Info.FirstArg;
627 Saved->SecondArg = Info.SecondArg;
628 Result.Data = Saved;
629 break;
630 }
631
Richard Smith4a8f3512018-07-19 19:00:37 +0000632 case Sema::TDK_IncompletePack:
633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000634 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000635 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000636 // FIXME: Should allocate from normal heap so that we can free this later.
637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 Saved->Param = Info.Param;
639 Saved->FirstArg = Info.FirstArg;
640 Saved->SecondArg = Info.SecondArg;
641 Result.Data = Saved;
642 break;
643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000647 if (Info.hasSFINAEDiagnostic()) {
648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649 SourceLocation(), PartialDiagnostic::NullDiagnostic());
650 Info.takeSFINAEDiagnostic(*Diag);
651 Result.HasDiagnostic = true;
652 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000653 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000654
655 case Sema::TDK_Success:
656 case Sema::TDK_NonDependentConversionFailure:
657 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 return Result;
661}
John McCall0d1da222010-01-12 00:44:57 +0000662
Larisse Voufo98b20f12013-07-19 23:00:19 +0000663void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000666 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000669 case Sema::TDK_TooManyArguments:
670 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000671 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000672 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000673 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Richard Smith4a8f3512018-07-19 19:00:37 +0000676 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000679 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000680 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000681 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000682 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000683 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000685
686 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000687 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000688 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690 Diag->~PartialDiagnosticAt();
691 HasDiagnostic = false;
692 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000693 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Douglas Gregor461761d2010-05-08 18:20:53 +0000695 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000696 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 break;
698 }
699}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
Larisse Voufo98b20f12013-07-19 23:00:19 +0000701PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000702 if (HasDiagnostic)
703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000704 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000705}
706
Larisse Voufo98b20f12013-07-19 23:00:19 +0000707TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000710 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000714 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000715 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000716 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000718 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000719 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000723 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725
Richard Smith4a8f3512018-07-19 19:00:37 +0000726 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000728 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000732 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 break;
734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return TemplateParameter();
737}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
Larisse Voufo98b20f12013-07-19 23:00:19 +0000739TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000741 case Sema::TDK_Success:
742 case Sema::TDK_Invalid:
743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_TooManyArguments:
745 case Sema::TDK_TooFewArguments:
746 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +0000747 case Sema::TDK_IncompletePack:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000748 case Sema::TDK_InvalidExplicitArguments:
749 case Sema::TDK_Inconsistent:
750 case Sema::TDK_Underqualified:
751 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000752 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000753 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000754 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000755
Richard Smith9b534542015-12-31 02:02:54 +0000756 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000757 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
Richard Smith44ecdbd2013-01-31 05:19:49 +0000760 case Sema::TDK_SubstitutionFailure:
761 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Richard Smith44ecdbd2013-01-31 05:19:49 +0000763 // Unhandled
764 case Sema::TDK_MiscellaneousDeductionFailure:
765 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000766 }
767
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000769}
770
Larisse Voufo98b20f12013-07-19 23:00:19 +0000771const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000774 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000779 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000780 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000781 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000782 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784
Richard Smith4a8f3512018-07-19 19:00:37 +0000785 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000786 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000787 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000788 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000789 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000790 case Sema::TDK_NonDeducedMismatch:
791 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792
Douglas Gregor461761d2010-05-08 18:20:53 +0000793 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000794 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 break;
796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000800
Larisse Voufo98b20f12013-07-19 23:00:19 +0000801const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000804 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_InstantiationDepth:
806 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +0000807 case Sema::TDK_IncompletePack:
Douglas Gregor461761d2010-05-08 18:20:53 +0000808 case Sema::TDK_TooManyArguments:
809 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000810 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000811 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000812 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000813 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000814 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000815
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000816 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000817 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000818 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000819 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000820 case Sema::TDK_NonDeducedMismatch:
821 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000822
Douglas Gregor461761d2010-05-08 18:20:53 +0000823 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000824 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000825 break;
826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Craig Topperc3ec1492014-05-26 06:22:03 +0000828 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000829}
830
Richard Smith9b534542015-12-31 02:02:54 +0000831llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
Richard Smithc92d2062017-01-05 23:02:44 +0000837 default:
838 return llvm::None;
839 }
Richard Smith9b534542015-12-31 02:02:54 +0000840}
841
Benjamin Kramer97e59492012-10-09 15:52:25 +0000842void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000843 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000844 for (auto &C : i->Conversions)
845 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847 i->DeductionFailure.Destroy();
848 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000849}
850
Richard Smith67ef14f2017-09-26 18:37:55 +0000851void OverloadCandidateSet::clear(CandidateSetKind CSK) {
Benjamin Kramer97e59492012-10-09 15:52:25 +0000852 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000853 SlabAllocator.Reset();
854 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000855 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000856 Functions.clear();
Richard Smith67ef14f2017-09-26 18:37:55 +0000857 Kind = CSK;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000858}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
John McCall4124c492011-10-17 18:40:02 +0000860namespace {
861 class UnbridgedCastsSet {
862 struct Entry {
863 Expr **Addr;
864 Expr *Saved;
865 };
866 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000867
John McCall4124c492011-10-17 18:40:02 +0000868 public:
869 void save(Sema &S, Expr *&E) {
870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871 Entry entry = { &E, E };
872 Entries.push_back(entry);
873 E = S.stripARCUnbridgedCast(E);
874 }
875
876 void restore() {
877 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000878 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000879 *i->Addr = i->Saved;
880 }
881 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000882}
John McCall4124c492011-10-17 18:40:02 +0000883
884/// checkPlaceholderForOverload - Do any interesting placeholder-like
885/// preprocessing on the given expression.
886///
887/// \param unbridgedCasts a collection to which to add unbridged casts;
888/// without this, they will be immediately diagnosed as errors
889///
890/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000891static bool
892checkPlaceholderForOverload(Sema &S, Expr *&E,
893 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
895 // We can't handle overloaded expressions here because overload
896 // resolution might reasonably tweak them.
897 if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899 // If the context potentially accepts unbridged ARC casts, strip
900 // the unbridged cast and add it to the collection for later restoration.
901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902 unbridgedCasts) {
903 unbridgedCasts->save(S, E);
904 return false;
905 }
906
907 // Go ahead and check everything else.
908 ExprResult result = S.CheckPlaceholderExpr(E);
909 if (result.isInvalid())
910 return true;
911
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000913 return false;
914 }
915
916 // Nothing to do.
917 return false;
918}
919
920/// checkArgPlaceholdersForOverload - Check a set of call operands for
921/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000922static bool checkArgPlaceholdersForOverload(Sema &S,
923 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000924 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000925 for (unsigned i = 0, e = Args.size(); i != e; ++i)
926 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000927 return true;
928
929 return false;
930}
931
George Burgess IV2d82b092017-04-06 00:23:31 +0000932/// Determine whether the given New declaration is an overload of the
933/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934/// New and Old cannot be overloaded, e.g., if New has the same signature as
935/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936/// functions (or function templates) at all. When it does return Ovl_Match or
937/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939/// declaration.
940///
941/// Example: Given the following input:
942///
943/// void f(int, float); // #1
944/// void f(int, int); // #2
945/// int f(int, int); // #3
946///
947/// When we process #1, there is no previous declaration of "f", so IsOverload
948/// will not be used.
949///
950/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951/// the parameter types, we see that #1 and #2 are overloaded (since they have
952/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953/// unchanged.
954///
955/// When we process #3, Old is an overload set containing #1 and #2. We compare
956/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958/// functions are not part of the signature), IsOverload returns Ovl_Match and
959/// MatchedDecl will be set to point to the FunctionDecl for #2.
960///
961/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962/// by a using declaration. The rules for whether to hide shadow declarations
963/// ignore some properties which otherwise figure into a function template's
964/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000965Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000966Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000968 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000969 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000970 NamedDecl *OldD = *I;
971
972 bool OldIsUsingDecl = false;
973 if (isa<UsingShadowDecl>(OldD)) {
974 OldIsUsingDecl = true;
975
976 // We can always introduce two using declarations into the same
977 // context, even if they have identical signatures.
978 if (NewIsUsingDecl) continue;
979
980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981 }
982
Richard Smithf091e122015-09-15 01:28:55 +0000983 // A using-declaration does not conflict with another declaration
984 // if one of them is hidden.
985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986 continue;
987
John McCalle9cccd82010-06-16 08:42:20 +0000988 // If either declaration was introduced by a using declaration,
989 // we'll need to use slightly different rules for matching.
990 // Essentially, these rules are the normal rules, except that
991 // function templates hide function templates with different
992 // return types or template parameter lists.
993 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000996
Alp Tokera2794f92014-01-22 07:29:52 +0000997 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 continue;
1002 }
1003
Alp Tokera2794f92014-01-22 07:29:52 +00001004 if (!isa<FunctionTemplateDecl>(OldD) &&
1005 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00001006 continue;
1007
John McCalldaa3d6b2009-12-09 03:35:25 +00001008 Match = *I;
1009 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +00001010 }
Erich Keane41af9712018-04-16 21:30:08 +00001011
1012 // Builtins that have custom typechecking or have a reference should
1013 // not be overloadable or redeclarable.
1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
Richard Smith151c4562016-12-20 21:35:28 +00001018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001019 // We can overload with these, which can show up when doing
1020 // redeclaration checks for UsingDecls.
1021 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001022 } else if (isa<TagDecl>(OldD)) {
1023 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001025 // Optimistically assume that an unresolved using decl will
1026 // overload; if it doesn't, we'll have to diagnose during
1027 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001028 //
1029 // Exception: if the scope is dependent and this is not a class
1030 // member, the using declaration can only introduce an enumerator.
1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
John McCall84d87672009-12-10 09:41:52 +00001035 } else {
John McCall1f82f242009-11-18 22:49:29 +00001036 // (C++ 13p1):
1037 // Only function declarations can be overloaded; object and type
1038 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001039 Match = *I;
1040 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001041 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001042 }
John McCall1f82f242009-11-18 22:49:29 +00001043
John McCalldaa3d6b2009-12-09 03:35:25 +00001044 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001045}
1046
Richard Smithac974a32013-06-30 09:48:50 +00001047bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001049 // C++ [basic.start.main]p2: This function shall not be overloaded.
1050 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001051 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001052
David Majnemerc729b0b2013-09-16 22:44:20 +00001053 // MSVCRT user defined entry points cannot be overloaded.
1054 if (New->isMSVCRTEntryPoint())
1055 return false;
1056
John McCall1f82f242009-11-18 22:49:29 +00001057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059
1060 // C++ [temp.fct]p2:
1061 // A function template can be overloaded with other function templates
1062 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001064 return true;
1065
1066 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001067 QualType OldQType = Context.getCanonicalType(Old->getType());
1068 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001069
1070 // Compare the signatures (C++ 1.3.10) of the two functions to
1071 // determine whether they are overloads. If we find any mismatch
1072 // in the signature, they are overloads.
1073
1074 // If either of these functions is a K&R-style function (no
1075 // prototype), then we consider them to have matching signatures.
1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078 return false;
1079
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001082
1083 // The signature of a function includes the types of its
1084 // parameters (C++ 1.3.10), which includes the presence or absence
1085 // of the ellipsis; see C++ DR 357).
1086 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001087 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001088 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001089 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001090 return true;
1091
1092 // C++ [temp.over.link]p4:
1093 // The signature of a function template consists of its function
1094 // signature, its return type and its template parameter list. The names
1095 // of the template parameters are significant only for establishing the
1096 // relationship between the template parameters and the rest of the
1097 // signature.
1098 //
1099 // We check the return type and template parameter lists for function
1100 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001101 //
1102 // However, we don't consider either of these when deciding whether
1103 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001104 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106 OldTemplate->getTemplateParameters(),
1107 false, TPL_TemplateMatch) ||
Richard Smith4576a772018-09-10 06:35:32 +00001108 !Context.hasSameType(Old->getDeclaredReturnType(),
1109 New->getDeclaredReturnType())))
John McCall1f82f242009-11-18 22:49:29 +00001110 return true;
1111
1112 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001113 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001114 //
1115 // As part of this, also check whether one of the member functions
1116 // is static, in which case they are not overloads (C++
1117 // 13.1p2). While not part of the definition of the signature,
1118 // this check is important to determine whether these functions
1119 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001120 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1121 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001122 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001123 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1124 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001125 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001126 (OldMethod->getRefQualifier() == RQ_None ||
1127 NewMethod->getRefQualifier() == RQ_None)) {
1128 // C++0x [over.load]p2:
1129 // - Member function declarations with the same name and the same
1130 // parameter-type-list as well as member function template
1131 // declarations with the same name, the same parameter-type-list, and
1132 // the same template parameter lists cannot be overloaded if any of
1133 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001134 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001135 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001136 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001137 }
1138 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Richard Smith574f4f62013-01-14 05:37:29 +00001141 // We may not have applied the implicit const for a constexpr member
1142 // function yet (because we haven't yet resolved whether this is a static
1143 // or non-static member function). Add it now, on the assumption that this
1144 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001145 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001146 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001147 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001148 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001149 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001150
1151 // We do not allow overloading based off of '__restrict'.
1152 OldQuals &= ~Qualifiers::Restrict;
1153 NewQuals &= ~Qualifiers::Restrict;
1154 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001155 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001158 // Though pass_object_size is placed on parameters and takes an argument, we
1159 // consider it to be a function-level modifier for the sake of function
1160 // identity. Either the function has one or more parameters with
1161 // pass_object_size or it doesn't.
1162 if (functionHasPassObjectSizeParams(New) !=
1163 functionHasPassObjectSizeParams(Old))
1164 return true;
1165
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001166 // enable_if attributes are an order-sensitive part of the signature.
1167 for (specific_attr_iterator<EnableIfAttr>
1168 NewI = New->specific_attr_begin<EnableIfAttr>(),
1169 NewE = New->specific_attr_end<EnableIfAttr>(),
1170 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1171 OldE = Old->specific_attr_end<EnableIfAttr>();
1172 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1173 if (NewI == NewE || OldI == OldE)
1174 return true;
1175 llvm::FoldingSetNodeID NewID, OldID;
1176 NewI->getCond()->Profile(NewID, Context, true);
1177 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001178 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001179 return true;
1180 }
1181
Justin Lebarba122ab2016-03-30 23:30:21 +00001182 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001183 // Don't allow overloading of destructors. (In theory we could, but it
1184 // would be a giant change to clang.)
1185 if (isa<CXXDestructorDecl>(New))
1186 return false;
1187
Artem Belevich94a55e82015-09-22 17:22:59 +00001188 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1189 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001190 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001191 return false;
1192
1193 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1194
Justin Lebar53b000af2016-10-03 16:48:27 +00001195 // Allow overloading of functions with same signature and different CUDA
1196 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001197 return NewTarget != OldTarget;
1198 }
1199
John McCall1f82f242009-11-18 22:49:29 +00001200 // The signatures match; this is not an overload.
1201 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202}
1203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001204/// Checks availability of the function depending on the current
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001205/// function context. Inside an unavailable function, unavailability is ignored.
1206///
1207/// \returns true if \arg FD is unavailable and current context is inside
1208/// an available function, false otherwise.
1209bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001210 if (!FD->isUnavailable())
1211 return false;
1212
1213 // Walk up the context of the caller.
1214 Decl *C = cast<Decl>(CurContext);
1215 do {
1216 if (C->isUnavailable())
1217 return false;
1218 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1219 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001220}
1221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001222/// Tries a user-defined conversion from From to ToType.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001223///
1224/// Produces an implicit conversion sequence for when a standard conversion
1225/// is not an option. See TryImplicitConversion for more information.
1226static ImplicitConversionSequence
1227TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1228 bool SuppressUserConversions,
1229 bool AllowExplicit,
1230 bool InOverloadResolution,
1231 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001232 bool AllowObjCWritebackConversion,
1233 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001234 ImplicitConversionSequence ICS;
1235
1236 if (SuppressUserConversions) {
1237 // We're not in the case above, so there is no conversion that
1238 // we can perform.
1239 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1240 return ICS;
1241 }
1242
1243 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001244 OverloadCandidateSet Conversions(From->getExprLoc(),
1245 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001246 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1247 Conversions, AllowExplicit,
1248 AllowObjCConversionOnExplicit)) {
1249 case OR_Success:
1250 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001251 ICS.setUserDefined();
1252 // C++ [over.ics.user]p4:
1253 // A conversion of an expression of class type to the same class
1254 // type is given Exact Match rank, and a conversion of an
1255 // expression of class type to a base class of that type is
1256 // given Conversion rank, in spite of the fact that a copy
1257 // constructor (i.e., a user-defined conversion function) is
1258 // called for those cases.
1259 if (CXXConstructorDecl *Constructor
1260 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1261 QualType FromCanon
1262 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1263 QualType ToCanon
1264 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1265 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001266 (FromCanon == ToCanon ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001267 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001268 // Turn this into a "standard" conversion sequence, so that it
1269 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001270 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001271 ICS.setStandard();
1272 ICS.Standard.setAsIdentityConversion();
1273 ICS.Standard.setFromType(From->getType());
1274 ICS.Standard.setAllToTypes(ToType);
1275 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001276 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 if (ToCanon != FromCanon)
1278 ICS.Standard.Second = ICK_Derived_To_Base;
1279 }
1280 }
Richard Smith48372b62015-01-27 03:30:40 +00001281 break;
1282
1283 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001284 ICS.setAmbiguous();
1285 ICS.Ambiguous.setFromType(From->getType());
1286 ICS.Ambiguous.setToType(ToType);
1287 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1288 Cand != Conversions.end(); ++Cand)
1289 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001290 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001291 break;
Richard Smith48372b62015-01-27 03:30:40 +00001292
1293 // Fall through.
1294 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001295 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001296 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001297 }
1298
1299 return ICS;
1300}
1301
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001302/// TryImplicitConversion - Attempt to perform an implicit conversion
1303/// from the given expression (Expr) to the given type (ToType). This
1304/// function returns an implicit conversion sequence that can be used
1305/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306///
1307/// void f(float f);
1308/// void g(int i) { f(i); }
1309///
1310/// this routine would produce an implicit conversion sequence to
1311/// describe the initialization of f from i, which will be a standard
1312/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1313/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1314//
1315/// Note that this routine only determines how the conversion can be
1316/// performed; it does not actually perform the conversion. As such,
1317/// it will not produce any diagnostics if no conversion is available,
1318/// but will instead return an implicit conversion sequence of kind
1319/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001320///
1321/// If @p SuppressUserConversions, then user-defined conversions are
1322/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001323/// If @p AllowExplicit, then explicit user-defined conversions are
1324/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001325///
1326/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1327/// writeback conversion, which allows __autoreleasing id* parameters to
1328/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001329static ImplicitConversionSequence
1330TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1331 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001333 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001334 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001335 bool AllowObjCWritebackConversion,
1336 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001337 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001338 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001339 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001340 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001341 return ICS;
1342 }
1343
David Blaikiebbafb8a2012-03-11 07:00:24 +00001344 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001345 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001346 return ICS;
1347 }
1348
Douglas Gregor836a7e82010-08-11 02:15:33 +00001349 // C++ [over.ics.user]p4:
1350 // A conversion of an expression of class type to the same class
1351 // type is given Exact Match rank, and a conversion of an
1352 // expression of class type to a base class of that type is
1353 // given Conversion rank, in spite of the fact that a copy/move
1354 // constructor (i.e., a user-defined conversion function) is
1355 // called for those cases.
1356 QualType FromType = From->getType();
1357 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001358 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001359 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001360 ICS.setStandard();
1361 ICS.Standard.setAsIdentityConversion();
1362 ICS.Standard.setFromType(FromType);
1363 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Douglas Gregor5ab11652010-04-17 22:01:05 +00001365 // We don't actually check at this point whether there is a valid
1366 // copy/move constructor, since overloading just assumes that it
1367 // exists. When we actually perform initialization, we'll find the
1368 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001369 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
Douglas Gregor5ab11652010-04-17 22:01:05 +00001371 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001372 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001373 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor836a7e82010-08-11 02:15:33 +00001375 return ICS;
1376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001378 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1379 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001380 AllowObjCWritebackConversion,
1381 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001382}
1383
John McCall31168b02011-06-15 23:02:42 +00001384ImplicitConversionSequence
1385Sema::TryImplicitConversion(Expr *From, QualType ToType,
1386 bool SuppressUserConversions,
1387 bool AllowExplicit,
1388 bool InOverloadResolution,
1389 bool CStyle,
1390 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001391 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001392 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001393 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001394 AllowObjCWritebackConversion,
1395 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001396}
1397
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001398/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001399/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001400/// converted expression. Flavor is the kind of conversion we're
1401/// performing, used in the error message. If @p AllowExplicit,
1402/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001403ExprResult
1404Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001405 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001406 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001407 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001408}
1409
John Wiegley01296292011-04-08 18:41:53 +00001410ExprResult
1411Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001412 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001413 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001414 if (checkPlaceholderForOverload(*this, From))
1415 return ExprError();
1416
John McCall31168b02011-06-15 23:02:42 +00001417 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1418 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001419 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001420 (Action == AA_Passing || Action == AA_Sending);
Erik Pilkingtonfa983902018-10-30 20:31:30 +00001421 if (getLangOpts().ObjC)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001422 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1423 From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001424 ICS = ::TryImplicitConversion(*this, From, ToType,
1425 /*SuppressUserConversions=*/false,
1426 AllowExplicit,
1427 /*InOverloadResolution=*/false,
1428 /*CStyle=*/false,
1429 AllowObjCWritebackConversion,
1430 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001431 return PerformImplicitConversion(From, ToType, ICS, Action);
1432}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001434/// Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001435/// conversion that strips "noexcept" or "noreturn" off the nested function
1436/// type.
1437bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001438 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001439 if (Context.hasSameUnqualifiedType(FromType, ToType))
1440 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441
John McCall991eb4b2010-12-21 00:44:39 +00001442 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001443 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001444 // where F adds one of the following at most once:
1445 // - a pointer
1446 // - a member pointer
1447 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001448 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001449 CanQualType CanTo = Context.getCanonicalType(ToType);
1450 CanQualType CanFrom = Context.getCanonicalType(FromType);
1451 Type::TypeClass TyClass = CanTo->getTypeClass();
1452 if (TyClass != CanFrom->getTypeClass()) return false;
1453 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1454 if (TyClass == Type::Pointer) {
1455 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1456 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1457 } else if (TyClass == Type::BlockPointer) {
1458 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1459 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1460 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001461 auto ToMPT = CanTo.getAs<MemberPointerType>();
1462 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1463 // A function pointer conversion cannot change the class of the function.
1464 if (ToMPT->getClass() != FromMPT->getClass())
1465 return false;
1466 CanTo = ToMPT->getPointeeType();
1467 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001468 } else {
1469 return false;
1470 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001471
John McCall991eb4b2010-12-21 00:44:39 +00001472 TyClass = CanTo->getTypeClass();
1473 if (TyClass != CanFrom->getTypeClass()) return false;
1474 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1475 return false;
1476 }
1477
Richard Smith3c4f8d22016-10-16 17:54:23 +00001478 const auto *FromFn = cast<FunctionType>(CanFrom);
1479 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001480
Richard Smith6f427402016-10-20 00:01:36 +00001481 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001482 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1483
1484 bool Changed = false;
1485
1486 // Drop 'noreturn' if not present in target type.
1487 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1488 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1489 Changed = true;
1490 }
1491
1492 // Drop 'noexcept' if not present in target type.
1493 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001494 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001495 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00001496 FromFn = cast<FunctionType>(
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00001497 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1498 EST_None)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001499 .getTypePtr());
1500 Changed = true;
1501 }
Artem Belevich55ebd6c2018-04-03 18:29:31 +00001502
Akira Hatanaka98a49332017-09-22 00:41:05 +00001503 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1504 // only if the ExtParameterInfo lists of the two function prototypes can be
1505 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1506 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1507 bool CanUseToFPT, CanUseFromFPT;
1508 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1509 CanUseFromFPT, NewParamInfos) &&
1510 CanUseToFPT && !CanUseFromFPT) {
1511 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1512 ExtInfo.ExtParameterInfos =
1513 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1514 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1515 FromFPT->getParamTypes(), ExtInfo);
1516 FromFn = QT->getAs<FunctionType>();
1517 Changed = true;
1518 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001519 }
1520
1521 if (!Changed)
1522 return false;
1523
John McCall991eb4b2010-12-21 00:44:39 +00001524 assert(QualType(FromFn, 0).isCanonical());
1525 if (QualType(FromFn, 0) != CanTo) return false;
1526
1527 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001528 return true;
1529}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001531/// Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor46188682010-05-18 22:42:18 +00001532/// vector conversion.
1533///
1534/// \param ICK Will be set to the vector conversion kind, if this is a vector
1535/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001536static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001538 // We need at least one of these types to be a vector type to have a vector
1539 // conversion.
1540 if (!ToType->isVectorType() && !FromType->isVectorType())
1541 return false;
1542
1543 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001544 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001545 return false;
1546
1547 // There are no conversions between extended vector types, only identity.
1548 if (ToType->isExtVectorType()) {
1549 // There are no conversions between extended vector types other than the
1550 // identity conversion.
1551 if (FromType->isExtVectorType())
1552 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregor46188682010-05-18 22:42:18 +00001554 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001555 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001556 ICK = ICK_Vector_Splat;
1557 return true;
1558 }
1559 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001560
1561 // We can perform the conversion between vector types in the following cases:
1562 // 1)vector types are equivalent AltiVec and GCC vector types
1563 // 2)lax vector conversions are permitted and the vector types are of the
1564 // same size
1565 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001566 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1567 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001568 ICK = ICK_Vector_Conversion;
1569 return true;
1570 }
Douglas Gregor46188682010-05-18 22:42:18 +00001571 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001572
Douglas Gregor46188682010-05-18 22:42:18 +00001573 return false;
1574}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001576static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1577 bool InOverloadResolution,
1578 StandardConversionSequence &SCS,
1579 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001580
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001581/// IsStandardConversion - Determines whether there is a standard
1582/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1583/// expression From to the type ToType. Standard conversion sequences
1584/// only consider non-class types; for conversions that involve class
1585/// types, use TryImplicitConversion. If a conversion exists, SCS will
1586/// contain the standard conversion sequence required to perform this
1587/// conversion and this routine will return true. Otherwise, this
1588/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001589static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1590 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001591 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001592 bool CStyle,
1593 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001597 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001598 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001599 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001600 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001601
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001602 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001603 // abort early. When overloading in C, however, we do permit them.
1604 if (S.getLangOpts().CPlusPlus &&
1605 (FromType->isRecordType() || ToType->isRecordType()))
1606 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001607
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608 // The first conversion can be an lvalue-to-rvalue conversion,
1609 // array-to-pointer conversion, or function-to-pointer conversion
1610 // (C++ 4p1).
1611
John McCall5c32be02010-08-24 20:38:10 +00001612 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001613 DeclAccessPair AccessPair;
1614 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001616 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001617 // We were able to resolve the address of the overloaded function,
1618 // so we can convert to the type of that function.
1619 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001620 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001621
1622 // we can sometimes resolve &foo<int> regardless of ToType, so check
1623 // if the type matches (identity) or we are converting to bool
1624 if (!S.Context.hasSameUnqualifiedType(
1625 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1626 QualType resultTy;
1627 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001628 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001629 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001630 // otherwise, only a boolean conversion is standard
1631 if (!ToType->isBooleanType())
1632 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634
Chandler Carruthffce2452011-03-29 08:08:18 +00001635 // Check if the "from" expression is taking the address of an overloaded
1636 // function and recompute the FromType accordingly. Take advantage of the
1637 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001638 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001639 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1640 if (Method && !Method->isStatic()) {
1641 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1642 "Non-unary operator on non-static member address");
1643 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1644 == UO_AddrOf &&
1645 "Non-address-of operator on non-static member address");
1646 const Type *ClassType
1647 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1648 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001649 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1650 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1651 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001652 "Non-address-of operator for overloaded function expression");
1653 FromType = S.Context.getPointerType(FromType);
1654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Douglas Gregor980fb162010-04-29 18:24:40 +00001656 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001657 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1658 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001659 assert(S.Context.hasSameType(
1660 FromType,
1661 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001662 } else {
1663 return false;
1664 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001665 }
John McCall154a2fd2011-08-30 00:57:29 +00001666 // Lvalue-to-rvalue conversion (C++11 4.1):
1667 // A glvalue (3.10) of a non-function, non-array type T can
1668 // be converted to a prvalue.
1669 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001670 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001671 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001672 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674
Douglas Gregorc79862f2012-04-12 17:51:55 +00001675 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001676 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001677 // of the type of the lvalue ...
1678 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1679 FromType = Atomic->getValueType();
1680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681 // If T is a non-class type, the type of the rvalue is the
1682 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1684 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001686 } else if (FromType->isArrayType()) {
1687 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001688 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689
1690 // An lvalue or rvalue of type "array of N T" or "array of unknown
1691 // bound of T" can be converted to an rvalue of type "pointer to
1692 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001693 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694
John McCall5c32be02010-08-24 20:38:10 +00001695 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001696 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001697 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698
1699 // For the purpose of ranking in overload resolution
1700 // (13.3.3.1.1), this conversion is considered an
1701 // array-to-pointer conversion followed by a qualification
1702 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001703 SCS.Second = ICK_Identity;
1704 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001705 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001706 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
John McCall086a4642010-11-24 05:12:34 +00001709 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001710 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001713 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1714 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1715 if (!S.checkAddressOfFunctionIsAvailable(FD))
1716 return false;
1717
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 // An lvalue of function type T can be converted to an rvalue of
1719 // type "pointer to T." The result is a pointer to the
1720 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001721 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001722 } else {
1723 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001724 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001726 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727
1728 // The second conversion can be an integral promotion, floating
1729 // point promotion, integral conversion, floating point conversion,
1730 // floating-integral conversion, pointer conversion,
1731 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001732 // For overloading in C, this can also be a "compatible-type"
1733 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001734 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001735 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001736 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001737 // The unqualified versions of the types are the same: there's no
1738 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001739 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001740 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001741 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001742 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001744 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001745 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001746 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001748 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001749 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750 SCS.Second = ICK_Complex_Promotion;
1751 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001752 } else if (ToType->isBooleanType() &&
1753 (FromType->isArithmeticType() ||
1754 FromType->isAnyPointerType() ||
1755 FromType->isBlockPointerType() ||
1756 FromType->isMemberPointerType() ||
1757 FromType->isNullPtrType())) {
1758 // Boolean conversions (C++ 4.12).
1759 SCS.Second = ICK_Boolean_Conversion;
1760 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001761 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001762 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001763 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001764 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001766 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001767 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001768 SCS.Second = ICK_Complex_Conversion;
1769 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001770 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1771 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001772 // Complex-real conversions (C99 6.3.1.7)
1773 SCS.Second = ICK_Complex_Real;
1774 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001775 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001776 // FIXME: disable conversions between long double and __float128 if
1777 // their representation is different until there is back end support
1778 // We of course allow this conversion if long double is really double.
1779 if (&S.Context.getFloatTypeSemantics(FromType) !=
1780 &S.Context.getFloatTypeSemantics(ToType)) {
1781 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1782 ToType == S.Context.LongDoubleTy) ||
1783 (FromType == S.Context.LongDoubleTy &&
1784 ToType == S.Context.Float128Ty));
1785 if (Float128AndLongDouble &&
Benjamin Kramer98057952018-01-17 22:56:57 +00001786 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1787 &llvm::APFloat::PPCDoubleDouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001788 return false;
1789 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001790 // Floating point conversions (C++ 4.8).
1791 SCS.Second = ICK_Floating_Conversion;
1792 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001794 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001795 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001796 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001797 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001798 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001799 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001800 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001801 SCS.Second = ICK_Block_Pointer_Conversion;
1802 } else if (AllowObjCWritebackConversion &&
1803 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1804 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001805 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1806 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001807 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001808 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001809 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001810 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001812 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001813 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001814 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001815 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001816 SCS.Second = SecondICK;
1817 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001818 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001819 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001820 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001821 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001822 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001823 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1824 InOverloadResolution,
1825 SCS, CStyle)) {
1826 SCS.Second = ICK_TransparentUnionConversion;
1827 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001828 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1829 CStyle)) {
1830 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001831 // appropriately.
1832 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001833 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001834 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001835 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001836 SCS.Second = ICK_Zero_Event_Conversion;
1837 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001838 } else if (ToType->isQueueT() &&
1839 From->isIntegerConstantExpr(S.getASTContext()) &&
1840 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1841 SCS.Second = ICK_Zero_Queue_Conversion;
1842 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001843 } else {
1844 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001845 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001847 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001849 // The third conversion can be a function pointer conversion or a
1850 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001851 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001852 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1853 // Function pointer conversions (removing 'noexcept') including removal of
1854 // 'noreturn' (Clang extension).
1855 SCS.Third = ICK_Function_Conversion;
1856 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1857 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001858 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001859 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001860 FromType = ToType;
1861 } else {
1862 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001863 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001864 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001865
1866 // C++ [over.best.ics]p6:
1867 // [...] Any difference in top-level cv-qualification is
1868 // subsumed by the initialization itself and does not constitute
1869 // a conversion. [...]
1870 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1871 QualType CanonTo = S.Context.getCanonicalType(ToType);
1872 if (CanonFrom.getLocalUnqualifiedType()
1873 == CanonTo.getLocalUnqualifiedType() &&
1874 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1875 FromType = ToType;
1876 CanonFrom = CanonTo;
1877 }
1878
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001879 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001880
George Burgess IV45461812015-10-11 20:13:20 +00001881 if (CanonFrom == CanonTo)
1882 return true;
1883
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001885 // this is a bad conversion sequence, unless we're resolving an overload in C.
1886 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001887 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888
George Burgess IV45461812015-10-11 20:13:20 +00001889 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001890 Sema::AssignConvertType Conv =
1891 S.CheckSingleAssignmentConstraints(ToType, ER,
1892 /*Diagnose=*/false,
1893 /*DiagnoseCFAudited=*/false,
1894 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001895 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001896 switch (Conv) {
1897 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001898 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001899 break;
1900 // For our purposes, discarding qualifiers is just as bad as using an
1901 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1902 // qualifiers, as well.
1903 case Sema::CompatiblePointerDiscardsQualifiers:
1904 case Sema::IncompatiblePointer:
1905 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001906 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001907 break;
1908 default:
George Burgess IV45461812015-10-11 20:13:20 +00001909 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001910 }
George Burgess IV45461812015-10-11 20:13:20 +00001911
George Burgess IV6098fd12016-09-03 00:28:25 +00001912 // First can only be an lvalue conversion, so we pretend that this was the
1913 // second conversion. First should already be valid from earlier in the
1914 // function.
1915 SCS.Second = SecondConv;
1916 SCS.setToType(1, ToType);
1917
1918 // Third is Identity, because Second should rank us worse than any other
1919 // conversion. This could also be ICK_Qualification, but it's simpler to just
1920 // lump everything in with the second conversion, and we don't gain anything
1921 // from making this ICK_Qualification.
1922 SCS.Third = ICK_Identity;
1923 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001924 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925}
George Burgess IV2099b542016-09-02 22:59:57 +00001926
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001927static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001928IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001929 QualType &ToType,
1930 bool InOverloadResolution,
1931 StandardConversionSequence &SCS,
1932 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001933
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001934 const RecordType *UT = ToType->getAsUnionType();
1935 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1936 return false;
1937 // The field to initialize within the transparent union.
1938 RecordDecl *UD = UT->getDecl();
1939 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001940 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001941 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1942 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001943 ToType = it->getType();
1944 return true;
1945 }
1946 }
1947 return false;
1948}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001949
1950/// IsIntegralPromotion - Determines whether the conversion from the
1951/// expression From (whose potentially-adjusted type is FromType) to
1952/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1953/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001954bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001955 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001956 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001957 if (!To) {
1958 return false;
1959 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001960
1961 // An rvalue of type char, signed char, unsigned char, short int, or
1962 // unsigned short int can be converted to an rvalue of type int if
1963 // int can represent all the values of the source type; otherwise,
1964 // the source rvalue can be converted to an rvalue of type unsigned
1965 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001966 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1967 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 if (// We can promote any signed, promotable integer type to an int
1969 (FromType->isSignedIntegerType() ||
1970 // We can promote any unsigned integer type whose size is
1971 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001972 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001973 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001974 }
1975
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976 return To->getKind() == BuiltinType::UInt;
1977 }
1978
Richard Smithb9c5a602012-09-13 21:18:54 +00001979 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 // A prvalue of an unscoped enumeration type whose underlying type is not
1981 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1982 // following types that can represent all the values of the enumeration
1983 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1984 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001987 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988 // with lowest integer conversion rank (4.13) greater than the rank of long
1989 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001990 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001991 // C++11 [conv.prom]p4:
1992 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1993 // can be converted to a prvalue of its underlying type. Moreover, if
1994 // integral promotion can be applied to its underlying type, a prvalue of an
1995 // unscoped enumeration type whose underlying type is fixed can also be
1996 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001997 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1998 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1999 // provided for a scoped enumeration.
2000 if (FromEnumType->getDecl()->isScoped())
2001 return false;
2002
Richard Smithb9c5a602012-09-13 21:18:54 +00002003 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00002004 // even if that's not the promoted type. Note that the check for promoting
2005 // the underlying type is based on the type alone, and does not consider
2006 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00002007 if (FromEnumType->getDecl()->isFixed()) {
2008 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2009 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00002010 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00002011 }
2012
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002013 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 if (ToType->isIntegerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002015 isCompleteType(From->getBeginLoc(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00002016 return Context.hasSameUnqualifiedType(
2017 ToType, FromEnumType->getDecl()->getPromotionType());
Richard Smithaadb2542018-06-28 21:17:55 +00002018
2019 // C++ [conv.prom]p5:
2020 // If the bit-field has an enumerated type, it is treated as any other
2021 // value of that type for promotion purposes.
2022 //
2023 // ... so do not fall through into the bit-field checks below in C++.
2024 if (getLangOpts().CPlusPlus)
2025 return false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00002026 }
John McCall56774992009-12-09 09:09:27 +00002027
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002028 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2030 // to an rvalue a prvalue of the first of the following types that can
2031 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002032 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002034 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002036 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002038 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002039 // Determine whether the type we're converting from is signed or
2040 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002041 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002042 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002044 // The types we'll try to promote to, in the appropriate
2045 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002046 QualType PromoteTypes[6] = {
2047 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002048 Context.LongTy, Context.UnsignedLongTy ,
2049 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002051 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2053 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002054 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2056 // We found the type that we can promote to. If this is the
2057 // type we wanted, we have a promotion. Otherwise, no
2058 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002059 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002060 }
2061 }
2062 }
2063
2064 // An rvalue for an integral bit-field (9.6) can be converted to an
2065 // rvalue of type int if int can represent all the values of the
2066 // bit-field; otherwise, it can be converted to unsigned int if
2067 // unsigned int can represent all the values of the bit-field. If
2068 // the bit-field is larger yet, no integral promotion applies to
2069 // it. If the bit-field has an enumerated type, it is treated as any
2070 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002071 // FIXME: We should delay checking of bit-fields until we actually perform the
2072 // conversion.
Richard Smithaadb2542018-06-28 21:17:55 +00002073 //
2074 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2075 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2076 // bit-fields and those whose underlying type is larger than int) for GCC
2077 // compatibility.
Richard Smith88f4bba2015-03-26 00:16:07 +00002078 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002079 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002080 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002081 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002082 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002083 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002084 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002086 // Are we promoting to an int from a bitfield that fits in an int?
2087 if (BitWidth < ToSize ||
2088 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2089 return To->getKind() == BuiltinType::Int;
2090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002092 // Are we promoting to an unsigned int from an unsigned bitfield
2093 // that fits into an unsigned int?
2094 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2095 return To->getKind() == BuiltinType::UInt;
2096 }
Mike Stump11289f42009-09-09 15:08:12 +00002097
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002098 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002099 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002103 // An rvalue of type bool can be converted to an rvalue of type int,
2104 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002105 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002106 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002107 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108
2109 return false;
2110}
2111
2112/// IsFloatingPointPromotion - Determines whether the conversion from
2113/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2114/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002115bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002116 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2117 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002118 /// An rvalue of type float can be converted to an rvalue of type
2119 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002120 if (FromBuiltin->getKind() == BuiltinType::Float &&
2121 ToBuiltin->getKind() == BuiltinType::Double)
2122 return true;
2123
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002124 // C99 6.3.1.5p1:
2125 // When a float is promoted to double or long double, or a
2126 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002128 (FromBuiltin->getKind() == BuiltinType::Float ||
2129 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002130 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2131 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002132 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002133
2134 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002135 if (!getLangOpts().NativeHalfType &&
2136 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002137 ToBuiltin->getKind() == BuiltinType::Float)
2138 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002139 }
2140
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002141 return false;
2142}
2143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002144/// Determine if a conversion is a complex promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002145///
2146/// A complex promotion is defined as a complex -> complex conversion
2147/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002148/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002149bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002150 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002151 if (!FromComplex)
2152 return false;
2153
John McCall9dd450b2009-09-21 23:43:11 +00002154 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002155 if (!ToComplex)
2156 return false;
2157
2158 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002159 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002160 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002161 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002162}
2163
Douglas Gregor237f96c2008-11-26 23:31:11 +00002164/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2165/// the pointer type FromPtr to a pointer to type ToPointee, with the
2166/// same type qualifiers as FromPtr has on its pointee type. ToType,
2167/// if non-empty, will be a pointer to ToType that may or may not have
2168/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002169///
Mike Stump11289f42009-09-09 15:08:12 +00002170static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002171BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002172 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002173 ASTContext &Context,
2174 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002175 assert((FromPtr->getTypeClass() == Type::Pointer ||
2176 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2177 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002178
John McCall31168b02011-06-15 23:02:42 +00002179 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002180 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002181 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
2183 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002184 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002185 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002186 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002187
John McCall31168b02011-06-15 23:02:42 +00002188 if (StripObjCLifetime)
2189 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002190
Mike Stump11289f42009-09-09 15:08:12 +00002191 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002192 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002193 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002194 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002195 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002196
2197 // Build a pointer to ToPointee. It has the right qualifiers
2198 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002199 if (isa<ObjCObjectPointerType>(ToType))
2200 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002201 return Context.getPointerType(ToPointee);
2202 }
2203
2204 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002205 QualType QualifiedCanonToPointee
2206 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002208 if (isa<ObjCObjectPointerType>(ToType))
2209 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2210 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002211}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212
Mike Stump11289f42009-09-09 15:08:12 +00002213static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002214 bool InOverloadResolution,
2215 ASTContext &Context) {
2216 // Handle value-dependent integral null pointer constants correctly.
2217 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2218 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002219 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 return !InOverloadResolution;
2221
Douglas Gregor56751b52009-09-25 04:25:58 +00002222 return Expr->isNullPointerConstant(Context,
2223 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2224 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002225}
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002227/// IsPointerConversion - Determines whether the conversion of the
2228/// expression From, which has the (possibly adjusted) type FromType,
2229/// can be converted to the type ToType via a pointer conversion (C++
2230/// 4.10). If so, returns true and places the converted type (that
2231/// might differ from ToType in its cv-qualifiers at some level) into
2232/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002233///
Douglas Gregora29dc052008-11-27 01:19:21 +00002234/// This routine also supports conversions to and from block pointers
2235/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2236/// pointers to interfaces. FIXME: Once we've determined the
2237/// appropriate overloading rules for Objective-C, we may want to
2238/// split the Objective-C checks into a different routine; however,
2239/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002240/// conversions, so for now they live here. IncompatibleObjC will be
2241/// set if the conversion is an allowed Objective-C conversion that
2242/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002243bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002244 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002245 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002246 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002247 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002248 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2249 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002250 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002251
Mike Stump11289f42009-09-09 15:08:12 +00002252 // Conversion from a null pointer constant to any Objective-C pointer type.
2253 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002255 ConvertedType = ToType;
2256 return true;
2257 }
2258
Douglas Gregor231d1c62008-11-27 00:15:41 +00002259 // Blocks: Block pointers can be converted to void*.
2260 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002262 ConvertedType = ToType;
2263 return true;
2264 }
2265 // Blocks: A null pointer constant can be converted to a block
2266 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002267 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002269 ConvertedType = ToType;
2270 return true;
2271 }
2272
Sebastian Redl576fd422009-05-10 18:38:11 +00002273 // If the left-hand-side is nullptr_t, the right side can be a null
2274 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002275 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002277 ConvertedType = ToType;
2278 return true;
2279 }
2280
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002281 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 if (!ToTypePtr)
2283 return false;
2284
2285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002287 ConvertedType = ToType;
2288 return true;
2289 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002290
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002292 // , including objective-c pointers.
2293 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002295 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002296 ConvertedType = BuildSimilarlyQualifiedPointerType(
2297 FromType->getAs<ObjCObjectPointerType>(),
2298 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002299 ToType, Context);
2300 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002301 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002302 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002303 if (!FromTypePtr)
2304 return false;
2305
2306 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002307
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002309 // pointer conversion, so don't do all of the work below.
2310 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2311 return false;
2312
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002313 // An rvalue of type "pointer to cv T," where T is an object type,
2314 // can be converted to an rvalue of type "pointer to cv void" (C++
2315 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002316 if (FromPointeeType->isIncompleteOrObjectType() &&
2317 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002318 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002319 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002320 ToType, Context,
2321 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002322 return true;
2323 }
2324
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002325 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002326 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002327 ToPointeeType->isVoidType()) {
2328 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329 ToPointeeType,
2330 ToType, Context);
2331 return true;
2332 }
2333
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002334 // When we're overloading in C, we allow a special kind of pointer
2335 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002336 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002337 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002339 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002340 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002341 return true;
2342 }
2343
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002345 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002346 // An rvalue of type "pointer to cv D," where D is a class type,
2347 // can be converted to an rvalue of type "pointer to cv B," where
2348 // B is a base class (clause 10) of D. If B is an inaccessible
2349 // (clause 11) or ambiguous (10.2) base class of D, a program that
2350 // necessitates this conversion is ill-formed. The result of the
2351 // conversion is a pointer to the base class sub-object of the
2352 // derived class object. The null pointer value is converted to
2353 // the null pointer value of the destination type.
2354 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002355 // Note that we do not check for ambiguity or inaccessibility
2356 // here. That is handled by CheckPointerConversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002357 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2358 ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002359 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002360 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002361 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002362 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002363 ToType, Context);
2364 return true;
2365 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002366
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002367 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2368 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2370 ToPointeeType,
2371 ToType, Context);
2372 return true;
2373 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002374
Douglas Gregora119f102008-12-19 19:13:09 +00002375 return false;
2376}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002378/// Adopt the given qualifiers for the given type.
Douglas Gregoraec25842011-04-26 23:16:46 +00002379static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2380 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002381
Douglas Gregoraec25842011-04-26 23:16:46 +00002382 // Check whether qualifiers already match.
2383 if (TQs == Qs)
2384 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002385
Douglas Gregoraec25842011-04-26 23:16:46 +00002386 if (Qs.compatiblyIncludes(TQs))
2387 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002388
Douglas Gregoraec25842011-04-26 23:16:46 +00002389 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2390}
Douglas Gregora119f102008-12-19 19:13:09 +00002391
2392/// isObjCPointerConversion - Determines whether this is an
2393/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2394/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002395bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002396 QualType& ConvertedType,
2397 bool &IncompatibleObjC) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002398 if (!getLangOpts().ObjC)
Douglas Gregora119f102008-12-19 19:13:09 +00002399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400
Douglas Gregoraec25842011-04-26 23:16:46 +00002401 // The set of qualifiers on the type we're converting from.
2402 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002403
Steve Naroff7cae42b2009-07-10 23:34:53 +00002404 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002405 const ObjCObjectPointerType* ToObjCPtr =
2406 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002407 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002408 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002409
Steve Naroff7cae42b2009-07-10 23:34:53 +00002410 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002411 // If the pointee types are the same (ignoring qualifications),
2412 // then this is not a pointer conversion.
2413 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2414 FromObjCPtr->getPointeeType()))
2415 return false;
2416
Douglas Gregorab209d82015-07-07 03:58:42 +00002417 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002418 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002419 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2420 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002422 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2423 FromObjCPtr->getPointeeType()))
2424 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002426 ToObjCPtr->getPointeeType(),
2427 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002429 return true;
2430 }
2431
2432 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2433 // Okay: this is some kind of implicit downcast of Objective-C
2434 // interfaces, which is permitted. However, we're going to
2435 // complain about it.
2436 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002438 ToObjCPtr->getPointeeType(),
2439 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002441 return true;
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002444 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002445 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002446 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002447 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002449 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002450 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002451 // to a block pointer type.
2452 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002453 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002454 return true;
2455 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002456 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002459 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002461 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002462 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002463 return true;
2464 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002465 else
Douglas Gregora119f102008-12-19 19:13:09 +00002466 return false;
2467
Douglas Gregor033f56d2008-12-23 00:53:59 +00002468 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002469 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002470 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002471 else if (const BlockPointerType *FromBlockPtr =
2472 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002473 FromPointeeType = FromBlockPtr->getPointeeType();
2474 else
Douglas Gregora119f102008-12-19 19:13:09 +00002475 return false;
2476
Douglas Gregora119f102008-12-19 19:13:09 +00002477 // If we have pointers to pointers, recursively check whether this
2478 // is an Objective-C conversion.
2479 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2480 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2481 IncompatibleObjC)) {
2482 // We always complain about this conversion.
2483 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002484 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002485 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002486 return true;
2487 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002488 // Allow conversion of pointee being objective-c pointer to another one;
2489 // as in I* to id.
2490 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2491 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2492 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2493 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002494
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002495 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002497 return true;
2498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499
Douglas Gregor033f56d2008-12-23 00:53:59 +00002500 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002501 // differences in the argument and result types are in Objective-C
2502 // pointer conversions. If so, we permit the conversion (but
2503 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002504 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002505 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002506 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002507 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002508 if (FromFunctionType && ToFunctionType) {
2509 // If the function types are exactly the same, this isn't an
2510 // Objective-C pointer conversion.
2511 if (Context.getCanonicalType(FromPointeeType)
2512 == Context.getCanonicalType(ToPointeeType))
2513 return false;
2514
2515 // Perform the quick checks that will tell us whether these
2516 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002517 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002518 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2519 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2520 return false;
2521
2522 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002523 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2524 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002525 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002526 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2527 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002528 ConvertedType, IncompatibleObjC)) {
2529 // Okay, we have an Objective-C pointer conversion.
2530 HasObjCConversion = true;
2531 } else {
2532 // Function types are too different. Abort.
2533 return false;
2534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
Douglas Gregora119f102008-12-19 19:13:09 +00002536 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002537 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002538 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002539 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2540 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002541 if (Context.getCanonicalType(FromArgType)
2542 == Context.getCanonicalType(ToArgType)) {
2543 // Okay, the types match exactly. Nothing to do.
2544 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2545 ConvertedType, IncompatibleObjC)) {
2546 // Okay, we have an Objective-C pointer conversion.
2547 HasObjCConversion = true;
2548 } else {
2549 // Argument types are too different. Abort.
2550 return false;
2551 }
2552 }
2553
2554 if (HasObjCConversion) {
2555 // We had an Objective-C conversion. Allow this pointer
2556 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002558 IncompatibleObjC = true;
2559 return true;
2560 }
2561 }
2562
Sebastian Redl72b597d2009-01-25 19:43:20 +00002563 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002564}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002566/// Determine whether this is an Objective-C writeback conversion,
John McCall31168b02011-06-15 23:02:42 +00002567/// used for parameter passing when performing automatic reference counting.
2568///
2569/// \param FromType The type we're converting form.
2570///
2571/// \param ToType The type we're converting to.
2572///
2573/// \param ConvertedType The type that will be produced after applying
2574/// this conversion.
2575bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2576 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002577 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002578 Context.hasSameUnqualifiedType(FromType, ToType))
2579 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002580
John McCall31168b02011-06-15 23:02:42 +00002581 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2582 QualType ToPointee;
2583 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2584 ToPointee = ToPointer->getPointeeType();
2585 else
2586 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002587
John McCall31168b02011-06-15 23:02:42 +00002588 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002589 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002590 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002591 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002592 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002593
John McCall31168b02011-06-15 23:02:42 +00002594 // Argument must be a pointer to __strong to __weak.
2595 QualType FromPointee;
2596 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2597 FromPointee = FromPointer->getPointeeType();
2598 else
2599 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002600
John McCall31168b02011-06-15 23:02:42 +00002601 Qualifiers FromQuals = FromPointee.getQualifiers();
2602 if (!FromPointee->isObjCLifetimeType() ||
2603 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2604 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2605 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002606
John McCall31168b02011-06-15 23:02:42 +00002607 // Make sure that we have compatible qualifiers.
2608 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2609 if (!ToQuals.compatiblyIncludes(FromQuals))
2610 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002611
John McCall31168b02011-06-15 23:02:42 +00002612 // Remove qualifiers from the pointee type we're converting from; they
2613 // aren't used in the compatibility check belong, and we'll be adding back
2614 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2615 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002616
John McCall31168b02011-06-15 23:02:42 +00002617 // The unqualified form of the pointee types must be compatible.
2618 ToPointee = ToPointee.getUnqualifiedType();
2619 bool IncompatibleObjC;
2620 if (Context.typesAreCompatible(FromPointee, ToPointee))
2621 FromPointee = ToPointee;
2622 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2623 IncompatibleObjC))
2624 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002625
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002626 /// Construct the type we're converting to, which is a pointer to
John McCall31168b02011-06-15 23:02:42 +00002627 /// __autoreleasing pointee.
2628 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2629 ConvertedType = Context.getPointerType(FromPointee);
2630 return true;
2631}
2632
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002633bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2634 QualType& ConvertedType) {
2635 QualType ToPointeeType;
2636 if (const BlockPointerType *ToBlockPtr =
2637 ToType->getAs<BlockPointerType>())
2638 ToPointeeType = ToBlockPtr->getPointeeType();
2639 else
2640 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002641
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002642 QualType FromPointeeType;
2643 if (const BlockPointerType *FromBlockPtr =
2644 FromType->getAs<BlockPointerType>())
2645 FromPointeeType = FromBlockPtr->getPointeeType();
2646 else
2647 return false;
2648 // We have pointer to blocks, check whether the only
2649 // differences in the argument and result types are in Objective-C
2650 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002651
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002652 const FunctionProtoType *FromFunctionType
2653 = FromPointeeType->getAs<FunctionProtoType>();
2654 const FunctionProtoType *ToFunctionType
2655 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002656
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002657 if (!FromFunctionType || !ToFunctionType)
2658 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002659
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002660 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002661 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002662
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002663 // Perform the quick checks that will tell us whether these
2664 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002665 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002666 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2667 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002668
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002669 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2670 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2671 if (FromEInfo != ToEInfo)
2672 return false;
2673
2674 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002675 if (Context.hasSameType(FromFunctionType->getReturnType(),
2676 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002677 // Okay, the types match exactly. Nothing to do.
2678 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002679 QualType RHS = FromFunctionType->getReturnType();
2680 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002681 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002682 !RHS.hasQualifiers() && LHS.hasQualifiers())
2683 LHS = LHS.getUnqualifiedType();
2684
2685 if (Context.hasSameType(RHS,LHS)) {
2686 // OK exact match.
2687 } else if (isObjCPointerConversion(RHS, LHS,
2688 ConvertedType, IncompatibleObjC)) {
2689 if (IncompatibleObjC)
2690 return false;
2691 // Okay, we have an Objective-C pointer conversion.
2692 }
2693 else
2694 return false;
2695 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002696
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002697 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002698 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002699 ArgIdx != NumArgs; ++ArgIdx) {
2700 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002701 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2702 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002703 if (Context.hasSameType(FromArgType, ToArgType)) {
2704 // Okay, the types match exactly. Nothing to do.
2705 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2706 ConvertedType, IncompatibleObjC)) {
2707 if (IncompatibleObjC)
2708 return false;
2709 // Okay, we have an Objective-C pointer conversion.
2710 } else
2711 // Argument types are too different. Abort.
2712 return false;
2713 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002714
2715 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2716 bool CanUseToFPT, CanUseFromFPT;
2717 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2718 CanUseToFPT, CanUseFromFPT,
2719 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002720 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002721
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002722 ConvertedType = ToType;
2723 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002724}
2725
Richard Trieucaff2472011-11-23 22:32:32 +00002726enum {
2727 ft_default,
2728 ft_different_class,
2729 ft_parameter_arity,
2730 ft_parameter_mismatch,
2731 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002732 ft_qualifer_mismatch,
2733 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002734};
2735
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002736/// Attempts to get the FunctionProtoType from a Type. Handles
2737/// MemberFunctionPointers properly.
2738static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2739 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2740 return FPT;
2741
2742 if (auto *MPT = FromType->getAs<MemberPointerType>())
2743 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2744
2745 return nullptr;
2746}
2747
Richard Trieucaff2472011-11-23 22:32:32 +00002748/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2749/// function types. Catches different number of parameter, mismatch in
2750/// parameter types, and different return types.
2751void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2752 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002753 // If either type is not valid, include no extra info.
2754 if (FromType.isNull() || ToType.isNull()) {
2755 PDiag << ft_default;
2756 return;
2757 }
2758
Richard Trieucaff2472011-11-23 22:32:32 +00002759 // Get the function type from the pointers.
2760 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2761 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2762 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002763 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002764 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2765 << QualType(FromMember->getClass(), 0);
2766 return;
2767 }
2768 FromType = FromMember->getPointeeType();
2769 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002770 }
2771
Richard Trieu96ed5b62011-12-13 23:19:45 +00002772 if (FromType->isPointerType())
2773 FromType = FromType->getPointeeType();
2774 if (ToType->isPointerType())
2775 ToType = ToType->getPointeeType();
2776
2777 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002778 FromType = FromType.getNonReferenceType();
2779 ToType = ToType.getNonReferenceType();
2780
Richard Trieucaff2472011-11-23 22:32:32 +00002781 // Don't print extra info for non-specialized template functions.
2782 if (FromType->isInstantiationDependentType() &&
2783 !FromType->getAs<TemplateSpecializationType>()) {
2784 PDiag << ft_default;
2785 return;
2786 }
2787
Richard Trieu96ed5b62011-12-13 23:19:45 +00002788 // No extra info for same types.
2789 if (Context.hasSameType(FromType, ToType)) {
2790 PDiag << ft_default;
2791 return;
2792 }
2793
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002794 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2795 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002796
2797 // Both types need to be function types.
2798 if (!FromFunction || !ToFunction) {
2799 PDiag << ft_default;
2800 return;
2801 }
2802
Alp Toker9cacbab2014-01-20 20:26:09 +00002803 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2804 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2805 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002806 return;
2807 }
2808
2809 // Handle different parameter types.
2810 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002811 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002812 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002813 << ToFunction->getParamType(ArgPos)
2814 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002815 return;
2816 }
2817
2818 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002819 if (!Context.hasSameType(FromFunction->getReturnType(),
2820 ToFunction->getReturnType())) {
2821 PDiag << ft_return_type << ToFunction->getReturnType()
2822 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002823 return;
2824 }
2825
2826 unsigned FromQuals = FromFunction->getTypeQuals(),
2827 ToQuals = ToFunction->getTypeQuals();
2828 if (FromQuals != ToQuals) {
2829 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2830 return;
2831 }
2832
Richard Smith3c4f8d22016-10-16 17:54:23 +00002833 // Handle exception specification differences on canonical type (in C++17
2834 // onwards).
2835 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002836 ->isNothrow() !=
Richard Smith3c4f8d22016-10-16 17:54:23 +00002837 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002838 ->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00002839 PDiag << ft_noexcept;
2840 return;
2841 }
2842
Richard Trieucaff2472011-11-23 22:32:32 +00002843 // Unable to find a difference, so add no extra info.
2844 PDiag << ft_default;
2845}
2846
Alp Toker9cacbab2014-01-20 20:26:09 +00002847/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002848/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002849/// they have same number of arguments. If the parameters are different,
2850/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002851bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2852 const FunctionProtoType *NewType,
2853 unsigned *ArgPos) {
2854 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2855 N = NewType->param_type_begin(),
2856 E = OldType->param_type_end();
2857 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002858 if (!Context.hasSameType(O->getUnqualifiedType(),
2859 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002860 if (ArgPos)
2861 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002862 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002863 }
2864 }
2865 return true;
2866}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002867
Douglas Gregor39c16d42008-10-24 04:54:22 +00002868/// CheckPointerConversion - Check the pointer conversion from the
2869/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002870/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002871/// conversions for which IsPointerConversion has already returned
2872/// true. It returns true and produces a diagnostic if there was an
2873/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002874bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002875 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002876 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002877 bool IgnoreBaseAccess,
2878 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002879 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002880 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002881
John McCall8cb679e2010-11-15 09:13:47 +00002882 Kind = CK_BitCast;
2883
George Burgess IV60bc9722016-01-13 23:36:34 +00002884 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002885 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002886 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002887 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2888 DiagRuntimeBehavior(From->getExprLoc(), From,
2889 PDiag(diag::warn_impcast_bool_to_null_pointer)
2890 << ToType << From->getSourceRange());
2891 else if (!isUnevaluatedContext())
2892 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2893 << ToType << From->getSourceRange();
2894 }
John McCall9320b872011-09-09 05:25:32 +00002895 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2896 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002897 QualType FromPointeeType = FromPtrType->getPointeeType(),
2898 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002899
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002900 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2901 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002902 // We must have a derived-to-base conversion. Check an
2903 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002904 unsigned InaccessibleID = 0;
2905 unsigned AmbigiousID = 0;
2906 if (Diagnose) {
2907 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2908 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2909 }
2910 if (CheckDerivedToBaseConversion(
2911 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2912 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2913 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002914 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002916 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002917 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002918 }
David Majnemer6bf02822015-10-31 08:42:14 +00002919
George Burgess IV60bc9722016-01-13 23:36:34 +00002920 if (Diagnose && !IsCStyleOrFunctionalCast &&
2921 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002922 assert(getLangOpts().MSVCCompat &&
2923 "this should only be possible with MSVCCompat!");
2924 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2925 << From->getSourceRange();
2926 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002927 }
John McCall9320b872011-09-09 05:25:32 +00002928 } else if (const ObjCObjectPointerType *ToPtrType =
2929 ToType->getAs<ObjCObjectPointerType>()) {
2930 if (const ObjCObjectPointerType *FromPtrType =
2931 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002932 // Objective-C++ conversions are always okay.
2933 // FIXME: We should have a different class of conversions for the
2934 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002935 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002936 return false;
John McCall9320b872011-09-09 05:25:32 +00002937 } else if (FromType->isBlockPointerType()) {
2938 Kind = CK_BlockPointerToObjCPointerCast;
2939 } else {
2940 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002941 }
John McCall9320b872011-09-09 05:25:32 +00002942 } else if (ToType->isBlockPointerType()) {
2943 if (!FromType->isBlockPointerType())
2944 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002945 }
John McCall8cb679e2010-11-15 09:13:47 +00002946
2947 // We shouldn't fall into this case unless it's valid for other
2948 // reasons.
2949 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2950 Kind = CK_NullToPointer;
2951
Douglas Gregor39c16d42008-10-24 04:54:22 +00002952 return false;
2953}
2954
Sebastian Redl72b597d2009-01-25 19:43:20 +00002955/// IsMemberPointerConversion - Determines whether the conversion of the
2956/// expression From, which has the (possibly adjusted) type FromType, can be
2957/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2958/// If so, returns true and places the converted type (that might differ from
2959/// ToType in its cv-qualifiers at some level) into ConvertedType.
2960bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002962 bool InOverloadResolution,
2963 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002964 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965 if (!ToTypePtr)
2966 return false;
2967
2968 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002969 if (From->isNullPointerConstant(Context,
2970 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002972 ConvertedType = ToType;
2973 return true;
2974 }
2975
2976 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002977 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002978 if (!FromTypePtr)
2979 return false;
2980
2981 // A pointer to member of B can be converted to a pointer to member of D,
2982 // where D is derived from B (C++ 4.11p2).
2983 QualType FromClass(FromTypePtr->getClass(), 0);
2984 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002985
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002986 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002987 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002988 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2989 ToClass.getTypePtr());
2990 return true;
2991 }
2992
2993 return false;
2994}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002995
Sebastian Redl72b597d2009-01-25 19:43:20 +00002996/// CheckMemberPointerConversion - Check the member pointer conversion from the
2997/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002998/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002999/// for which IsMemberPointerConversion has already returned true. It returns
3000/// true and produces a diagnostic if there was an error, or returns false
3001/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003002bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00003003 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00003004 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00003005 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00003006 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003007 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00003008 if (!FromPtrType) {
3009 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00003011 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00003012 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00003013 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00003014 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00003015 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00003016
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003017 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00003018 assert(ToPtrType && "No member pointer cast has a target type "
3019 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003020
Sebastian Redled8f2002009-01-28 18:33:18 +00003021 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3022 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00003023
Sebastian Redled8f2002009-01-28 18:33:18 +00003024 // FIXME: What about dependent types?
3025 assert(FromClass->isRecordType() && "Pointer into non-class.");
3026 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003027
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003029 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00003030 bool DerivationOkay =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003031 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003032 assert(DerivationOkay &&
3033 "Should not have been called if derivation isn't OK.");
3034 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003035
Sebastian Redled8f2002009-01-28 18:33:18 +00003036 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3037 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003038 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3039 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3040 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3041 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003042 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003043
Douglas Gregor89ee6822009-02-28 01:32:25 +00003044 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003045 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3046 << FromClass << ToClass << QualType(VBase, 0)
3047 << From->getSourceRange();
3048 return true;
3049 }
3050
John McCall5b0829a2010-02-10 09:31:12 +00003051 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003052 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3053 Paths.front(),
3054 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003055
Anders Carlssond7923c62009-08-22 23:33:40 +00003056 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003057 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003058 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003059 return false;
3060}
3061
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003062/// Determine whether the lifetime conversion between the two given
3063/// qualifiers sets is nontrivial.
3064static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3065 Qualifiers ToQuals) {
3066 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003067 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003068 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3069 return false;
3070
3071 return true;
3072}
3073
Douglas Gregor9a657932008-10-21 23:43:52 +00003074/// IsQualificationConversion - Determines whether the conversion from
3075/// an rvalue of type FromType to ToType is a qualification conversion
3076/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003077///
3078/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3079/// when the qualification conversion involves a change in the Objective-C
3080/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003081bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003083 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003084 FromType = Context.getCanonicalType(FromType);
3085 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003086 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003087
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 // If FromType and ToType are the same type, this is not a
3089 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003090 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003091 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003092
Douglas Gregor9a657932008-10-21 23:43:52 +00003093 // (C++ 4.4p4):
3094 // A conversion can add cv-qualifiers at levels other than the first
3095 // in multi-level pointers, subject to the following rules: [...]
3096 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003097 bool UnwrappedAnyPointer = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00003098 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003099 // Within each iteration of the loop, we check the qualifiers to
3100 // determine if this still looks like a qualification
3101 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003102 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003103 // until there are no more pointers or pointers-to-members left to
3104 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003105 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003106
Douglas Gregor90609aa2011-04-25 18:40:17 +00003107 Qualifiers FromQuals = FromType.getQualifiers();
3108 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003109
3110 // Ignore __unaligned qualifier if this type is void.
3111 if (ToType.getUnqualifiedType()->isVoidType())
3112 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003113
John McCall31168b02011-06-15 23:02:42 +00003114 // Objective-C ARC:
3115 // Check Objective-C lifetime conversions.
3116 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3117 UnwrappedAnyPointer) {
3118 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003119 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3120 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003121 FromQuals.removeObjCLifetime();
3122 ToQuals.removeObjCLifetime();
3123 } else {
3124 // Qualification conversions cannot cast between different
3125 // Objective-C lifetime qualifiers.
3126 return false;
3127 }
3128 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003129
Douglas Gregorf30053d2011-05-08 06:09:53 +00003130 // Allow addition/removal of GC attributes but not changing GC attributes.
3131 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3132 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3133 FromQuals.removeObjCGCAttr();
3134 ToQuals.removeObjCGCAttr();
3135 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003136
Douglas Gregor9a657932008-10-21 23:43:52 +00003137 // -- for every j > 0, if const is in cv 1,j then const is in cv
3138 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003139 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003140 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregor9a657932008-10-21 23:43:52 +00003142 // -- if the cv 1,j and cv 2,j are different, then const is in
3143 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003144 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003145 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003146 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregor9a657932008-10-21 23:43:52 +00003148 // Keep track of whether all prior cv-qualifiers in the "to" type
3149 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003150 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003151 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003152 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003153
Yaxun Liu99a9f752018-07-20 11:32:51 +00003154 // Allows address space promotion by language rules implemented in
3155 // Type::Qualifiers::isAddressSpaceSupersetOf.
3156 Qualifiers FromQuals = FromType.getQualifiers();
3157 Qualifiers ToQuals = ToType.getQualifiers();
3158 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3159 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3160 return false;
3161 }
3162
Douglas Gregor9a657932008-10-21 23:43:52 +00003163 // We are left with FromType and ToType being the pointee types
3164 // after unwrapping the original FromType and ToType the same number
3165 // of types. If we unwrapped any pointers, and if FromType and
3166 // ToType have the same unqualified type (since we checked
3167 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003168 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003169}
3170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003171/// - Determine whether this is a conversion from a scalar type to an
Douglas Gregorc79862f2012-04-12 17:51:55 +00003172/// atomic type.
3173///
3174/// If successful, updates \c SCS's second and third steps in the conversion
3175/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003176static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3177 bool InOverloadResolution,
3178 StandardConversionSequence &SCS,
3179 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003180 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3181 if (!ToAtomic)
3182 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003183
Douglas Gregorc79862f2012-04-12 17:51:55 +00003184 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003185 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003186 InOverloadResolution, InnerSCS,
3187 CStyle, /*AllowObjCWritebackConversion=*/false))
3188 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003189
Douglas Gregorc79862f2012-04-12 17:51:55 +00003190 SCS.Second = InnerSCS.Second;
3191 SCS.setToType(1, InnerSCS.getToType(1));
3192 SCS.Third = InnerSCS.Third;
3193 SCS.QualificationIncludesObjCLifetime
3194 = InnerSCS.QualificationIncludesObjCLifetime;
3195 SCS.setToType(2, InnerSCS.getToType(2));
3196 return true;
3197}
3198
Sebastian Redle5417162012-03-27 18:33:03 +00003199static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3200 CXXConstructorDecl *Constructor,
3201 QualType Type) {
3202 const FunctionProtoType *CtorType =
3203 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003204 if (CtorType->getNumParams() > 0) {
3205 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003206 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3207 return true;
3208 }
3209 return false;
3210}
3211
Sebastian Redl82ace982012-02-11 23:51:08 +00003212static OverloadingResult
3213IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3214 CXXRecordDecl *To,
3215 UserDefinedConversionSequence &User,
3216 OverloadCandidateSet &CandidateSet,
3217 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003218 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003219 for (auto *D : S.LookupConstructors(To)) {
3220 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003221 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003222 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003223
Richard Smithc2bebe92016-05-11 20:37:46 +00003224 bool Usable = !Info.Constructor->isInvalidDecl() &&
3225 S.isInitListConstructor(Info.Constructor) &&
3226 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003227 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003228 // If the first argument is (a reference to) the target type,
3229 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003230 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3231 S.Context, Info.Constructor, ToType);
3232 if (Info.ConstructorTmpl)
3233 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3234 /*ExplicitArgs*/ nullptr, From,
3235 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003236 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003237 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3238 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003239 }
3240 }
3241
3242 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3243
3244 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003245 switch (auto Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003246 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003247 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003248 case OR_Success: {
3249 // Record the standard conversion we used and the conversion function.
3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003251 QualType ThisType = Constructor->getThisType(S.Context);
3252 // Initializer lists don't have conversions as such.
3253 User.Before.setAsIdentityConversion();
3254 User.HadMultipleCandidates = HadMultipleCandidates;
3255 User.ConversionFunction = Constructor;
3256 User.FoundConversionFunction = Best->FoundDecl;
3257 User.After.setAsIdentityConversion();
3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003260 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003261 }
3262
3263 case OR_No_Viable_Function:
3264 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003265 case OR_Ambiguous:
3266 return OR_Ambiguous;
3267 }
3268
3269 llvm_unreachable("Invalid OverloadResult!");
3270}
3271
Douglas Gregor576e98c2009-01-30 23:27:23 +00003272/// Determines whether there is a user-defined conversion sequence
3273/// (C++ [over.ics.user]) that converts expression From to the type
3274/// ToType. If such a conversion exists, User will contain the
3275/// user-defined conversion sequence that performs such a conversion
3276/// and this routine will return true. Otherwise, this routine returns
3277/// false and User is unspecified.
3278///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003279/// \param AllowExplicit true if the conversion should consider C++0x
3280/// "explicit" conversion functions as well as non-explicit conversion
3281/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003282///
3283/// \param AllowObjCConversionOnExplicit true if the conversion should
3284/// allow an extra Objective-C pointer conversion on uses of explicit
3285/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003286static OverloadingResult
3287IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003288 UserDefinedConversionSequence &User,
3289 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003290 bool AllowExplicit,
3291 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003292 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Richard Smith67ef14f2017-09-26 18:37:55 +00003293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003294
Douglas Gregor5ab11652010-04-17 22:01:05 +00003295 // Whether we will only visit constructors.
3296 bool ConstructorsOnly = false;
3297
3298 // If the type we are conversion to is a class type, enumerate its
3299 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003301 // C++ [over.match.ctor]p1:
3302 // When objects of class type are direct-initialized (8.5), or
3303 // copy-initialized from an expression of the same or a
3304 // derived class type (8.5), overload resolution selects the
3305 // constructor. [...] For copy-initialization, the candidate
3306 // functions are all the converting constructors (12.3.1) of
3307 // that class. The argument list is the expression-list within
3308 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003310 (From->getType()->getAs<RecordType>() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003311 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003312 ConstructorsOnly = true;
3313
Richard Smithdb0ac552015-12-18 22:40:25 +00003314 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003315 // We're not going to find any constructors.
3316 } else if (CXXRecordDecl *ToRecordDecl
3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003318
3319 Expr **Args = &From;
3320 unsigned NumArgs = 1;
3321 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003323 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003324 OverloadingResult Result = IsInitializerListConstructorConversion(
3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326 if (Result != OR_No_Viable_Function)
3327 return Result;
3328 // Never mind.
Richard Smith67ef14f2017-09-26 18:37:55 +00003329 CandidateSet.clear(
3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Sebastian Redl82ace982012-02-11 23:51:08 +00003331
3332 // If we're list-initializing, we pass the individual elements as
3333 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003334 Args = InitList->getInits();
3335 NumArgs = InitList->getNumInits();
3336 ListInitializing = true;
3337 }
3338
Richard Smithc2bebe92016-05-11 20:37:46 +00003339 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003341 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003342 continue;
John McCalla0296f72010-03-19 07:35:19 +00003343
Richard Smithc2bebe92016-05-11 20:37:46 +00003344 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003345 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003347 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003348 Usable = Usable &&
3349 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003350 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003351 bool SuppressUserConversions = !ConstructorsOnly;
3352 if (SuppressUserConversions && ListInitializing) {
3353 SuppressUserConversions = false;
3354 if (NumArgs == 1) {
3355 // If the first argument is (a reference to) the target type,
3356 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003357 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003358 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003359 }
3360 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003361 if (Info.ConstructorTmpl)
3362 S.AddTemplateOverloadCandidate(
3363 Info.ConstructorTmpl, Info.FoundDecl,
3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003366 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003367 // Allow one user-defined conversion when user specifies a
3368 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003370 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003371 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003372 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003373 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003374 }
3375 }
3376
Douglas Gregor5ab11652010-04-17 22:01:05 +00003377 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003378 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003379 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003380 // No conversion functions from incomplete types.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003381 } else if (const RecordType *FromRecordType =
3382 From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003383 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003388 DeclAccessPair FoundDecl = I.getPair();
3389 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391 if (isa<UsingShadowDecl>(D))
3392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003394 CXXConversionDecl *Conv;
3395 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003398 else
John McCallda4458e2010-03-31 01:36:47 +00003399 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003400
3401 if (AllowExplicit || !Conv->isExplicit()) {
3402 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003405 CandidateSet,
3406 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003407 else
John McCall5c32be02010-08-24 20:38:10 +00003408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003409 From, ToType, CandidateSet,
3410 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003411 }
3412 }
3413 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003414 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003415
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003416 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003418 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003419 switch (auto Result =
3420 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
John McCall5c32be02010-08-24 20:38:10 +00003421 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003422 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003423 // Record the standard conversion we used and the conversion function.
3424 if (CXXConstructorDecl *Constructor
3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426 // C++ [over.ics.user]p1:
3427 // If the user-defined conversion is specified by a
3428 // constructor (12.3.1), the initial standard conversion
3429 // sequence converts the source type to the type required by
3430 // the argument of the constructor.
3431 //
3432 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003433 if (isa<InitListExpr>(From)) {
3434 // Initializer lists don't have conversions as such.
3435 User.Before.setAsIdentityConversion();
3436 } else {
3437 if (Best->Conversions[0].isEllipsis())
3438 User.EllipsisConversion = true;
3439 else {
3440 User.Before = Best->Conversions[0].Standard;
3441 User.EllipsisConversion = false;
3442 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003443 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003444 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003445 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003446 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003447 User.After.setAsIdentityConversion();
3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003450 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003451 }
3452 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003453 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454 // C++ [over.ics.user]p1:
3455 //
3456 // [...] If the user-defined conversion is specified by a
3457 // conversion function (12.3.2), the initial standard
3458 // conversion sequence converts the source type to the
3459 // implicit object parameter of the conversion function.
3460 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003461 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003462 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003463 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003464 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003465
John McCall5c32be02010-08-24 20:38:10 +00003466 // C++ [over.ics.user]p2:
3467 // The second standard conversion sequence converts the
3468 // result of the user-defined conversion to the target type
3469 // for the sequence. Since an implicit conversion sequence
3470 // is an initialization, the special rules for
3471 // initialization by user-defined conversion apply when
3472 // selecting the best user-defined conversion for a
3473 // user-defined conversion sequence (see 13.3.3 and
3474 // 13.3.3.1).
3475 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003476 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003477 }
David Blaikie8a40f702012-01-17 06:56:22 +00003478 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003479
John McCall5c32be02010-08-24 20:38:10 +00003480 case OR_No_Viable_Function:
3481 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
John McCall5c32be02010-08-24 20:38:10 +00003483 case OR_Ambiguous:
3484 return OR_Ambiguous;
3485 }
3486
David Blaikie8a40f702012-01-17 06:56:22 +00003487 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003488}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003490bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003491Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003492 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003493 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003497 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003498 if (OvResult == OR_Ambiguous)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003499 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003500 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003502 if (!RequireCompleteType(From->getBeginLoc(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003503 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003504 From->getType(), From->getSourceRange()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003505 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003506 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003507 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003508 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003511}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003513/// Compare the user-defined conversion functions or constructors
Douglas Gregor2837aa22012-02-22 17:32:19 +00003514/// of two user-defined conversion sequences to determine whether any ordering
3515/// is possible.
3516static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003517compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003518 FunctionDecl *Function2) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003519 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003520 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003521
Douglas Gregor2837aa22012-02-22 17:32:19 +00003522 // Objective-C++:
3523 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003524 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003525 // respectively, always prefer the conversion to a function pointer,
3526 // because the function pointer is more lightweight and is more likely
3527 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003529 if (!Conv1)
3530 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003531
Douglas Gregor2837aa22012-02-22 17:32:19 +00003532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533 if (!Conv2)
3534 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003535
Douglas Gregor2837aa22012-02-22 17:32:19 +00003536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003540 return Block1 ? ImplicitConversionSequence::Worse
3541 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003542 }
3543
3544 return ImplicitConversionSequence::Indistinguishable;
3545}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003546
3547static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548 const ImplicitConversionSequence &ICS) {
3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550 (ICS.isUserDefined() &&
3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552}
3553
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003554/// CompareImplicitConversionSequences - Compare two implicit
3555/// conversion sequences to determine whether one is better than the
3556/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003557static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003558CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003559 const ImplicitConversionSequence& ICS1,
3560 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003561{
3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563 // conversion sequences (as defined in 13.3.3.1)
3564 // -- a standard conversion sequence (13.3.3.1.1) is a better
3565 // conversion sequence than a user-defined conversion sequence or
3566 // an ellipsis conversion sequence, and
3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568 // conversion sequence than an ellipsis conversion sequence
3569 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003570 //
John McCall0d1da222010-01-12 00:44:57 +00003571 // C++0x [over.best.ics]p10:
3572 // For the purpose of ranking implicit conversion sequences as
3573 // described in 13.3.3.2, the ambiguous conversion sequence is
3574 // treated as a user-defined sequence that is indistinguishable
3575 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003576
3577 // String literal to 'char *' conversion has been deprecated in C++03. It has
3578 // been removed from C++11. We still accept this conversion, if it happens at
3579 // the best viable function. Otherwise, this conversion is considered worse
3580 // than ellipsis conversion. Consider this as an extension; this is not in the
3581 // standard. For example:
3582 //
3583 // int &f(...); // #1
3584 // void f(char*); // #2
3585 // void g() { int &r = f("foo"); }
3586 //
3587 // In C++03, we pick #2 as the best viable function.
3588 // In C++11, we pick #1 as the best viable function, because ellipsis
3589 // conversion is better than string-literal to char* conversion (since there
3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591 // convert arguments, #2 would be the best viable function in C++11.
3592 // If the best viable function has this conversion, a warning will be issued
3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594
3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599 ? ImplicitConversionSequence::Worse
3600 : ImplicitConversionSequence::Better;
3601
Douglas Gregor5ab11652010-04-17 22:01:05 +00003602 if (ICS1.getKindRank() < ICS2.getKindRank())
3603 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003604 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003605 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003606
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003607 // The following checks require both conversion sequences to be of
3608 // the same kind.
3609 if (ICS1.getKind() != ICS2.getKind())
3610 return ImplicitConversionSequence::Indistinguishable;
3611
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003612 ImplicitConversionSequence::CompareKind Result =
3613 ImplicitConversionSequence::Indistinguishable;
3614
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003615 // Two implicit conversion sequences of the same form are
3616 // indistinguishable conversion sequences unless one of the
3617 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003618
Larisse Voufo19d08672015-01-27 18:47:05 +00003619 // List-initialization sequence L1 is a better conversion sequence than
3620 // list-initialization sequence L2 if:
3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003624 // and N1 is smaller than N2.,
3625 // even if one of the other rules in this paragraph would otherwise apply.
3626 if (!ICS1.isBad()) {
3627 if (ICS1.isStdInitializerListElement() &&
3628 !ICS2.isStdInitializerListElement())
3629 return ImplicitConversionSequence::Better;
3630 if (!ICS1.isStdInitializerListElement() &&
3631 ICS2.isStdInitializerListElement())
3632 return ImplicitConversionSequence::Worse;
3633 }
3634
John McCall0d1da222010-01-12 00:44:57 +00003635 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003636 // Standard conversion sequence S1 is a better conversion sequence than
3637 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003638 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003639 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003640 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003641 // User-defined conversion sequence U1 is a better conversion
3642 // sequence than another user-defined conversion sequence U2 if
3643 // they contain the same user-defined conversion function or
3644 // constructor and if the second standard conversion sequence of
3645 // U1 is better than the second standard conversion sequence of
3646 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003647 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003648 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003649 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003650 ICS1.UserDefined.After,
3651 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003652 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003653 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003654 ICS1.UserDefined.ConversionFunction,
3655 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003656 }
3657
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003658 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003659}
3660
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003661// Per 13.3.3.2p3, compare the given standard conversion sequences to
3662// determine if one is a proper subset of the other.
3663static ImplicitConversionSequence::CompareKind
3664compareStandardConversionSubsets(ASTContext &Context,
3665 const StandardConversionSequence& SCS1,
3666 const StandardConversionSequence& SCS2) {
3667 ImplicitConversionSequence::CompareKind Result
3668 = ImplicitConversionSequence::Indistinguishable;
3669
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003671 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673 return ImplicitConversionSequence::Better;
3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003677 if (SCS1.Second != SCS2.Second) {
3678 if (SCS1.Second == ICK_Identity)
3679 Result = ImplicitConversionSequence::Better;
3680 else if (SCS2.Second == ICK_Identity)
3681 Result = ImplicitConversionSequence::Worse;
3682 else
3683 return ImplicitConversionSequence::Indistinguishable;
Richard Smitha3405ff2018-07-11 00:19:19 +00003684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003685 return ImplicitConversionSequence::Indistinguishable;
3686
3687 if (SCS1.Third == SCS2.Third) {
3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689 : ImplicitConversionSequence::Indistinguishable;
3690 }
3691
3692 if (SCS1.Third == ICK_Identity)
3693 return Result == ImplicitConversionSequence::Worse
3694 ? ImplicitConversionSequence::Indistinguishable
3695 : ImplicitConversionSequence::Better;
3696
3697 if (SCS2.Third == ICK_Identity)
3698 return Result == ImplicitConversionSequence::Better
3699 ? ImplicitConversionSequence::Indistinguishable
3700 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003702 return ImplicitConversionSequence::Indistinguishable;
3703}
3704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003705/// Determine whether one of the given reference bindings is better
Douglas Gregore696ebb2011-01-26 14:52:12 +00003706/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003707static bool
3708isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003710 // C++0x [over.ics.rank]p3b4:
3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003716 // reference*.
3717 //
3718 // FIXME: Rvalue references. We're going rogue with the above edits,
3719 // because the semantics in the current C++0x working paper (N3225 at the
3720 // time of this writing) break the standard definition of std::forward
3721 // and std::reference_wrapper when dealing with references to functions.
3722 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregore696ebb2011-01-26 14:52:12 +00003727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728 SCS2.IsLvalueReference) ||
3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003731}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733/// CompareStandardConversionSequences - Compare two standard
3734/// conversion sequences to determine whether one is better than the
3735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003736static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003737CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003738 const StandardConversionSequence& SCS1,
3739 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003740{
3741 // Standard conversion sequence S1 is a better conversion sequence
3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743
3744 // -- S1 is a proper subsequence of S2 (comparing the conversion
3745 // sequences in the canonical form defined by 13.3.3.1.1,
3746 // excluding any Lvalue Transformation; the identity conversion
3747 // sequence is considered to be a subsequence of any
3748 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003749 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003751 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003752
3753 // -- the rank of S1 is better than the rank of S2 (by the rules
3754 // defined below), or, if not that,
3755 ImplicitConversionRank Rank1 = SCS1.getRank();
3756 ImplicitConversionRank Rank2 = SCS2.getRank();
3757 if (Rank1 < Rank2)
3758 return ImplicitConversionSequence::Better;
3759 else if (Rank2 < Rank1)
3760 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003761
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763 // are indistinguishable unless one of the following rules
3764 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003765
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003766 // A conversion that is not a conversion of a pointer, or
3767 // pointer to member, to bool is better than another conversion
3768 // that is such a conversion.
3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770 return SCS2.isPointerConversionToBool()
3771 ? ImplicitConversionSequence::Better
3772 : ImplicitConversionSequence::Worse;
3773
Douglas Gregor5c407d92008-10-23 00:40:37 +00003774 // C++ [over.ics.rank]p4b2:
3775 //
3776 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003777 // conversion of B* to A* is better than conversion of B* to
3778 // void*, and conversion of A* to void* is better than conversion
3779 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003780 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003781 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003782 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003783 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785 // Exactly one of the conversion sequences is a conversion to
3786 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790 // Neither conversion sequence converts to a void pointer; compare
3791 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003792 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003797 // Both conversion sequences are conversions to void
3798 // pointers. Compare the source types to determine if there's an
3799 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003800 QualType FromType1 = SCS1.getFromType();
3801 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802
3803 // Adjust the types we're converting from via the array-to-pointer
3804 // conversion, if we need to.
3805 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003806 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003807 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003808 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003812
Richard Smith0f59cb32015-12-18 21:45:41 +00003813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003814 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003816 return ImplicitConversionSequence::Worse;
3817
3818 // Objective-C++: If one interface is more specific than the
3819 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003820 const ObjCObjectPointerType* FromObjCPtr1
3821 = FromType1->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType* FromObjCPtr2
3823 = FromType2->getAs<ObjCObjectPointerType>();
3824 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003826 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003828 FromObjCPtr1);
3829 if (AssignLeft != AssignRight) {
3830 return AssignLeft? ImplicitConversionSequence::Better
3831 : ImplicitConversionSequence::Worse;
3832 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003833 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003834 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003835
3836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003838 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003839 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003840 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003841
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003843 // Check for a better reference binding based on the kind of bindings.
3844 if (isBetterReferenceBindingKind(SCS1, SCS2))
3845 return ImplicitConversionSequence::Better;
3846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003848
Sebastian Redlb28b4072009-03-22 23:49:27 +00003849 // C++ [over.ics.rank]p3b4:
3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3851 // which the references refer are the same type except for
3852 // top-level cv-qualifiers, and the type to which the reference
3853 // initialized by S2 refers is more cv-qualified than the type
3854 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003855 QualType T1 = SCS1.getToType(2);
3856 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003857 T1 = S.Context.getCanonicalType(T1);
3858 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003859 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003862 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003863 // Objective-C++ ARC: If the references refer to objects with different
3864 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003865 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003866 SCS2.ObjCLifetimeConversionBinding) {
3867 return SCS1.ObjCLifetimeConversionBinding
3868 ? ImplicitConversionSequence::Worse
3869 : ImplicitConversionSequence::Better;
3870 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003871
Chandler Carruth8e543b32010-12-12 08:17:55 +00003872 // If the type is an array type, promote the element qualifiers to the
3873 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003874 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003876 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003878 if (T2.isMoreQualifiedThan(T1))
3879 return ImplicitConversionSequence::Better;
3880 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003881 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003882 }
3883 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003884
Francois Pichet08d2fa02011-09-18 21:37:37 +00003885 // In Microsoft mode, prefer an integral conversion to a
3886 // floating-to-integral conversion if the integral conversion
3887 // is between types of the same size.
3888 // For example:
3889 // void f(float);
3890 // void f(int);
3891 // int main {
3892 // long a;
3893 // f(a);
3894 // }
3895 // Here, MSVC will call f(int) instead of generating a compile error
3896 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003899 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003900 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003901 return ImplicitConversionSequence::Better;
3902
Zi Xuan Wu64d85a22018-11-16 03:00:00 +00003903 // Prefer a compatible vector conversion over a lax vector conversion
3904 // For example:
3905 //
3906 // typedef float __v4sf __attribute__((__vector_size__(16)));
3907 // void f(vector float);
3908 // void f(vector signed int);
3909 // int main() {
3910 // __v4sf a;
3911 // f(a);
3912 // }
3913 // Here, we'd like to choose f(vector float) and not
3914 // report an ambiguous call error
3915 if (SCS1.Second == ICK_Vector_Conversion &&
3916 SCS2.Second == ICK_Vector_Conversion) {
3917 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3918 SCS1.getFromType(), SCS1.getToType(2));
3919 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3920 SCS2.getFromType(), SCS2.getToType(2));
3921
3922 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3923 return SCS1IsCompatibleVectorConversion
3924 ? ImplicitConversionSequence::Better
3925 : ImplicitConversionSequence::Worse;
3926 }
3927
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003928 return ImplicitConversionSequence::Indistinguishable;
3929}
3930
3931/// CompareQualificationConversions - Compares two standard conversion
3932/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003933/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003934static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003935CompareQualificationConversions(Sema &S,
3936 const StandardConversionSequence& SCS1,
3937 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003938 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003939 // -- S1 and S2 differ only in their qualification conversion and
3940 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3941 // cv-qualification signature of type T1 is a proper subset of
3942 // the cv-qualification signature of type T2, and S1 is not the
3943 // deprecated string literal array-to-pointer conversion (4.2).
3944 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3945 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3946 return ImplicitConversionSequence::Indistinguishable;
3947
3948 // FIXME: the example in the standard doesn't use a qualification
3949 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003950 QualType T1 = SCS1.getToType(2);
3951 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003952 T1 = S.Context.getCanonicalType(T1);
3953 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003954 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003955 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3956 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003957
3958 // If the types are the same, we won't learn anything by unwrapped
3959 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003960 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003961 return ImplicitConversionSequence::Indistinguishable;
3962
Chandler Carruth607f38e2009-12-29 07:16:59 +00003963 // If the type is an array type, promote the element qualifiers to the type
3964 // for comparison.
3965 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003966 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003967 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003968 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003969
Mike Stump11289f42009-09-09 15:08:12 +00003970 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003971 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003972
John McCall31168b02011-06-15 23:02:42 +00003973 // Objective-C++ ARC:
3974 // Prefer qualification conversions not involving a change in lifetime
3975 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003976 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003977 SCS2.QualificationIncludesObjCLifetime) {
3978 Result = SCS1.QualificationIncludesObjCLifetime
3979 ? ImplicitConversionSequence::Worse
3980 : ImplicitConversionSequence::Better;
3981 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003982
Richard Smitha3405ff2018-07-11 00:19:19 +00003983 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003984 // Within each iteration of the loop, we check the qualifiers to
3985 // determine if this still looks like a qualification
3986 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003987 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003988 // until there are no more pointers or pointers-to-members left
3989 // to unwrap. This essentially mimics what
3990 // IsQualificationConversion does, but here we're checking for a
3991 // strict subset of qualifiers.
3992 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3993 // The qualifiers are the same, so this doesn't tell us anything
3994 // about how the sequences rank.
3995 ;
3996 else if (T2.isMoreQualifiedThan(T1)) {
3997 // T1 has fewer qualifiers, so it could be the better sequence.
3998 if (Result == ImplicitConversionSequence::Worse)
3999 // Neither has qualifiers that are a subset of the other's
4000 // qualifiers.
4001 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00004002
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004003 Result = ImplicitConversionSequence::Better;
4004 } else if (T1.isMoreQualifiedThan(T2)) {
4005 // T2 has fewer qualifiers, so it could be the better sequence.
4006 if (Result == ImplicitConversionSequence::Better)
4007 // Neither has qualifiers that are a subset of the other's
4008 // qualifiers.
4009 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004011 Result = ImplicitConversionSequence::Worse;
4012 } else {
4013 // Qualifiers are disjoint.
4014 return ImplicitConversionSequence::Indistinguishable;
4015 }
4016
4017 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00004018 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004019 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004020 }
4021
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004022 // Check that the winning standard conversion sequence isn't using
4023 // the deprecated string literal array to pointer conversion.
4024 switch (Result) {
4025 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004026 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004027 Result = ImplicitConversionSequence::Indistinguishable;
4028 break;
4029
4030 case ImplicitConversionSequence::Indistinguishable:
4031 break;
4032
4033 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004034 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004035 Result = ImplicitConversionSequence::Indistinguishable;
4036 break;
4037 }
4038
4039 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004040}
4041
Douglas Gregor5c407d92008-10-23 00:40:37 +00004042/// CompareDerivedToBaseConversions - Compares two standard conversion
4043/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00004044/// various kinds of derived-to-base conversions (C++
4045/// [over.ics.rank]p4b3). As part of these checks, we also look at
4046/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00004047static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00004048CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00004049 const StandardConversionSequence& SCS1,
4050 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00004051 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004052 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00004053 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004054 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004055
4056 // Adjust the types we're converting from via the array-to-pointer
4057 // conversion, if we need to.
4058 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004059 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004060 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004061 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004062
4063 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004064 FromType1 = S.Context.getCanonicalType(FromType1);
4065 ToType1 = S.Context.getCanonicalType(ToType1);
4066 FromType2 = S.Context.getCanonicalType(FromType2);
4067 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004068
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004069 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004070 //
4071 // If class B is derived directly or indirectly from class A and
4072 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004073 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004074 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004075 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004076 SCS2.Second == ICK_Pointer_Conversion &&
4077 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4078 FromType1->isPointerType() && FromType2->isPointerType() &&
4079 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004080 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004081 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004082 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004083 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004084 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004086 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004087 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004088
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004089 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004090 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004091 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004092 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004093 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004094 return ImplicitConversionSequence::Worse;
4095 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004096
4097 // -- conversion of B* to A* is better than conversion of C* to A*,
4098 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004099 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004100 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004101 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004102 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004103 }
4104 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4105 SCS2.Second == ICK_Pointer_Conversion) {
4106 const ObjCObjectPointerType *FromPtr1
4107 = FromType1->getAs<ObjCObjectPointerType>();
4108 const ObjCObjectPointerType *FromPtr2
4109 = FromType2->getAs<ObjCObjectPointerType>();
4110 const ObjCObjectPointerType *ToPtr1
4111 = ToType1->getAs<ObjCObjectPointerType>();
4112 const ObjCObjectPointerType *ToPtr2
4113 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004114
Douglas Gregor058d3de2011-01-31 18:51:41 +00004115 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4116 // Apply the same conversion ranking rules for Objective-C pointer types
4117 // that we do for C++ pointers to class types. However, we employ the
4118 // Objective-C pseudo-subtyping relationship used for assignment of
4119 // Objective-C pointer types.
4120 bool FromAssignLeft
4121 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4122 bool FromAssignRight
4123 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4124 bool ToAssignLeft
4125 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4126 bool ToAssignRight
4127 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004128
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004129 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004130 // type is better than a conversion to 'id'.
4131 if (ToPtr1->isObjCIdType() &&
4132 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4133 return ImplicitConversionSequence::Worse;
4134 if (ToPtr2->isObjCIdType() &&
4135 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4136 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004137
4138 // A conversion to a non-id object pointer type is better than a
4139 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004140 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4141 return ImplicitConversionSequence::Worse;
4142 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4143 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004144
4145 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004146 // type is better than a conversion to 'Class'.
4147 if (ToPtr1->isObjCClassType() &&
4148 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4149 return ImplicitConversionSequence::Worse;
4150 if (ToPtr2->isObjCClassType() &&
4151 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4152 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004153
4154 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004155 // conversion to a qualified 'Class' type.
4156 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4157 return ImplicitConversionSequence::Worse;
4158 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4159 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004160
Douglas Gregor058d3de2011-01-31 18:51:41 +00004161 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004162 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004163 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004164 (ToAssignLeft != ToAssignRight)) {
4165 if (FromPtr1->isSpecialized()) {
4166 // "conversion of B<A> * to B * is better than conversion of B * to
4167 // C *.
4168 bool IsFirstSame =
4169 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4170 bool IsSecondSame =
4171 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4172 if (IsFirstSame) {
4173 if (!IsSecondSame)
4174 return ImplicitConversionSequence::Better;
4175 } else if (IsSecondSame)
4176 return ImplicitConversionSequence::Worse;
4177 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004178 return ToAssignLeft? ImplicitConversionSequence::Worse
4179 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004180 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004181
4182 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4183 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4184 (FromAssignLeft != FromAssignRight))
4185 return FromAssignLeft? ImplicitConversionSequence::Better
4186 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004187 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004188 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004189
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004190 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004191 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4192 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4193 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004195 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004196 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004197 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004199 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004201 ToType2->getAs<MemberPointerType>();
4202 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4203 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4204 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4205 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4206 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4207 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4208 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4209 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004210 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004211 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004212 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004213 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004214 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004215 return ImplicitConversionSequence::Better;
4216 }
4217 // conversion of B::* to C::* is better than conversion of A::* to C::*
4218 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004219 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004220 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004221 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004222 return ImplicitConversionSequence::Worse;
4223 }
4224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Douglas Gregor5ab11652010-04-17 22:01:05 +00004226 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004227 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004228 // -- binding of an expression of type C to a reference of type
4229 // B& is better than binding an expression of type C to a
4230 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004231 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4232 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004233 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004234 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004235 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004236 return ImplicitConversionSequence::Worse;
4237 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004238
Douglas Gregor2fe98832008-11-03 19:09:14 +00004239 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004240 // -- binding of an expression of type B to a reference of type
4241 // A& is better than binding an expression of type C to a
4242 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004243 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4244 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004245 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004246 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004247 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004248 return ImplicitConversionSequence::Worse;
4249 }
4250 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004251
Douglas Gregor5c407d92008-10-23 00:40:37 +00004252 return ImplicitConversionSequence::Indistinguishable;
4253}
4254
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004255/// Determine whether the given type is valid, e.g., it is not an invalid
Douglas Gregor45bb4832013-03-26 23:36:30 +00004256/// C++ class.
4257static bool isTypeValid(QualType T) {
4258 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4259 return !Record->isInvalidDecl();
4260
4261 return true;
4262}
4263
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004264/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4265/// determine whether they are reference-related,
4266/// reference-compatible, reference-compatible with added
4267/// qualification, or incompatible, for use in C++ initialization by
4268/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4269/// type, and the first type (T1) is the pointee type of the reference
4270/// type being initialized.
4271Sema::ReferenceCompareResult
4272Sema::CompareReferenceRelationship(SourceLocation Loc,
4273 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004274 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004275 bool &ObjCConversion,
4276 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004277 assert(!OrigT1->isReferenceType() &&
4278 "T1 must be the pointee type of the reference type");
4279 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4280
4281 QualType T1 = Context.getCanonicalType(OrigT1);
4282 QualType T2 = Context.getCanonicalType(OrigT2);
4283 Qualifiers T1Quals, T2Quals;
4284 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4285 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4286
4287 // C++ [dcl.init.ref]p4:
4288 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4289 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4290 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004291 DerivedToBase = false;
4292 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004293 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004294 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004295 if (UnqualT1 == UnqualT2) {
4296 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004297 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004298 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004299 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004301 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4302 UnqualT2->isObjCObjectOrInterfaceType() &&
4303 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4304 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004305 else if (UnqualT2->isFunctionType() &&
4306 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4307 // C++1z [dcl.init.ref]p4:
4308 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4309 // function" and T1 is "function"
4310 //
4311 // We extend this to also apply to 'noreturn', so allow any function
4312 // conversion between function types.
4313 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004314 else
4315 return Ref_Incompatible;
4316
4317 // At this point, we know that T1 and T2 are reference-related (at
4318 // least).
4319
4320 // If the type is an array type, promote the element qualifiers to the type
4321 // for comparison.
4322 if (isa<ArrayType>(T1) && T1Quals)
4323 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4324 if (isa<ArrayType>(T2) && T2Quals)
4325 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4326
4327 // C++ [dcl.init.ref]p4:
4328 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4329 // reference-related to T2 and cv1 is the same cv-qualification
4330 // as, or greater cv-qualification than, cv2. For purposes of
4331 // overload resolution, cases for which cv1 is greater
4332 // cv-qualification than cv2 are identified as
4333 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004334 //
4335 // Note that we also require equivalence of Objective-C GC and address-space
4336 // qualifiers when performing these computations, so that e.g., an int in
4337 // address space 1 is not reference-compatible with an int in address
4338 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004339 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4340 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004341 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4342 ObjCLifetimeConversion = true;
4343
John McCall31168b02011-06-15 23:02:42 +00004344 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004345 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004346 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004347
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004348 // MS compiler ignores __unaligned qualifier for references; do the same.
4349 T1Quals.removeUnaligned();
4350 T2Quals.removeUnaligned();
4351
Richard Smithce766292016-10-21 23:01:55 +00004352 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004353 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004354 else
4355 return Ref_Related;
4356}
4357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004358/// Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004359/// with DeclType. Return true if something definite is found.
4360static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004361FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4362 QualType DeclType, SourceLocation DeclLoc,
4363 Expr *Init, QualType T2, bool AllowRvalues,
4364 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004365 assert(T2->isRecordType() && "Can only find conversions of record types.");
4366 CXXRecordDecl *T2RecordDecl
4367 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4368
Richard Smith67ef14f2017-09-26 18:37:55 +00004369 OverloadCandidateSet CandidateSet(
4370 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004371 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4372 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004373 NamedDecl *D = *I;
4374 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4375 if (isa<UsingShadowDecl>(D))
4376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4377
4378 FunctionTemplateDecl *ConvTemplate
4379 = dyn_cast<FunctionTemplateDecl>(D);
4380 CXXConversionDecl *Conv;
4381 if (ConvTemplate)
4382 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4383 else
4384 Conv = cast<CXXConversionDecl>(D);
4385
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004387 // explicit conversions, skip it.
4388 if (!AllowExplicit && Conv->isExplicit())
4389 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregor836a7e82010-08-11 02:15:33 +00004391 if (AllowRvalues) {
4392 bool DerivedToBase = false;
4393 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004394 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004395
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004396 // If we are initializing an rvalue reference, don't permit conversion
4397 // functions that return lvalues.
4398 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4399 const ReferenceType *RefType
4400 = Conv->getConversionType()->getAs<LValueReferenceType>();
4401 if (RefType && !RefType->getPointeeType()->isFunctionType())
4402 continue;
4403 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004404
Douglas Gregor836a7e82010-08-11 02:15:33 +00004405 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004406 S.CompareReferenceRelationship(
4407 DeclLoc,
4408 Conv->getConversionType().getNonReferenceType()
4409 .getUnqualifiedType(),
4410 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004411 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004412 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004413 continue;
4414 } else {
4415 // If the conversion function doesn't return a reference type,
4416 // it can't be considered for this conversion. An rvalue reference
4417 // is only acceptable if its referencee is a function type.
4418
4419 const ReferenceType *RefType =
4420 Conv->getConversionType()->getAs<ReferenceType>();
4421 if (!RefType ||
4422 (!RefType->isLValueReferenceType() &&
4423 !RefType->getPointeeType()->isFunctionType()))
4424 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Douglas Gregor836a7e82010-08-11 02:15:33 +00004427 if (ConvTemplate)
4428 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004429 Init, DeclType, CandidateSet,
4430 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004431 else
4432 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004433 DeclType, CandidateSet,
4434 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004435 }
4436
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004437 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4438
Sebastian Redld92badf2010-06-30 18:13:39 +00004439 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004440 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004441 case OR_Success:
4442 // C++ [over.ics.ref]p1:
4443 //
4444 // [...] If the parameter binds directly to the result of
4445 // applying a conversion function to the argument
4446 // expression, the implicit conversion sequence is a
4447 // user-defined conversion sequence (13.3.3.1.2), with the
4448 // second standard conversion sequence either an identity
4449 // conversion or, if the conversion function returns an
4450 // entity of a type that is a derived class of the parameter
4451 // type, a derived-to-base Conversion.
4452 if (!Best->FinalConversion.DirectBinding)
4453 return false;
4454
4455 ICS.setUserDefined();
4456 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4457 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004458 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004459 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004460 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004461 ICS.UserDefined.EllipsisConversion = false;
4462 assert(ICS.UserDefined.After.ReferenceBinding &&
4463 ICS.UserDefined.After.DirectBinding &&
4464 "Expected a direct reference binding!");
4465 return true;
4466
4467 case OR_Ambiguous:
4468 ICS.setAmbiguous();
4469 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4470 Cand != CandidateSet.end(); ++Cand)
4471 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004472 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004473 return true;
4474
4475 case OR_No_Viable_Function:
4476 case OR_Deleted:
4477 // There was no suitable conversion, or we found a deleted
4478 // conversion; continue with other checks.
4479 return false;
4480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
David Blaikie8a40f702012-01-17 06:56:22 +00004482 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004483}
4484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004485/// Compute an implicit conversion sequence for reference
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004486/// initialization.
4487static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004488TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004489 SourceLocation DeclLoc,
4490 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004491 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004492 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4493
4494 // Most paths end in a failed conversion.
4495 ImplicitConversionSequence ICS;
4496 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4497
4498 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4499 QualType T2 = Init->getType();
4500
4501 // If the initializer is the address of an overloaded function, try
4502 // to resolve the overloaded function. If all goes well, T2 is the
4503 // type of the resulting function.
4504 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4505 DeclAccessPair Found;
4506 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4507 false, Found))
4508 T2 = Fn->getType();
4509 }
4510
4511 // Compute some basic properties of the types and the initializer.
4512 bool isRValRef = DeclType->isRValueReferenceType();
4513 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004514 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004515 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004516 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004517 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004518 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004519 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004520
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004521
Sebastian Redld92badf2010-06-30 18:13:39 +00004522 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004523 // A reference to type "cv1 T1" is initialized by an expression
4524 // of type "cv2 T2" as follows:
4525
Sebastian Redld92badf2010-06-30 18:13:39 +00004526 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004527 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004528 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4529 // reference-compatible with "cv2 T2," or
4530 //
4531 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004532 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004533 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004534 // When a parameter of reference type binds directly (8.5.3)
4535 // to an argument expression, the implicit conversion sequence
4536 // is the identity conversion, unless the argument expression
4537 // has a type that is a derived class of the parameter type,
4538 // in which case the implicit conversion sequence is a
4539 // derived-to-base Conversion (13.3.3.1).
4540 ICS.setStandard();
4541 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004542 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4543 : ObjCConversion? ICK_Compatible_Conversion
4544 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004545 ICS.Standard.Third = ICK_Identity;
4546 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4547 ICS.Standard.setToType(0, T2);
4548 ICS.Standard.setToType(1, T1);
4549 ICS.Standard.setToType(2, T1);
4550 ICS.Standard.ReferenceBinding = true;
4551 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004552 ICS.Standard.IsLvalueReference = !isRValRef;
4553 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4554 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004555 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004556 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004557 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004558 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004559
Sebastian Redld92badf2010-06-30 18:13:39 +00004560 // Nothing more to do: the inaccessibility/ambiguity check for
4561 // derived-to-base conversions is suppressed when we're
4562 // computing the implicit conversion sequence (C++
4563 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004564 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004565 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004566
Sebastian Redld92badf2010-06-30 18:13:39 +00004567 // -- has a class type (i.e., T2 is a class type), where T1 is
4568 // not reference-related to T2, and can be implicitly
4569 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4570 // is reference-compatible with "cv3 T3" 92) (this
4571 // conversion is selected by enumerating the applicable
4572 // conversion functions (13.3.1.6) and choosing the best
4573 // one through overload resolution (13.3)),
4574 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004575 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004576 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4578 Init, T2, /*AllowRvalues=*/false,
4579 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004580 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004581 }
4582 }
4583
Sebastian Redld92badf2010-06-30 18:13:39 +00004584 // -- Otherwise, the reference shall be an lvalue reference to a
4585 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004586 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004588 return ICS;
4589
Douglas Gregorf143cd52011-01-24 16:14:37 +00004590 // -- If the initializer expression
4591 //
4592 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004593 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004594 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004595 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004596 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4597 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004598 ICS.setStandard();
4599 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004601 : ObjCConversion? ICK_Compatible_Conversion
4602 : ICK_Identity;
4603 ICS.Standard.Third = ICK_Identity;
4604 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4605 ICS.Standard.setToType(0, T2);
4606 ICS.Standard.setToType(1, T1);
4607 ICS.Standard.setToType(2, T1);
4608 ICS.Standard.ReferenceBinding = true;
4609 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4610 // binding unless we're binding to a class prvalue.
4611 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4612 // allow the use of rvalue references in C++98/03 for the benefit of
4613 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004615 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004616 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004617 ICS.Standard.IsLvalueReference = !isRValRef;
4618 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004620 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004621 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004622 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004623 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Douglas Gregorf143cd52011-01-24 16:14:37 +00004627 // -- has a class type (i.e., T2 is a class type), where T1 is not
4628 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629 // an xvalue, class prvalue, or function lvalue of type
4630 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004631 // "cv3 T3",
4632 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004634 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004636 // class subobject).
4637 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004638 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004639 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4640 Init, T2, /*AllowRvalues=*/true,
4641 AllowExplicit)) {
4642 // In the second case, if the reference is an rvalue reference
4643 // and the second standard conversion sequence of the
4644 // user-defined conversion sequence includes an lvalue-to-rvalue
4645 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004647 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4648 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4649
Douglas Gregor95273c32011-01-21 16:36:05 +00004650 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652
Richard Smith19172c42014-07-14 02:28:44 +00004653 // A temporary of function type cannot be created; don't even try.
4654 if (T1->isFunctionType())
4655 return ICS;
4656
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004657 // -- Otherwise, a temporary of type "cv1 T1" is created and
4658 // initialized from the initializer expression using the
4659 // rules for a non-reference copy initialization (8.5). The
4660 // reference is then bound to the temporary. If T1 is
4661 // reference-related to T2, cv1 must be the same
4662 // cv-qualification as, or greater cv-qualification than,
4663 // cv2; otherwise, the program is ill-formed.
4664 if (RefRelationship == Sema::Ref_Related) {
4665 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4666 // we would be reference-compatible or reference-compatible with
4667 // added qualification. But that wasn't the case, so the reference
4668 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004669 //
4670 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004671 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004672 Qualifiers T1Quals = T1.getQualifiers();
4673 Qualifiers T2Quals = T2.getQualifiers();
4674 T1Quals.removeObjCGCAttr();
4675 T1Quals.removeObjCLifetime();
4676 T2Quals.removeObjCGCAttr();
4677 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004678 // MS compiler ignores __unaligned qualifier for references; do the same.
4679 T1Quals.removeUnaligned();
4680 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004681 if (!T1Quals.compatiblyIncludes(T2Quals))
4682 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004683 }
4684
4685 // If at least one of the types is a class type, the types are not
4686 // related, and we aren't allowed any user conversions, the
4687 // reference binding fails. This case is important for breaking
4688 // recursion, since TryImplicitConversion below will attempt to
4689 // create a temporary through the use of a copy constructor.
4690 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4691 (T1->isRecordType() || T2->isRecordType()))
4692 return ICS;
4693
Douglas Gregorcba72b12011-01-21 05:18:22 +00004694 // If T1 is reference-related to T2 and the reference is an rvalue
4695 // reference, the initializer expression shall not be an lvalue.
4696 if (RefRelationship >= Sema::Ref_Related &&
4697 isRValRef && Init->Classify(S.Context).isLValue())
4698 return ICS;
4699
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004700 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004701 // When a parameter of reference type is not bound directly to
4702 // an argument expression, the conversion sequence is the one
4703 // required to convert the argument expression to the
4704 // underlying type of the reference according to
4705 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4706 // to copy-initializing a temporary of the underlying type with
4707 // the argument expression. Any difference in top-level
4708 // cv-qualification is subsumed by the initialization itself
4709 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004710 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4711 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004712 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004713 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004714 /*AllowObjCWritebackConversion=*/false,
4715 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004716
4717 // Of course, that's still a reference binding.
4718 if (ICS.isStandard()) {
4719 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004720 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004721 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004722 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004723 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004724 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004725 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004726 const ReferenceType *LValRefType =
4727 ICS.UserDefined.ConversionFunction->getReturnType()
4728 ->getAs<LValueReferenceType>();
4729
4730 // C++ [over.ics.ref]p3:
4731 // Except for an implicit object parameter, for which see 13.3.1, a
4732 // standard conversion sequence cannot be formed if it requires [...]
4733 // binding an rvalue reference to an lvalue other than a function
4734 // lvalue.
4735 // Note that the function case is not possible here.
4736 if (DeclType->isRValueReferenceType() && LValRefType) {
4737 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4738 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4739 // reference to an rvalue!
4740 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4741 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004742 }
Richard Smith19172c42014-07-14 02:28:44 +00004743
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004744 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004745 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004746 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4747 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004748 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4749 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004750 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004751
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004752 return ICS;
4753}
4754
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004755static ImplicitConversionSequence
4756TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4757 bool SuppressUserConversions,
4758 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004759 bool AllowObjCWritebackConversion,
4760 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004761
4762/// TryListConversion - Try to copy-initialize a value of type ToType from the
4763/// initializer list From.
4764static ImplicitConversionSequence
4765TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4766 bool SuppressUserConversions,
4767 bool InOverloadResolution,
4768 bool AllowObjCWritebackConversion) {
4769 // C++11 [over.ics.list]p1:
4770 // When an argument is an initializer list, it is not an expression and
4771 // special rules apply for converting it to a parameter type.
4772
4773 ImplicitConversionSequence Result;
4774 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4775
Sebastian Redl09edce02012-01-23 22:09:39 +00004776 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004777 // initialized from init lists.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004778 if (!S.isCompleteType(From->getBeginLoc(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004779 return Result;
4780
Larisse Voufo19d08672015-01-27 18:47:05 +00004781 // Per DR1467:
4782 // If the parameter type is a class X and the initializer list has a single
4783 // element of type cv U, where U is X or a class derived from X, the
4784 // implicit conversion sequence is the one required to convert the element
4785 // to the parameter type.
4786 //
4787 // Otherwise, if the parameter type is a character array [... ]
4788 // and the initializer list has a single element that is an
4789 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4790 // implicit conversion sequence is the identity conversion.
4791 if (From->getNumInits() == 1) {
4792 if (ToType->isRecordType()) {
4793 QualType InitType = From->getInit(0)->getType();
4794 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004795 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004796 return TryCopyInitialization(S, From->getInit(0), ToType,
4797 SuppressUserConversions,
4798 InOverloadResolution,
4799 AllowObjCWritebackConversion);
4800 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004801 // FIXME: Check the other conditions here: array of character type,
4802 // initializer is a string literal.
4803 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004804 InitializedEntity Entity =
4805 InitializedEntity::InitializeParameter(S.Context, ToType,
4806 /*Consumed=*/false);
4807 if (S.CanPerformCopyInitialization(Entity, From)) {
4808 Result.setStandard();
4809 Result.Standard.setAsIdentityConversion();
4810 Result.Standard.setFromType(ToType);
4811 Result.Standard.setAllToTypes(ToType);
4812 return Result;
4813 }
4814 }
4815 }
4816
4817 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004818 // C++11 [over.ics.list]p2:
4819 // If the parameter type is std::initializer_list<X> or "array of X" and
4820 // all the elements can be implicitly converted to X, the implicit
4821 // conversion sequence is the worst conversion necessary to convert an
4822 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004823 //
4824 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004825 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004826 // list has exactly N elements or if it has fewer than N elements and X is
4827 // default-constructible, and if all the elements of the initializer list
4828 // can be implicitly converted to X, the implicit conversion sequence is
4829 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004830 //
4831 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004832 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004833 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004834 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004835 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004836 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004837 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004838 if (!X.isNull()) {
4839 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4840 Expr *Init = From->getInit(i);
4841 ImplicitConversionSequence ICS =
4842 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4843 InOverloadResolution,
4844 AllowObjCWritebackConversion);
4845 // If a single element isn't convertible, fail.
4846 if (ICS.isBad()) {
4847 Result = ICS;
4848 break;
4849 }
4850 // Otherwise, look for the worst conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004851 if (Result.isBad() || CompareImplicitConversionSequences(
4852 S, From->getBeginLoc(), ICS, Result) ==
4853 ImplicitConversionSequence::Worse)
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004854 Result = ICS;
4855 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004856
4857 // For an empty list, we won't have computed any conversion sequence.
4858 // Introduce the identity conversion sequence.
4859 if (From->getNumInits() == 0) {
4860 Result.setStandard();
4861 Result.Standard.setAsIdentityConversion();
4862 Result.Standard.setFromType(ToType);
4863 Result.Standard.setAllToTypes(ToType);
4864 }
4865
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004866 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004867 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004868 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004869
Larisse Voufo19d08672015-01-27 18:47:05 +00004870 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004871 // C++11 [over.ics.list]p3:
4872 // Otherwise, if the parameter is a non-aggregate class X and overload
4873 // resolution chooses a single best constructor [...] the implicit
4874 // conversion sequence is a user-defined conversion sequence. If multiple
4875 // constructors are viable but none is better than the others, the
4876 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004877 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4878 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004879 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4880 /*AllowExplicit=*/false,
4881 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004882 AllowObjCWritebackConversion,
4883 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004884 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004885
Larisse Voufo19d08672015-01-27 18:47:05 +00004886 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004887 // C++11 [over.ics.list]p4:
4888 // Otherwise, if the parameter has an aggregate type which can be
4889 // initialized from the initializer list [...] the implicit conversion
4890 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004891 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004892 // Type is an aggregate, argument is an init list. At this point it comes
4893 // down to checking whether the initialization works.
4894 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004895 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4896 // need to call into the initialization code here; overload resolution
4897 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004898 InitializedEntity Entity =
4899 InitializedEntity::InitializeParameter(S.Context, ToType,
4900 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004901 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004902 Result.setUserDefined();
4903 Result.UserDefined.Before.setAsIdentityConversion();
4904 // Initializer lists don't have a type.
4905 Result.UserDefined.Before.setFromType(QualType());
4906 Result.UserDefined.Before.setAllToTypes(QualType());
4907
4908 Result.UserDefined.After.setAsIdentityConversion();
4909 Result.UserDefined.After.setFromType(ToType);
4910 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004911 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004912 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004913 return Result;
4914 }
4915
Larisse Voufo19d08672015-01-27 18:47:05 +00004916 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004917 // C++11 [over.ics.list]p5:
4918 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004919 if (ToType->isReferenceType()) {
4920 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4921 // mention initializer lists in any way. So we go by what list-
4922 // initialization would do and try to extrapolate from that.
4923
4924 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4925
4926 // If the initializer list has a single element that is reference-related
4927 // to the parameter type, we initialize the reference from that.
4928 if (From->getNumInits() == 1) {
4929 Expr *Init = From->getInit(0);
4930
4931 QualType T2 = Init->getType();
4932
4933 // If the initializer is the address of an overloaded function, try
4934 // to resolve the overloaded function. If all goes well, T2 is the
4935 // type of the resulting function.
4936 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4937 DeclAccessPair Found;
4938 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4939 Init, ToType, false, Found))
4940 T2 = Fn->getType();
4941 }
4942
4943 // Compute some basic properties of the types and the initializer.
4944 bool dummy1 = false;
4945 bool dummy2 = false;
4946 bool dummy3 = false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004947 Sema::ReferenceCompareResult RefRelationship =
4948 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
Sebastian Redldf888642011-12-03 14:54:30 +00004949 dummy2, dummy3);
4950
Richard Smith4d2bbd72013-09-06 01:22:42 +00004951 if (RefRelationship >= Sema::Ref_Related) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004952 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
Richard Smitha93f1022013-09-06 22:30:28 +00004953 SuppressUserConversions,
4954 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004955 }
Sebastian Redldf888642011-12-03 14:54:30 +00004956 }
4957
4958 // Otherwise, we bind the reference to a temporary created from the
4959 // initializer list.
4960 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4961 InOverloadResolution,
4962 AllowObjCWritebackConversion);
4963 if (Result.isFailure())
4964 return Result;
4965 assert(!Result.isEllipsis() &&
4966 "Sub-initialization cannot result in ellipsis conversion.");
4967
4968 // Can we even bind to a temporary?
4969 if (ToType->isRValueReferenceType() ||
4970 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4971 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4972 Result.UserDefined.After;
4973 SCS.ReferenceBinding = true;
4974 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4975 SCS.BindsToRvalue = true;
4976 SCS.BindsToFunctionLvalue = false;
4977 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4978 SCS.ObjCLifetimeConversionBinding = false;
4979 } else
4980 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4981 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004982 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004983 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004984
Larisse Voufo19d08672015-01-27 18:47:05 +00004985 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004986 // C++11 [over.ics.list]p6:
4987 // Otherwise, if the parameter type is not a class:
4988 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004989 // - if the initializer list has one element that is not itself an
4990 // initializer list, the implicit conversion sequence is the one
4991 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004992 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004993 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004994 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4995 SuppressUserConversions,
4996 InOverloadResolution,
4997 AllowObjCWritebackConversion);
4998 // - if the initializer list has no elements, the implicit conversion
4999 // sequence is the identity conversion.
5000 else if (NumInits == 0) {
5001 Result.setStandard();
5002 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00005003 Result.Standard.setFromType(ToType);
5004 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00005005 }
5006 return Result;
5007 }
5008
Larisse Voufo19d08672015-01-27 18:47:05 +00005009 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00005010 // C++11 [over.ics.list]p7:
5011 // In all cases other than those enumerated above, no conversion is possible
5012 return Result;
5013}
5014
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005015/// TryCopyInitialization - Try to copy-initialize a value of type
5016/// ToType from the expression From. Return the implicit conversion
5017/// sequence required to pass this argument, which may be a bad
5018/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00005019/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00005020/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005021static ImplicitConversionSequence
5022TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005024 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005025 bool AllowObjCWritebackConversion,
5026 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00005027 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5028 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5029 InOverloadResolution,AllowObjCWritebackConversion);
5030
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005031 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005032 return TryReferenceInit(S, From, ToType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005033 /*FIXME:*/ From->getBeginLoc(),
5034 SuppressUserConversions, AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005035
John McCall5c32be02010-08-24 20:38:10 +00005036 return TryImplicitConversion(S, From, ToType,
5037 SuppressUserConversions,
5038 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00005039 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00005040 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005041 AllowObjCWritebackConversion,
5042 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005043}
5044
Anna Zaks1b068122011-07-28 19:46:48 +00005045static bool TryCopyInitialization(const CanQualType FromQTy,
5046 const CanQualType ToQTy,
5047 Sema &S,
5048 SourceLocation Loc,
5049 ExprValueKind FromVK) {
5050 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5051 ImplicitConversionSequence ICS =
5052 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5053
5054 return !ICS.isBad();
5055}
5056
Douglas Gregor436424c2008-11-18 23:14:02 +00005057/// TryObjectArgumentInitialization - Try to initialize the object
5058/// parameter of the given member function (@c Method) from the
5059/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005060static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005061TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005062 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005063 CXXMethodDecl *Method,
5064 CXXRecordDecl *ActingContext) {
5065 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005066 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5067 // const volatile object.
5068 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5069 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005070 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005071
5072 // Set up the conversion sequence as a "bad" conversion, to allow us
5073 // to exit early.
5074 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005075
5076 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005077 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005078 FromType = PT->getPointeeType();
5079
Douglas Gregor02824322011-01-26 19:30:28 +00005080 // When we had a pointer, it's implicitly dereferenced, so we
5081 // better have an lvalue.
5082 assert(FromClassification.isLValue());
5083 }
5084
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005085 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005086
Douglas Gregor02824322011-01-26 19:30:28 +00005087 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005089 // parameter is
5090 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005091 // - "lvalue reference to cv X" for functions declared without a
5092 // ref-qualifier or with the & ref-qualifier
5093 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005094 // ref-qualifier
5095 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005097 // cv-qualification on the member function declaration.
5098 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005100 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005101 // (C++ [over.match.funcs]p5). We perform a simplified version of
5102 // reference binding here, that allows class rvalues to bind to
5103 // non-constant references.
5104
Douglas Gregor02824322011-01-26 19:30:28 +00005105 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005106 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005108 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005109 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005110 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005111 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005112 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005113 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005114
5115 // Check that we have either the same type or a derived type. It
5116 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005117 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005118 ImplicitConversionKind SecondKind;
5119 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5120 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005121 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005122 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005123 else {
John McCall65eb8792010-02-25 01:37:24 +00005124 ICS.setBad(BadConversionSequence::unrelated_class,
5125 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005126 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005127 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005128
Douglas Gregor02824322011-01-26 19:30:28 +00005129 // Check the ref-qualifier.
5130 switch (Method->getRefQualifier()) {
5131 case RQ_None:
5132 // Do nothing; we don't care about lvalueness or rvalueness.
5133 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134
Douglas Gregor02824322011-01-26 19:30:28 +00005135 case RQ_LValue:
5136 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5137 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005139 ImplicitParamType);
5140 return ICS;
5141 }
5142 break;
5143
5144 case RQ_RValue:
5145 if (!FromClassification.isRValue()) {
5146 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005148 ImplicitParamType);
5149 return ICS;
5150 }
5151 break;
5152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153
Douglas Gregor436424c2008-11-18 23:14:02 +00005154 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005155 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005156 ICS.Standard.setAsIdentityConversion();
5157 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005158 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005159 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005160 ICS.Standard.ReferenceBinding = true;
5161 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005163 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005164 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5165 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5166 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005167 return ICS;
5168}
5169
5170/// PerformObjectArgumentInitialization - Perform initialization of
5171/// the implicit object parameter for the given Method with the given
5172/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005173ExprResult
5174Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005176 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005177 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005178 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005179 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005180 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005181
Douglas Gregor02824322011-01-26 19:30:28 +00005182 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005183 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005184 FromRecordType = PT->getPointeeType();
5185 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005186 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005187 } else {
5188 FromRecordType = From->getType();
5189 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005190 FromClassification = From->Classify(Context);
Richard Smith7ed5fb22018-07-27 17:13:18 +00005191
5192 // When performing member access on an rvalue, materialize a temporary.
5193 if (From->isRValue()) {
5194 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5195 Method->getRefQualifier() !=
5196 RefQualifierKind::RQ_RValue);
5197 }
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005198 }
5199
John McCall6e9f8f62009-12-03 04:06:58 +00005200 // Note that we always use the true parent context when performing
5201 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005202 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005203 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
Richard Smith0f59cb32015-12-18 21:45:41 +00005204 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005205 if (ICS.isBad()) {
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005206 switch (ICS.Bad.Kind) {
5207 case BadConversionSequence::bad_qualifiers: {
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005208 Qualifiers FromQs = FromRecordType.getQualifiers();
5209 Qualifiers ToQs = DestType.getQualifiers();
5210 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5211 if (CVR) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005212 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5213 << Method->getDeclName() << FromRecordType << (CVR - 1)
5214 << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005215 Diag(Method->getLocation(), diag::note_previous_decl)
5216 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005217 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005218 }
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005219 break;
5220 }
5221
5222 case BadConversionSequence::lvalue_ref_to_rvalue:
5223 case BadConversionSequence::rvalue_ref_to_lvalue: {
5224 bool IsRValueQualified =
5225 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005226 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5227 << Method->getDeclName() << FromClassification.isRValue()
5228 << IsRValueQualified;
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005229 Diag(Method->getLocation(), diag::note_previous_decl)
5230 << Method->getDeclName();
5231 return ExprError();
5232 }
5233
5234 case BadConversionSequence::no_conversion:
5235 case BadConversionSequence::unrelated_class:
5236 break;
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005237 }
5238
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005239 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5240 << ImplicitParamRecordType << FromRecordType
5241 << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
John Wiegley01296292011-04-08 18:41:53 +00005244 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5245 ExprResult FromRes =
5246 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5247 if (FromRes.isInvalid())
5248 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005249 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005250 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005251
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005252 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005253 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005254 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005255 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005256}
5257
Douglas Gregor5fb53972009-01-14 15:45:31 +00005258/// TryContextuallyConvertToBool - Attempt to contextually convert the
5259/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005260static ImplicitConversionSequence
5261TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005262 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005263 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005264 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005265 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005266 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005267 /*AllowObjCWritebackConversion=*/false,
5268 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005269}
5270
5271/// PerformContextuallyConvertToBool - Perform a contextual conversion
5272/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005273ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005274 if (checkPlaceholderForOverload(*this, From))
5275 return ExprError();
5276
John McCall5c32be02010-08-24 20:38:10 +00005277 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005278 if (!ICS.isBad())
5279 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005280
Fariborz Jahanian76197412009-11-18 18:26:29 +00005281 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005282 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5283 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005284 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005285}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005286
Richard Smithf8379a02012-01-18 23:55:52 +00005287/// Check that the specified conversion is permitted in a converted constant
5288/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5289/// is acceptable.
5290static bool CheckConvertedConstantConversions(Sema &S,
5291 StandardConversionSequence &SCS) {
5292 // Since we know that the target type is an integral or unscoped enumeration
5293 // type, most conversion kinds are impossible. All possible First and Third
5294 // conversions are fine.
5295 switch (SCS.Second) {
5296 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005297 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005298 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005299 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005300 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005301 return true;
5302
5303 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005304 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005305 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5306 // conversion, so we allow it in a converted constant expression.
5307 //
5308 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5309 // a lot of popular code. We should at least add a warning for this
5310 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005311 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5312 SCS.getToType(2)->isBooleanType();
5313
Richard Smith410cc892014-11-26 03:26:53 +00005314 case ICK_Pointer_Conversion:
5315 case ICK_Pointer_Member:
5316 // C++1z: null pointer conversions and null member pointer conversions are
5317 // only permitted if the source type is std::nullptr_t.
5318 return SCS.getFromType()->isNullPtrType();
5319
5320 case ICK_Floating_Promotion:
5321 case ICK_Complex_Promotion:
5322 case ICK_Floating_Conversion:
5323 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005324 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005325 case ICK_Compatible_Conversion:
5326 case ICK_Derived_To_Base:
5327 case ICK_Vector_Conversion:
5328 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005329 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005330 case ICK_Block_Pointer_Conversion:
5331 case ICK_TransparentUnionConversion:
5332 case ICK_Writeback_Conversion:
5333 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005334 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005335 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005336 return false;
5337
5338 case ICK_Lvalue_To_Rvalue:
5339 case ICK_Array_To_Pointer:
5340 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005341 llvm_unreachable("found a first conversion kind in Second");
5342
Richard Smithf8379a02012-01-18 23:55:52 +00005343 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005344 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005345
5346 case ICK_Num_Conversion_Kinds:
5347 break;
5348 }
5349
5350 llvm_unreachable("unknown conversion kind");
5351}
5352
5353/// CheckConvertedConstantExpression - Check that the expression From is a
5354/// converted constant expression of type T, perform the conversion and produce
5355/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005356static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5357 QualType T, APValue &Value,
5358 Sema::CCEKind CCE,
5359 bool RequireInt) {
5360 assert(S.getLangOpts().CPlusPlus11 &&
5361 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005362
Richard Smith410cc892014-11-26 03:26:53 +00005363 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005364 return ExprError();
5365
Richard Smith410cc892014-11-26 03:26:53 +00005366 // C++1z [expr.const]p3:
5367 // A converted constant expression of type T is an expression,
5368 // implicitly converted to type T, where the converted
5369 // expression is a constant expression and the implicit conversion
5370 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005371 // C++1z [stmt.if]p2:
5372 // If the if statement is of the form if constexpr, the value of the
5373 // condition shall be a contextually converted constant expression of type
5374 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005375 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005376 CCE == Sema::CCEK_ConstexprIf
5377 ? TryContextuallyConvertToBool(S, From)
5378 : TryCopyInitialization(S, From, T,
5379 /*SuppressUserConversions=*/false,
5380 /*InOverloadResolution=*/false,
5381 /*AllowObjcWritebackConversion=*/false,
5382 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005383 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005384 switch (ICS.getKind()) {
5385 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005386 SCS = &ICS.Standard;
5387 break;
5388 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005389 // We are converting to a non-class type, so the Before sequence
5390 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005391 SCS = &ICS.UserDefined.After;
5392 break;
5393 case ImplicitConversionSequence::AmbiguousConversion:
5394 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005395 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005396 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005397 diag::err_typecheck_converted_constant_expression)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005398 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005399 return ExprError();
5400
5401 case ImplicitConversionSequence::EllipsisConversion:
5402 llvm_unreachable("ellipsis conversion in converted constant expression");
5403 }
5404
Richard Smith410cc892014-11-26 03:26:53 +00005405 // Check that we would only use permitted conversions.
5406 if (!CheckConvertedConstantConversions(S, *SCS)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005407 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005408 diag::err_typecheck_converted_constant_expression_disallowed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005409 << From->getType() << From->getSourceRange() << T;
Richard Smith410cc892014-11-26 03:26:53 +00005410 }
5411 // [...] and where the reference binding (if any) binds directly.
5412 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005413 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005414 diag::err_typecheck_converted_constant_expression_indirect)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005415 << From->getType() << From->getSourceRange() << T;
Richard Smith410cc892014-11-26 03:26:53 +00005416 }
5417
5418 ExprResult Result =
5419 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005420 if (Result.isInvalid())
5421 return Result;
5422
5423 // Check for a narrowing implicit conversion.
5424 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005425 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005426 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005427 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005428 case NK_Dependent_Narrowing:
5429 // Implicit conversion to a narrower type, but the expression is
5430 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005431 case NK_Variable_Narrowing:
5432 // Implicit conversion to a narrower type, and the value is not a constant
5433 // expression. We'll diagnose this in a moment.
5434 case NK_Not_Narrowing:
5435 break;
5436
5437 case NK_Constant_Narrowing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005438 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5439 << CCE << /*Constant*/ 1
5440 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005441 break;
5442
5443 case NK_Type_Narrowing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005444 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5445 << CCE << /*Constant*/ 0 << From->getType() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005446 break;
5447 }
5448
Richard Smith52e624f2016-12-21 21:42:57 +00005449 if (Result.get()->isValueDependent()) {
5450 Value = APValue();
5451 return Result;
5452 }
5453
Richard Smithf8379a02012-01-18 23:55:52 +00005454 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005455 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005456 Expr::EvalResult Eval;
5457 Eval.Diag = &Notes;
Reid Kleckner1a840d22018-05-10 18:57:35 +00005458 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5459 ? Expr::EvaluateForMangling
5460 : Expr::EvaluateForCodeGen;
Richard Smithf8379a02012-01-18 23:55:52 +00005461
Reid Kleckner1a840d22018-05-10 18:57:35 +00005462 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
Richard Smith410cc892014-11-26 03:26:53 +00005463 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005464 // The expression can't be folded, so we can't keep it at this position in
5465 // the AST.
5466 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005467 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005468 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005469
5470 if (Notes.empty()) {
5471 // It's a constant expression.
Bill Wendling91549ed2018-11-20 23:24:16 +00005472 return ConstantExpr::Create(S.Context, Result.get());
Richard Smith911e1422012-01-30 22:27:01 +00005473 }
Richard Smithf8379a02012-01-18 23:55:52 +00005474 }
5475
5476 // It's not a constant expression. Produce an appropriate diagnostic.
5477 if (Notes.size() == 1 &&
5478 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005479 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005480 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005481 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5482 << CCE << From->getSourceRange();
Richard Smithf8379a02012-01-18 23:55:52 +00005483 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005484 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005485 }
Richard Smith410cc892014-11-26 03:26:53 +00005486 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005487}
5488
Richard Smith410cc892014-11-26 03:26:53 +00005489ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5490 APValue &Value, CCEKind CCE) {
5491 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5492}
5493
5494ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5495 llvm::APSInt &Value,
5496 CCEKind CCE) {
5497 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5498
5499 APValue V;
5500 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005501 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005502 Value = V.getInt();
5503 return R;
5504}
5505
5506
John McCallfec112d2011-09-09 06:11:02 +00005507/// dropPointerConversions - If the given standard conversion sequence
5508/// involves any pointer conversions, remove them. This may change
5509/// the result type of the conversion sequence.
5510static void dropPointerConversion(StandardConversionSequence &SCS) {
5511 if (SCS.Second == ICK_Pointer_Conversion) {
5512 SCS.Second = ICK_Identity;
5513 SCS.Third = ICK_Identity;
5514 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5515 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005516}
John McCall5c32be02010-08-24 20:38:10 +00005517
John McCallfec112d2011-09-09 06:11:02 +00005518/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5519/// convert the expression From to an Objective-C pointer type.
5520static ImplicitConversionSequence
5521TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5522 // Do an implicit conversion to 'id'.
5523 QualType Ty = S.Context.getObjCIdType();
5524 ImplicitConversionSequence ICS
5525 = TryImplicitConversion(S, From, Ty,
5526 // FIXME: Are these flags correct?
5527 /*SuppressUserConversions=*/false,
5528 /*AllowExplicit=*/true,
5529 /*InOverloadResolution=*/false,
5530 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005531 /*AllowObjCWritebackConversion=*/false,
5532 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005533
5534 // Strip off any final conversions to 'id'.
5535 switch (ICS.getKind()) {
5536 case ImplicitConversionSequence::BadConversion:
5537 case ImplicitConversionSequence::AmbiguousConversion:
5538 case ImplicitConversionSequence::EllipsisConversion:
5539 break;
5540
5541 case ImplicitConversionSequence::UserDefinedConversion:
5542 dropPointerConversion(ICS.UserDefined.After);
5543 break;
5544
5545 case ImplicitConversionSequence::StandardConversion:
5546 dropPointerConversion(ICS.Standard);
5547 break;
5548 }
5549
5550 return ICS;
5551}
5552
5553/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5554/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005555/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005556ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005557 if (checkPlaceholderForOverload(*this, From))
5558 return ExprError();
5559
John McCall8b07ec22010-05-15 11:32:37 +00005560 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005561 ImplicitConversionSequence ICS =
5562 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005563 if (!ICS.isBad())
5564 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005565 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005566}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005567
Richard Smith8dd34252012-02-04 07:07:42 +00005568/// Determine whether the provided type is an integral type, or an enumeration
5569/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005570bool Sema::ICEConvertDiagnoser::match(QualType T) {
5571 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5572 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005573}
5574
Larisse Voufo236bec22013-06-10 06:50:24 +00005575static ExprResult
5576diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5577 Sema::ContextualImplicitConverter &Converter,
5578 QualType T, UnresolvedSetImpl &ViableConversions) {
5579
5580 if (Converter.Suppress)
5581 return ExprError();
5582
5583 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5584 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5585 CXXConversionDecl *Conv =
5586 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5587 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5588 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5589 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005590 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005591}
5592
5593static bool
5594diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5595 Sema::ContextualImplicitConverter &Converter,
5596 QualType T, bool HadMultipleCandidates,
5597 UnresolvedSetImpl &ExplicitConversions) {
5598 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5599 DeclAccessPair Found = ExplicitConversions[0];
5600 CXXConversionDecl *Conversion =
5601 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5602
5603 // The user probably meant to invoke the given explicit
5604 // conversion; use it.
5605 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5606 std::string TypeStr;
5607 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5608
5609 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005610 << FixItHint::CreateInsertion(From->getBeginLoc(),
Larisse Voufo236bec22013-06-10 06:50:24 +00005611 "static_cast<" + TypeStr + ">(")
5612 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005613 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005614 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5615
5616 // If we aren't in a SFINAE context, build a call to the
5617 // explicit conversion function.
5618 if (SemaRef.isSFINAEContext())
5619 return true;
5620
Craig Topperc3ec1492014-05-26 06:22:03 +00005621 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005622 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5623 HadMultipleCandidates);
5624 if (Result.isInvalid())
5625 return true;
5626 // Record usage of conversion in an implicit cast.
5627 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005628 CK_UserDefinedConversion, Result.get(),
5629 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005630 }
5631 return false;
5632}
5633
5634static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5635 Sema::ContextualImplicitConverter &Converter,
5636 QualType T, bool HadMultipleCandidates,
5637 DeclAccessPair &Found) {
5638 CXXConversionDecl *Conversion =
5639 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005640 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005641
5642 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5643 if (!Converter.SuppressConversion) {
5644 if (SemaRef.isSFINAEContext())
5645 return true;
5646
5647 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5648 << From->getSourceRange();
5649 }
5650
5651 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5652 HadMultipleCandidates);
5653 if (Result.isInvalid())
5654 return true;
5655 // Record usage of conversion in an implicit cast.
5656 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005657 CK_UserDefinedConversion, Result.get(),
5658 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005659 return false;
5660}
5661
5662static ExprResult finishContextualImplicitConversion(
5663 Sema &SemaRef, SourceLocation Loc, Expr *From,
5664 Sema::ContextualImplicitConverter &Converter) {
5665 if (!Converter.match(From->getType()) && !Converter.Suppress)
5666 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5667 << From->getSourceRange();
5668
5669 return SemaRef.DefaultLvalueConversion(From);
5670}
5671
5672static void
5673collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5674 UnresolvedSetImpl &ViableConversions,
5675 OverloadCandidateSet &CandidateSet) {
5676 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5677 DeclAccessPair FoundDecl = ViableConversions[I];
5678 NamedDecl *D = FoundDecl.getDecl();
5679 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5680 if (isa<UsingShadowDecl>(D))
5681 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5682
5683 CXXConversionDecl *Conv;
5684 FunctionTemplateDecl *ConvTemplate;
5685 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5686 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5687 else
5688 Conv = cast<CXXConversionDecl>(D);
5689
5690 if (ConvTemplate)
5691 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005692 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5693 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005694 else
5695 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005696 ToType, CandidateSet,
5697 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005698 }
5699}
5700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005701/// Attempt to convert the given expression to a type which is accepted
Richard Smithccc11812013-05-21 19:05:48 +00005702/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005703///
Richard Smithccc11812013-05-21 19:05:48 +00005704/// This routine will attempt to convert an expression of class type to a
5705/// type accepted by the specified converter. In C++11 and before, the class
5706/// must have a single non-explicit conversion function converting to a matching
5707/// type. In C++1y, there can be multiple such conversion functions, but only
5708/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709///
Douglas Gregor4799d032010-06-30 00:20:43 +00005710/// \param Loc The source location of the construct that requires the
5711/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005712///
James Dennett18348b62012-06-22 08:52:37 +00005713/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005714///
Richard Smithccc11812013-05-21 19:05:48 +00005715/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005716///
Douglas Gregor4799d032010-06-30 00:20:43 +00005717/// \returns The expression, converted to an integral or enumeration type if
5718/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005719ExprResult Sema::PerformContextualImplicitConversion(
5720 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005721 // We can't perform any more checking for type-dependent expressions.
5722 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005723 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Eli Friedman1da70392012-01-26 00:26:18 +00005725 // Process placeholders immediately.
5726 if (From->hasPlaceholderType()) {
5727 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005728 if (result.isInvalid())
5729 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005730 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005731 }
5732
Richard Smithccc11812013-05-21 19:05:48 +00005733 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005734 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005735 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005736 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005737
5738 // FIXME: Check for missing '()' if T is a function type?
5739
Richard Smithccc11812013-05-21 19:05:48 +00005740 // We can only perform contextual implicit conversions on objects of class
5741 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005742 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005743 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005744 if (!Converter.Suppress)
5745 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005746 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005749 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005750 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005751 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005752 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005753
5754 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005755 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005756
Craig Toppere14c0f82014-03-12 04:55:44 +00005757 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005758 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005759 }
Richard Smithccc11812013-05-21 19:05:48 +00005760 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005761
Richard Smithdb0ac552015-12-18 22:40:25 +00005762 if (Converter.Suppress ? !isCompleteType(Loc, T)
5763 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005764 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005766 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005767 UnresolvedSet<4>
5768 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005769 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005770 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005771 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Larisse Voufo236bec22013-06-10 06:50:24 +00005773 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005774 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005775
Larisse Voufo236bec22013-06-10 06:50:24 +00005776 // To check that there is only one target type, in C++1y:
5777 QualType ToType;
5778 bool HasUniqueTargetType = true;
5779
5780 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005781 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005782 NamedDecl *D = (*I)->getUnderlyingDecl();
5783 CXXConversionDecl *Conversion;
5784 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5785 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005786 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005787 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5788 else
5789 continue; // C++11 does not consider conversion operator templates(?).
5790 } else
5791 Conversion = cast<CXXConversionDecl>(D);
5792
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005793 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005794 "Conversion operator templates are considered potentially "
5795 "viable in C++1y");
5796
5797 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5798 if (Converter.match(CurToType) || ConvTemplate) {
5799
5800 if (Conversion->isExplicit()) {
5801 // FIXME: For C++1y, do we need this restriction?
5802 // cf. diagnoseNoViableConversion()
5803 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005804 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005805 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005806 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005807 if (ToType.isNull())
5808 ToType = CurToType.getUnqualifiedType();
5809 else if (HasUniqueTargetType &&
5810 (CurToType.getUnqualifiedType() != ToType))
5811 HasUniqueTargetType = false;
5812 }
5813 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005814 }
Richard Smith8dd34252012-02-04 07:07:42 +00005815 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005817
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005818 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005819 // C++1y [conv]p6:
5820 // ... An expression e of class type E appearing in such a context
5821 // is said to be contextually implicitly converted to a specified
5822 // type T and is well-formed if and only if e can be implicitly
5823 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005824 // for conversion functions whose return type is cv T or reference to
5825 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005826 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
Larisse Voufo236bec22013-06-10 06:50:24 +00005828 // If no unique T is found:
5829 if (ToType.isNull()) {
5830 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5831 HadMultipleCandidates,
5832 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005833 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005834 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005836
Larisse Voufo236bec22013-06-10 06:50:24 +00005837 // If more than one unique Ts are found:
5838 if (!HasUniqueTargetType)
5839 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5840 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841
Larisse Voufo236bec22013-06-10 06:50:24 +00005842 // If one unique T is found:
5843 // First, build a candidate set from the previously recorded
5844 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005845 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005846 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5847 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Larisse Voufo236bec22013-06-10 06:50:24 +00005849 // Then, perform overload resolution over the candidate set.
5850 OverloadCandidateSet::iterator Best;
5851 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5852 case OR_Success: {
5853 // Apply this conversion.
5854 DeclAccessPair Found =
5855 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5856 if (recordConversion(*this, Loc, From, Converter, T,
5857 HadMultipleCandidates, Found))
5858 return ExprError();
5859 break;
5860 }
5861 case OR_Ambiguous:
5862 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5863 ViableConversions);
5864 case OR_No_Viable_Function:
5865 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5866 HadMultipleCandidates,
5867 ExplicitConversions))
5868 return ExprError();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005869 LLVM_FALLTHROUGH;
Larisse Voufo236bec22013-06-10 06:50:24 +00005870 case OR_Deleted:
5871 // We'll complain below about a non-integral condition type.
5872 break;
5873 }
5874 } else {
5875 switch (ViableConversions.size()) {
5876 case 0: {
5877 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5878 HadMultipleCandidates,
5879 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005880 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005881
Larisse Voufo236bec22013-06-10 06:50:24 +00005882 // We'll complain below about a non-integral condition type.
5883 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005884 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005885 case 1: {
5886 // Apply this conversion.
5887 DeclAccessPair Found = ViableConversions[0];
5888 if (recordConversion(*this, Loc, From, Converter, T,
5889 HadMultipleCandidates, Found))
5890 return ExprError();
5891 break;
5892 }
5893 default:
5894 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5895 ViableConversions);
5896 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898
Larisse Voufo236bec22013-06-10 06:50:24 +00005899 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005900}
5901
Richard Smith100b24a2014-04-17 01:52:14 +00005902/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5903/// an acceptable non-member overloaded operator for a call whose
5904/// arguments have types T1 (and, if non-empty, T2). This routine
5905/// implements the check in C++ [over.match.oper]p3b2 concerning
5906/// enumeration types.
5907static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5908 FunctionDecl *Fn,
5909 ArrayRef<Expr *> Args) {
5910 QualType T1 = Args[0]->getType();
5911 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5912
5913 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5914 return true;
5915
5916 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5917 return true;
5918
5919 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5920 if (Proto->getNumParams() < 1)
5921 return false;
5922
5923 if (T1->isEnumeralType()) {
5924 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5925 if (Context.hasSameUnqualifiedType(T1, ArgType))
5926 return true;
5927 }
5928
5929 if (Proto->getNumParams() < 2)
5930 return false;
5931
5932 if (!T2.isNull() && T2->isEnumeralType()) {
5933 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5934 if (Context.hasSameUnqualifiedType(T2, ArgType))
5935 return true;
5936 }
5937
5938 return false;
5939}
5940
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005941/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005942/// candidate functions, using the given function call arguments. If
5943/// @p SuppressUserConversions, then don't allow user-defined
5944/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005945///
James Dennett2a4d13c2012-06-15 07:13:21 +00005946/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005947/// based on an incomplete set of function arguments. This feature is used by
5948/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005949void
5950Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005951 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005952 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005953 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005954 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005955 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005956 bool AllowExplicit,
5957 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005958 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005959 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005960 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005961 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005962 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005963
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005964 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005965 if (!isa<CXXConstructorDecl>(Method)) {
5966 // If we get here, it's because we're calling a member function
5967 // that is named without a member access expression (e.g.,
5968 // "this->f") that was either written explicitly or created
5969 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005970 // function, e.g., X::f(). We use an empty type for the implied
5971 // object argument (C++ [over.call.func]p3), and the acting context
5972 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005973 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005974 Expr::Classification::makeSimpleLValue(), Args,
5975 CandidateSet, SuppressUserConversions,
5976 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005977 return;
5978 }
5979 // We treat a constructor like a non-member function, since its object
5980 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005981 }
5982
Douglas Gregorff7028a2009-11-13 23:59:09 +00005983 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005984 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005985
Richard Smith100b24a2014-04-17 01:52:14 +00005986 // C++ [over.match.oper]p3:
5987 // if no operand has a class type, only those non-member functions in the
5988 // lookup set that have a first parameter of type T1 or "reference to
5989 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5990 // is a right operand) a second parameter of type T2 or "reference to
5991 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5992 // candidate functions.
5993 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5994 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5995 return;
5996
Richard Smith8b86f2d2013-11-04 01:48:18 +00005997 // C++11 [class.copy]p11: [DR1402]
5998 // A defaulted move constructor that is defined as deleted is ignored by
5999 // overload resolution.
6000 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6001 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6002 Constructor->isMoveConstructor())
6003 return;
6004
Douglas Gregor27381f32009-11-23 12:27:39 +00006005 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006006 EnterExpressionEvaluationContext Unevaluated(
6007 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006008
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006009 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006010 OverloadCandidate &Candidate =
6011 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006012 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006013 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006014 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006015 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006016 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006017 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
Erich Keane3efe0022018-07-20 14:13:28 +00006019 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00006020 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6021 Candidate.Viable = false;
6022 Candidate.FailureKind = ovl_non_default_multiversion_function;
6023 return;
6024 }
6025
John McCall578a1f82014-12-14 01:46:53 +00006026 if (Constructor) {
6027 // C++ [class.copy]p3:
6028 // A member function template is never instantiated to perform the copy
6029 // of a class object to an object of its class type.
6030 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00006031 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00006032 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006033 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
Richard Smith0f59cb32015-12-18 21:45:41 +00006034 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00006035 Candidate.Viable = false;
6036 Candidate.FailureKind = ovl_fail_illegal_constructor;
6037 return;
6038 }
Richard Smith836a3b42017-01-13 20:46:54 +00006039
6040 // C++ [over.match.funcs]p8: (proposed DR resolution)
6041 // A constructor inherited from class type C that has a first parameter
6042 // of type "reference to P" (including such a constructor instantiated
6043 // from a template) is excluded from the set of candidate functions when
6044 // constructing an object of type cv D if the argument list has exactly
6045 // one argument and D is reference-related to P and P is reference-related
6046 // to C.
6047 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6048 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6049 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6050 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6051 QualType C = Context.getRecordType(Constructor->getParent());
6052 QualType D = Context.getRecordType(Shadow->getParent());
6053 SourceLocation Loc = Args.front()->getExprLoc();
6054 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6055 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6056 Candidate.Viable = false;
6057 Candidate.FailureKind = ovl_fail_inhctor_slice;
6058 return;
6059 }
6060 }
John McCall578a1f82014-12-14 01:46:53 +00006061 }
6062
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006063 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006064
6065 // (C++ 13.3.2p2): A candidate function having fewer than m
6066 // parameters is viable only if it has an ellipsis in its parameter
6067 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006068 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00006069 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006070 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006071 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006072 return;
6073 }
6074
6075 // (C++ 13.3.2p2): A candidate function having more than m parameters
6076 // is viable only if the (m+1)st parameter has a default argument
6077 // (8.3.6). For the purposes of overload resolution, the
6078 // parameter list is truncated on the right, so that there are
6079 // exactly m parameters.
6080 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006081 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006082 // Not enough arguments.
6083 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006084 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006085 return;
6086 }
6087
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006088 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006089 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006090 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006091 // Skip the check for callers that are implicit members, because in this
6092 // case we may not yet know what the member's target is; the target is
6093 // inferred for the member automatically, based on the bases and fields of
6094 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006095 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006096 Candidate.Viable = false;
6097 Candidate.FailureKind = ovl_fail_bad_target;
6098 return;
6099 }
6100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006101 // Determine the implicit conversion sequences for each of the
6102 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006103 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006104 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6105 // We already formed a conversion sequence for this parameter during
6106 // template argument deduction.
6107 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006108 // (C++ 13.3.2p3): for F to be a viable function, there shall
6109 // exist for each argument an implicit conversion sequence
6110 // (13.3.3.1) that converts that argument to the corresponding
6111 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006112 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006113 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006114 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006115 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006116 /*InOverloadResolution=*/true,
6117 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006118 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006119 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006120 if (Candidate.Conversions[ArgIdx].isBad()) {
6121 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006122 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006123 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006124 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006125 } else {
6126 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6127 // argument for which there is no corresponding parameter is
6128 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006129 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006130 }
6131 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006132
6133 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6134 Candidate.Viable = false;
6135 Candidate.FailureKind = ovl_fail_enable_if;
6136 Candidate.DeductionFailure.Data = FailedAttr;
6137 return;
6138 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006139
6140 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6141 Candidate.Viable = false;
6142 Candidate.FailureKind = ovl_fail_ext_disabled;
6143 return;
6144 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006145}
6146
Manman Rend2a3cd72016-04-07 19:30:20 +00006147ObjCMethodDecl *
6148Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6149 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6150 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006151 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006152
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006153 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6154 bool Match = true;
6155 ObjCMethodDecl *Method = Methods[b];
6156 unsigned NumNamedArgs = Sel.getNumArgs();
6157 // Method might have more arguments than selector indicates. This is due
6158 // to addition of c-style arguments in method.
6159 if (Method->param_size() > NumNamedArgs)
6160 NumNamedArgs = Method->param_size();
6161 if (Args.size() < NumNamedArgs)
6162 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006163
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006164 for (unsigned i = 0; i < NumNamedArgs; i++) {
6165 // We can't do any type-checking on a type-dependent argument.
6166 if (Args[i]->isTypeDependent()) {
6167 Match = false;
6168 break;
6169 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006170
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006171 ParmVarDecl *param = Method->parameters()[i];
6172 Expr *argExpr = Args[i];
6173 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006174
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006175 // Strip the unbridged-cast placeholder expression off unless it's
6176 // a consumed argument.
6177 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6178 !param->hasAttr<CFConsumedAttr>())
6179 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006180
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006181 // If the parameter is __unknown_anytype, move on to the next method.
6182 if (param->getType() == Context.UnknownAnyTy) {
6183 Match = false;
6184 break;
6185 }
George Burgess IV45461812015-10-11 20:13:20 +00006186
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006187 ImplicitConversionSequence ConversionState
6188 = TryCopyInitialization(*this, argExpr, param->getType(),
6189 /*SuppressUserConversions*/false,
6190 /*InOverloadResolution=*/true,
6191 /*AllowObjCWritebackConversion=*/
6192 getLangOpts().ObjCAutoRefCount,
6193 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006194 // This function looks for a reasonably-exact match, so we consider
6195 // incompatible pointer conversions to be a failure here.
6196 if (ConversionState.isBad() ||
6197 (ConversionState.isStandard() &&
6198 ConversionState.Standard.Second ==
6199 ICK_Incompatible_Pointer_Conversion)) {
6200 Match = false;
6201 break;
6202 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006203 }
6204 // Promote additional arguments to variadic methods.
6205 if (Match && Method->isVariadic()) {
6206 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6207 if (Args[i]->isTypeDependent()) {
6208 Match = false;
6209 break;
6210 }
6211 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6212 nullptr);
6213 if (Arg.isInvalid()) {
6214 Match = false;
6215 break;
6216 }
6217 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006218 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006219 // Check for extra arguments to non-variadic methods.
6220 if (Args.size() != NumNamedArgs)
6221 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006222 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6223 // Special case when selectors have no argument. In this case, select
6224 // one with the most general result type of 'id'.
6225 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6226 QualType ReturnT = Methods[b]->getReturnType();
6227 if (ReturnT->isObjCIdType())
6228 return Methods[b];
6229 }
6230 }
6231 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006232
6233 if (Match)
6234 return Method;
6235 }
6236 return nullptr;
6237}
6238
George Burgess IV177399e2017-01-09 04:12:14 +00006239static bool
6240convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6241 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6242 bool MissingImplicitThis, Expr *&ConvertedThis,
6243 SmallVectorImpl<Expr *> &ConvertedArgs) {
6244 if (ThisArg) {
6245 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6246 assert(!isa<CXXConstructorDecl>(Method) &&
6247 "Shouldn't have `this` for ctors!");
6248 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6249 ExprResult R = S.PerformObjectArgumentInitialization(
6250 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6251 if (R.isInvalid())
6252 return false;
6253 ConvertedThis = R.get();
6254 } else {
6255 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6256 (void)MD;
6257 assert((MissingImplicitThis || MD->isStatic() ||
6258 isa<CXXConstructorDecl>(MD)) &&
6259 "Expected `this` for non-ctor instance methods");
6260 }
6261 ConvertedThis = nullptr;
6262 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006263
George Burgess IV458b3f32016-08-12 04:19:35 +00006264 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006265 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006266 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6267
Nick Lewyckye283c552015-08-25 22:33:16 +00006268 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006269 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006270 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006271 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6272 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006273 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006274
George Burgess IV177399e2017-01-09 04:12:14 +00006275 if (R.isInvalid())
6276 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006277
George Burgess IVe96abf72016-02-24 22:31:14 +00006278 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006279 }
6280
George Burgess IV177399e2017-01-09 04:12:14 +00006281 if (Trap.hasErrorOccurred())
6282 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006283
Nick Lewyckye283c552015-08-25 22:33:16 +00006284 // Push default arguments if needed.
6285 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6286 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6287 ParmVarDecl *P = Function->getParamDecl(i);
Ilya Biryukov1a1dffd2018-03-09 14:43:29 +00006288 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6289 ? P->getUninstantiatedDefaultArg()
6290 : P->getDefaultArg();
6291 // This can only happen in code completion, i.e. when PartialOverloading
6292 // is true.
6293 if (!DefArg)
6294 return false;
6295 ExprResult R =
6296 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6297 S.Context, Function->getParamDecl(i)),
6298 SourceLocation(), DefArg);
George Burgess IV177399e2017-01-09 04:12:14 +00006299 if (R.isInvalid())
6300 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006301 ConvertedArgs.push_back(R.get());
6302 }
6303
George Burgess IV177399e2017-01-09 04:12:14 +00006304 if (Trap.hasErrorOccurred())
6305 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006306 }
George Burgess IV177399e2017-01-09 04:12:14 +00006307 return true;
6308}
6309
6310EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6311 bool MissingImplicitThis) {
Michael Krusedc5ce722018-08-03 01:21:16 +00006312 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6313 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
George Burgess IV177399e2017-01-09 04:12:14 +00006314 return nullptr;
6315
6316 SFINAETrap Trap(*this);
6317 SmallVector<Expr *, 16> ConvertedArgs;
6318 // FIXME: We should look into making enable_if late-parsed.
6319 Expr *DiscardedThis;
6320 if (!convertArgsForAvailabilityChecks(
6321 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6322 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
Michael Krusedc5ce722018-08-03 01:21:16 +00006323 return *EnableIfAttrs.begin();
Nick Lewyckye283c552015-08-25 22:33:16 +00006324
George Burgess IV2a6150d2015-10-16 01:17:38 +00006325 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006326 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006327 // FIXME: This doesn't consider value-dependent cases, because doing so is
6328 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006329 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006330 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006331 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006332
6333 if (!Result.isInt() || !Result.getInt().getBoolValue())
6334 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006335 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006336 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006337}
6338
George Burgess IV177399e2017-01-09 04:12:14 +00006339template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006340static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006341 bool ArgDependent, SourceLocation Loc,
6342 CheckFn &&IsSuccessful) {
6343 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006344 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006345 if (ArgDependent == DIA->getArgDependent())
6346 Attrs.push_back(DIA);
6347 }
6348
6349 // Common case: No diagnose_if attributes, so we can quit early.
6350 if (Attrs.empty())
6351 return false;
6352
6353 auto WarningBegin = std::stable_partition(
6354 Attrs.begin(), Attrs.end(),
6355 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6356
George Burgess IV177399e2017-01-09 04:12:14 +00006357 // Note that diagnose_if attributes are late-parsed, so they appear in the
6358 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006359 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6360 IsSuccessful);
6361 if (ErrAttr != WarningBegin) {
6362 const DiagnoseIfAttr *DIA = *ErrAttr;
6363 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6364 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6365 << DIA->getParent() << DIA->getCond()->getSourceRange();
6366 return true;
6367 }
George Burgess IV177399e2017-01-09 04:12:14 +00006368
George Burgess IVce6284b2017-01-28 02:19:40 +00006369 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6370 if (IsSuccessful(DIA)) {
6371 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6372 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6373 << DIA->getParent() << DIA->getCond()->getSourceRange();
6374 }
6375
6376 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006377}
6378
George Burgess IVce6284b2017-01-28 02:19:40 +00006379bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6380 const Expr *ThisArg,
6381 ArrayRef<const Expr *> Args,
6382 SourceLocation Loc) {
6383 return diagnoseDiagnoseIfAttrsWith(
6384 *this, Function, /*ArgDependent=*/true, Loc,
6385 [&](const DiagnoseIfAttr *DIA) {
6386 APValue Result;
6387 // It's sane to use the same Args for any redecl of this function, since
6388 // EvaluateWithSubstitution only cares about the position of each
6389 // argument in the arg list, not the ParmVarDecl* it maps to.
6390 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006391 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006392 return false;
6393 return Result.isInt() && Result.getInt().getBoolValue();
6394 });
George Burgess IV177399e2017-01-09 04:12:14 +00006395}
6396
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006397bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006398 SourceLocation Loc) {
6399 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006400 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006401 [&](const DiagnoseIfAttr *DIA) {
6402 bool Result;
6403 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6404 Result;
6405 });
George Burgess IV177399e2017-01-09 04:12:14 +00006406}
6407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006408/// Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006409/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006410void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006411 ArrayRef<Expr *> Args,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006412 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006413 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006414 bool SuppressUserConversions,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006415 bool PartialOverloading,
6416 bool FirstArgumentIsBase) {
John McCall4c4c1df2010-01-26 03:27:55 +00006417 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006418 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006419 ArrayRef<Expr *> FunctionArgs = Args;
6420
6421 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6422 FunctionDecl *FD =
6423 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6424
6425 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6426 QualType ObjectType;
6427 Expr::Classification ObjectClassification;
6428 if (Args.size() > 0) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006429 if (Expr *E = Args[0]) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006430 // Use the explicit base to restrict the lookup:
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006431 ObjectType = E->getType();
6432 ObjectClassification = E->Classify(Context);
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006433 } // .. else there is an implicit base.
6434 FunctionArgs = Args.slice(1);
6435 }
6436 if (FunTmpl) {
George Burgess IV177399e2017-01-09 04:12:14 +00006437 AddMethodTemplateCandidate(
6438 FunTmpl, F.getPair(),
6439 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006440 ExplicitTemplateArgs, ObjectType, ObjectClassification,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006441 FunctionArgs, CandidateSet, SuppressUserConversions,
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006442 PartialOverloading);
6443 } else {
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006444 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6445 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6446 ObjectClassification, FunctionArgs, CandidateSet,
6447 SuppressUserConversions, PartialOverloading);
6448 }
6449 } else {
6450 // This branch handles both standalone functions and static methods.
6451
6452 // Slice the first argument (which is the base) when we access
6453 // static method as non-static.
6454 if (Args.size() > 0 &&
6455 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6456 !isa<CXXConstructorDecl>(FD)))) {
6457 assert(cast<CXXMethodDecl>(FD)->isStatic());
6458 FunctionArgs = Args.slice(1);
6459 }
6460 if (FunTmpl) {
6461 AddTemplateOverloadCandidate(
6462 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6463 CandidateSet, SuppressUserConversions, PartialOverloading);
6464 } else {
6465 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6466 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006467 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006468 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006469 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006470}
6471
John McCallf0f1cf02009-11-17 07:50:12 +00006472/// AddMethodCandidate - Adds a named decl (which is some kind of
6473/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006474void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006475 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006476 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006477 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006478 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006479 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006480 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006481 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006482
6483 if (isa<UsingShadowDecl>(Decl))
6484 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006485
John McCallf0f1cf02009-11-17 07:50:12 +00006486 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6487 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6488 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006489 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006490 /*ExplicitArgs*/ nullptr, ObjectType,
6491 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006492 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006493 } else {
John McCalla0296f72010-03-19 07:35:19 +00006494 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006495 ObjectType, ObjectClassification, Args, CandidateSet,
6496 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006497 }
6498}
6499
Douglas Gregor436424c2008-11-18 23:14:02 +00006500/// AddMethodCandidate - Adds the given C++ member function to the set
6501/// of candidate functions, using the given function call arguments
6502/// and the object argument (@c Object). For example, in a call
6503/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6504/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6505/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006506/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006507void
John McCalla0296f72010-03-19 07:35:19 +00006508Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006509 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006510 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006511 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006512 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006513 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006514 bool PartialOverloading,
6515 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006516 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006517 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006518 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006519 assert(!isa<CXXConstructorDecl>(Method) &&
6520 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006521
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006522 if (!CandidateSet.isNewCandidate(Method))
6523 return;
6524
Richard Smith8b86f2d2013-11-04 01:48:18 +00006525 // C++11 [class.copy]p23: [DR1402]
6526 // A defaulted move assignment operator that is defined as deleted is
6527 // ignored by overload resolution.
6528 if (Method->isDefaulted() && Method->isDeleted() &&
6529 Method->isMoveAssignmentOperator())
6530 return;
6531
Douglas Gregor27381f32009-11-23 12:27:39 +00006532 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006533 EnterExpressionEvaluationContext Unevaluated(
6534 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006535
Douglas Gregor436424c2008-11-18 23:14:02 +00006536 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006537 OverloadCandidate &Candidate =
6538 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006539 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006540 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006541 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006542 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006543 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006544
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006545 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006546
6547 // (C++ 13.3.2p2): A candidate function having fewer than m
6548 // parameters is viable only if it has an ellipsis in its parameter
6549 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006550 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6551 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006552 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006553 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006554 return;
6555 }
6556
6557 // (C++ 13.3.2p2): A candidate function having more than m parameters
6558 // is viable only if the (m+1)st parameter has a default argument
6559 // (8.3.6). For the purposes of overload resolution, the
6560 // parameter list is truncated on the right, so that there are
6561 // exactly m parameters.
6562 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006563 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006564 // Not enough arguments.
6565 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006566 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006567 return;
6568 }
6569
6570 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006571
John McCall6e9f8f62009-12-03 04:06:58 +00006572 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006573 // The implicit object argument is ignored.
6574 Candidate.IgnoreObjectArgument = true;
6575 else {
6576 // Determine the implicit conversion sequence for the object
6577 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006578 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6579 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6580 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006581 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006582 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006583 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006584 return;
6585 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006586 }
6587
Eli Bendersky291a57e2014-09-25 23:59:08 +00006588 // (CUDA B.1): Check for invalid calls between targets.
6589 if (getLangOpts().CUDA)
6590 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006591 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006592 Candidate.Viable = false;
6593 Candidate.FailureKind = ovl_fail_bad_target;
6594 return;
6595 }
6596
Douglas Gregor436424c2008-11-18 23:14:02 +00006597 // Determine the implicit conversion sequences for each of the
6598 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006599 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006600 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6601 // We already formed a conversion sequence for this parameter during
6602 // template argument deduction.
6603 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006604 // (C++ 13.3.2p3): for F to be a viable function, there shall
6605 // exist for each argument an implicit conversion sequence
6606 // (13.3.3.1) that converts that argument to the corresponding
6607 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006608 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006609 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006610 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006611 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006612 /*InOverloadResolution=*/true,
6613 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006614 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006615 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006616 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006617 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006618 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006619 }
6620 } else {
6621 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6622 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006623 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006624 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006625 }
6626 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006627
6628 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6629 Candidate.Viable = false;
6630 Candidate.FailureKind = ovl_fail_enable_if;
6631 Candidate.DeductionFailure.Data = FailedAttr;
6632 return;
6633 }
Erich Keane281d20b2018-01-08 21:34:17 +00006634
Erich Keane3efe0022018-07-20 14:13:28 +00006635 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00006636 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6637 Candidate.Viable = false;
6638 Candidate.FailureKind = ovl_non_default_multiversion_function;
6639 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006640}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006642/// Add a C++ member function template as a candidate to the candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006643/// set, using template argument deduction to produce an appropriate member
6644/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006645void
Douglas Gregor97628d62009-08-21 00:16:32 +00006646Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006647 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006648 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006649 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006650 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006651 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006652 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006653 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006654 bool SuppressUserConversions,
6655 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006656 if (!CandidateSet.isNewCandidate(MethodTmpl))
6657 return;
6658
Douglas Gregor97628d62009-08-21 00:16:32 +00006659 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006660 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006661 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006662 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006663 // candidate functions in the usual way.113) A given name can refer to one
6664 // or more function templates and also to a set of overloaded non-template
6665 // functions. In such a case, the candidate functions generated from each
6666 // function template are combined with the set of non-template candidate
6667 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006668 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006669 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006670 ConversionSequenceList Conversions;
6671 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6672 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6673 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6674 return CheckNonDependentConversions(
6675 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6676 SuppressUserConversions, ActingContext, ObjectType,
6677 ObjectClassification);
6678 })) {
6679 OverloadCandidate &Candidate =
6680 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006681 Candidate.FoundDecl = FoundDecl;
6682 Candidate.Function = MethodTmpl->getTemplatedDecl();
6683 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006684 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006685 Candidate.IgnoreObjectArgument =
6686 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6687 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006688 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006689 if (Result == TDK_NonDependentConversionFailure)
6690 Candidate.FailureKind = ovl_fail_bad_conversion;
6691 else {
6692 Candidate.FailureKind = ovl_fail_bad_deduction;
6693 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6694 Info);
6695 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006696 return;
6697 }
Mike Stump11289f42009-09-09 15:08:12 +00006698
Douglas Gregor97628d62009-08-21 00:16:32 +00006699 // Add the function template specialization produced by template argument
6700 // deduction as a candidate.
6701 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006702 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006703 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006704 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006705 ActingContext, ObjectType, ObjectClassification, Args,
6706 CandidateSet, SuppressUserConversions, PartialOverloading,
6707 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006708}
6709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006710/// Add a C++ function template specialization as a candidate
Douglas Gregor05155d82009-08-21 23:19:43 +00006711/// in the candidate set, using template argument deduction to produce
6712/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006713void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006714Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006715 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006716 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006717 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006718 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006719 bool SuppressUserConversions,
6720 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006721 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6722 return;
6723
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006724 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006725 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006726 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006727 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006728 // candidate functions in the usual way.113) A given name can refer to one
6729 // or more function templates and also to a set of overloaded non-template
6730 // functions. In such a case, the candidate functions generated from each
6731 // function template are combined with the set of non-template candidate
6732 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006733 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006734 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006735 ConversionSequenceList Conversions;
6736 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6737 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6738 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6739 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6740 Args, CandidateSet, Conversions,
6741 SuppressUserConversions);
6742 })) {
6743 OverloadCandidate &Candidate =
6744 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006745 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006746 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6747 Candidate.Viable = false;
6748 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006749 // Ignore the object argument if there is one, since we don't have an object
6750 // type.
6751 Candidate.IgnoreObjectArgument =
6752 isa<CXXMethodDecl>(Candidate.Function) &&
6753 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006754 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006755 if (Result == TDK_NonDependentConversionFailure)
6756 Candidate.FailureKind = ovl_fail_bad_conversion;
6757 else {
6758 Candidate.FailureKind = ovl_fail_bad_deduction;
6759 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6760 Info);
6761 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006762 return;
6763 }
Mike Stump11289f42009-09-09 15:08:12 +00006764
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006765 // Add the function template specialization produced by template argument
6766 // deduction as a candidate.
6767 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006768 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006769 SuppressUserConversions, PartialOverloading,
6770 /*AllowExplicit*/false, Conversions);
6771}
6772
6773/// Check that implicit conversion sequences can be formed for each argument
6774/// whose corresponding parameter has a non-dependent type, per DR1391's
6775/// [temp.deduct.call]p10.
6776bool Sema::CheckNonDependentConversions(
6777 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6778 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6779 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6780 CXXRecordDecl *ActingContext, QualType ObjectType,
6781 Expr::Classification ObjectClassification) {
6782 // FIXME: The cases in which we allow explicit conversions for constructor
6783 // arguments never consider calling a constructor template. It's not clear
6784 // that is correct.
6785 const bool AllowExplicit = false;
6786
6787 auto *FD = FunctionTemplate->getTemplatedDecl();
6788 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6789 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6790 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6791
6792 Conversions =
6793 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6794
6795 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006796 EnterExpressionEvaluationContext Unevaluated(
6797 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006798
6799 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6800 // require that, but this check should never result in a hard error, and
6801 // overload resolution is permitted to sidestep instantiations.
6802 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6803 !ObjectType.isNull()) {
6804 Conversions[0] = TryObjectArgumentInitialization(
6805 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6806 Method, ActingContext);
6807 if (Conversions[0].isBad())
6808 return true;
6809 }
6810
6811 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6812 ++I) {
6813 QualType ParamType = ParamTypes[I];
6814 if (!ParamType->isDependentType()) {
6815 Conversions[ThisConversions + I]
6816 = TryCopyInitialization(*this, Args[I], ParamType,
6817 SuppressUserConversions,
6818 /*InOverloadResolution=*/true,
6819 /*AllowObjCWritebackConversion=*/
6820 getLangOpts().ObjCAutoRefCount,
6821 AllowExplicit);
6822 if (Conversions[ThisConversions + I].isBad())
6823 return true;
6824 }
6825 }
6826
6827 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006828}
Mike Stump11289f42009-09-09 15:08:12 +00006829
Douglas Gregor4b60a152013-11-07 22:34:54 +00006830/// Determine whether this is an allowable conversion from the result
6831/// of an explicit conversion operator to the expected type, per C++
6832/// [over.match.conv]p1 and [over.match.ref]p1.
6833///
6834/// \param ConvType The return type of the conversion function.
6835///
6836/// \param ToType The type we are converting to.
6837///
6838/// \param AllowObjCPointerConversion Allow a conversion from one
6839/// Objective-C pointer to another.
6840///
6841/// \returns true if the conversion is allowable, false otherwise.
6842static bool isAllowableExplicitConversion(Sema &S,
6843 QualType ConvType, QualType ToType,
6844 bool AllowObjCPointerConversion) {
6845 QualType ToNonRefType = ToType.getNonReferenceType();
6846
6847 // Easy case: the types are the same.
6848 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6849 return true;
6850
6851 // Allow qualification conversions.
6852 bool ObjCLifetimeConversion;
6853 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6854 ObjCLifetimeConversion))
6855 return true;
6856
6857 // If we're not allowed to consider Objective-C pointer conversions,
6858 // we're done.
6859 if (!AllowObjCPointerConversion)
6860 return false;
6861
6862 // Is this an Objective-C pointer conversion?
6863 bool IncompatibleObjC = false;
6864 QualType ConvertedType;
6865 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6866 IncompatibleObjC);
6867}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006868
Douglas Gregora1f013e2008-11-07 22:36:19 +00006869/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006870/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006871/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006872/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006873/// (which may or may not be the same type as the type that the
6874/// conversion function produces).
6875void
6876Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006877 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006878 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006879 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006880 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006881 bool AllowObjCConversionOnExplicit,
6882 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006883 assert(!Conversion->getDescribedFunctionTemplate() &&
6884 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006885 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006886 if (!CandidateSet.isNewCandidate(Conversion))
6887 return;
6888
Richard Smith2a7d4812013-05-04 07:00:32 +00006889 // If the conversion function has an undeduced return type, trigger its
6890 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006891 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006892 if (DeduceReturnType(Conversion, From->getExprLoc()))
6893 return;
6894 ConvType = Conversion->getConversionType().getNonReferenceType();
6895 }
6896
Richard Smith67ef14f2017-09-26 18:37:55 +00006897 // If we don't allow any conversion of the result type, ignore conversion
6898 // functions that don't convert to exactly (possibly cv-qualified) T.
6899 if (!AllowResultConversion &&
6900 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6901 return;
6902
Richard Smith089c3162013-09-21 21:55:46 +00006903 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6904 // operator is only a candidate if its return type is the target type or
6905 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006906 if (Conversion->isExplicit() &&
6907 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006908 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006909 return;
6910
Douglas Gregor27381f32009-11-23 12:27:39 +00006911 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006912 EnterExpressionEvaluationContext Unevaluated(
6913 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006914
Douglas Gregora1f013e2008-11-07 22:36:19 +00006915 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006916 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006917 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006918 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006919 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006920 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006921 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006922 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006923 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006924 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006925 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006926
Douglas Gregor6affc782010-08-19 15:37:02 +00006927 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006928 // For conversion functions, the function is considered to be a member of
6929 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006930 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006931 //
6932 // Determine the implicit conversion sequence for the implicit
6933 // object parameter.
6934 QualType ImplicitParamType = From->getType();
6935 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6936 ImplicitParamType = FromPtrType->getPointeeType();
6937 CXXRecordDecl *ConversionContext
6938 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939
Richard Smith0f59cb32015-12-18 21:45:41 +00006940 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6941 *this, CandidateSet.getLocation(), From->getType(),
6942 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
John McCall0d1da222010-01-12 00:44:57 +00006944 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006946 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006947 return;
6948 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006949
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006950 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006951 // derived to base as such conversions are given Conversion Rank. They only
6952 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6953 QualType FromCanon
6954 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6955 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006956 if (FromCanon == ToCanon ||
6957 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006958 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006959 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006960 return;
6961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregora1f013e2008-11-07 22:36:19 +00006963 // To determine what the conversion from the result of calling the
6964 // conversion function to the type we're eventually trying to
6965 // convert to (ToType), we need to synthesize a call to the
6966 // conversion function and attempt copy initialization from it. This
6967 // makes sure that we get the right semantics with respect to
6968 // lvalues/rvalues and the type. Fortunately, we can allocate this
6969 // call on the stack and we don't need its arguments to be
6970 // well-formed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006971 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue,
6972 From->getBeginLoc());
John McCallcf142162010-08-07 06:22:56 +00006973 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6974 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006975 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006976 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006977
Richard Smith48d24642011-07-13 22:53:21 +00006978 QualType ConversionType = Conversion->getConversionType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006979 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006980 Candidate.Viable = false;
6981 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6982 return;
6983 }
6984
Richard Smith48d24642011-07-13 22:53:21 +00006985 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006986
Mike Stump11289f42009-09-09 15:08:12 +00006987 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006988 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6989 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006990 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006991 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006992 From->getBeginLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006993 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006994 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006995 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006996 /*InOverloadResolution=*/false,
6997 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006998
John McCall0d1da222010-01-12 00:44:57 +00006999 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00007000 case ImplicitConversionSequence::StandardConversion:
7001 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007003 // C++ [over.ics.user]p3:
7004 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007005 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007006 // shall have exact match rank.
7007 if (Conversion->getPrimaryTemplate() &&
7008 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7009 Candidate.Viable = false;
7010 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007011 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregorcba72b12011-01-21 05:18:22 +00007014 // C++0x [dcl.init.ref]p5:
7015 // In the second case, if the reference is an rvalue reference and
7016 // the second standard conversion sequence of the user-defined
7017 // conversion sequence includes an lvalue-to-rvalue conversion, the
7018 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00007020 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7021 Candidate.Viable = false;
7022 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007023 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00007024 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007025 break;
7026
7027 case ImplicitConversionSequence::BadConversion:
7028 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00007029 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007030 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00007031
7032 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007033 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00007034 "Can only end up with a standard conversion sequence or failure");
7035 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007036
Craig Topper5fc8fc22014-08-27 06:28:36 +00007037 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007038 Candidate.Viable = false;
7039 Candidate.FailureKind = ovl_fail_enable_if;
7040 Candidate.DeductionFailure.Data = FailedAttr;
7041 return;
7042 }
Erich Keane281d20b2018-01-08 21:34:17 +00007043
Erich Keane3efe0022018-07-20 14:13:28 +00007044 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00007045 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7046 Candidate.Viable = false;
7047 Candidate.FailureKind = ovl_non_default_multiversion_function;
7048 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007049}
7050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007051/// Adds a conversion function template specialization
Douglas Gregor05155d82009-08-21 23:19:43 +00007052/// candidate to the overload set, using template argument deduction
7053/// to deduce the template arguments of the conversion function
7054/// template from the type that we are converting to (C++
7055/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00007056void
Douglas Gregor05155d82009-08-21 23:19:43 +00007057Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00007058 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007059 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00007060 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00007061 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00007062 bool AllowObjCConversionOnExplicit,
7063 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007064 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7065 "Only conversion function templates permitted here");
7066
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007067 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7068 return;
7069
Craig Toppere6706e42012-09-19 02:26:47 +00007070 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007071 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00007072 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00007073 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00007074 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00007075 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007076 Candidate.FoundDecl = FoundDecl;
7077 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7078 Candidate.Viable = false;
7079 Candidate.FailureKind = ovl_fail_bad_deduction;
7080 Candidate.IsSurrogate = false;
7081 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00007082 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007084 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00007085 return;
7086 }
Mike Stump11289f42009-09-09 15:08:12 +00007087
Douglas Gregor05155d82009-08-21 23:19:43 +00007088 // Add the conversion function template specialization produced by
7089 // template argument deduction as a candidate.
7090 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007091 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007092 CandidateSet, AllowObjCConversionOnExplicit,
7093 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007094}
7095
Douglas Gregorab7897a2008-11-19 22:57:39 +00007096/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7097/// converts the given @c Object to a function pointer via the
7098/// conversion function @c Conversion, and then attempts to call it
7099/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7100/// the type of function that we'll eventually be calling.
7101void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007102 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007103 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007104 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007105 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007106 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007107 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007108 if (!CandidateSet.isNewCandidate(Conversion))
7109 return;
7110
Douglas Gregor27381f32009-11-23 12:27:39 +00007111 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007112 EnterExpressionEvaluationContext Unevaluated(
7113 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007114
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007116 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007117 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007118 Candidate.Surrogate = Conversion;
7119 Candidate.Viable = true;
7120 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007121 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007122 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007123
7124 // Determine the implicit conversion sequence for the implicit
7125 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007126 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7127 *this, CandidateSet.getLocation(), Object->getType(),
7128 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007129 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007130 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007131 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007132 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007133 return;
7134 }
7135
7136 // The first conversion is actually a user-defined conversion whose
7137 // first conversion is ObjectInit's standard conversion (which is
7138 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007139 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007140 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007141 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007142 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007143 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007144 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007145 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007146 = Candidate.Conversions[0].UserDefined.Before;
7147 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7148
Mike Stump11289f42009-09-09 15:08:12 +00007149 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007150 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007151
7152 // (C++ 13.3.2p2): A candidate function having fewer than m
7153 // parameters is viable only if it has an ellipsis in its parameter
7154 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007155 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007156 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007157 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007158 return;
7159 }
7160
7161 // Function types don't have any default arguments, so just check if
7162 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007163 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007164 // Not enough arguments.
7165 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007166 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007167 return;
7168 }
7169
7170 // Determine the implicit conversion sequences for each of the
7171 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007172 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007173 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007174 // (C++ 13.3.2p3): for F to be a viable function, there shall
7175 // exist for each argument an implicit conversion sequence
7176 // (13.3.3.1) that converts that argument to the corresponding
7177 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007178 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007179 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007180 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007181 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007182 /*InOverloadResolution=*/false,
7183 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007184 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007185 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007186 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007187 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007188 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007189 }
7190 } else {
7191 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7192 // argument for which there is no corresponding parameter is
7193 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007194 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007195 }
7196 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007197
Craig Topper5fc8fc22014-08-27 06:28:36 +00007198 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007199 Candidate.Viable = false;
7200 Candidate.FailureKind = ovl_fail_enable_if;
7201 Candidate.DeductionFailure.Data = FailedAttr;
7202 return;
7203 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007204}
7205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007206/// Add overload candidates for overloaded operators that are
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007207/// member functions.
7208///
7209/// Add the overloaded operator candidates that are member functions
7210/// for the operator Op that was used in an operator expression such
7211/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7212/// CandidateSet will store the added overload candidates. (C++
7213/// [over.match.oper]).
7214void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7215 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007216 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007217 OverloadCandidateSet& CandidateSet,
7218 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7220
7221 // C++ [over.match.oper]p3:
7222 // For a unary operator @ with an operand of a type whose
7223 // cv-unqualified version is T1, and for a binary operator @ with
7224 // a left operand of a type whose cv-unqualified version is T1 and
7225 // a right operand of a type whose cv-unqualified version is T2,
7226 // three sets of candidate functions, designated member
7227 // candidates, non-member candidates and built-in candidates, are
7228 // constructed as follows:
7229 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007230
Richard Smith0feaf0c2013-04-20 12:41:22 +00007231 // -- If T1 is a complete class type or a class currently being
7232 // defined, the set of member candidates is the result of the
7233 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7234 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007235 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007236 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007237 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007238 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007239 // If the type is neither complete nor being defined, bail out now.
7240 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007241 return;
Mike Stump11289f42009-09-09 15:08:12 +00007242
John McCall27b18f82009-11-17 02:14:36 +00007243 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7244 LookupQualifiedName(Operators, T1Rec->getDecl());
7245 Operators.suppressDiagnostics();
7246
Mike Stump11289f42009-09-09 15:08:12 +00007247 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007248 OperEnd = Operators.end();
7249 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007250 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007251 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007252 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007253 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007254 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007255}
7256
Douglas Gregora11693b2008-11-12 17:17:38 +00007257/// AddBuiltinCandidate - Add a candidate for a built-in
7258/// operator. ResultTy and ParamTys are the result and parameter types
7259/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007260/// arguments being passed to the candidate. IsAssignmentOperator
7261/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007262/// operator. NumContextualBoolArguments is the number of arguments
7263/// (at the beginning of the argument list) that will be contextually
7264/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007265void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007266 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007267 bool IsAssignmentOperator,
7268 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007269 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007270 EnterExpressionEvaluationContext Unevaluated(
7271 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007272
Douglas Gregora11693b2008-11-12 17:17:38 +00007273 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007274 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007275 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7276 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007277 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007278 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007279 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007280
7281 // Determine the implicit conversion sequences for each of the
7282 // arguments.
7283 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007284 Candidate.ExplicitCallArguments = Args.size();
7285 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007286 // C++ [over.match.oper]p4:
7287 // For the built-in assignment operators, conversions of the
7288 // left operand are restricted as follows:
7289 // -- no temporaries are introduced to hold the left operand, and
7290 // -- no user-defined conversions are applied to the left
7291 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007292 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007293 //
7294 // We block these conversions by turning off user-defined
7295 // conversions, since that is the only way that initialization of
7296 // a reference to a non-class type can occur from something that
7297 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007298 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007299 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007300 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007301 Candidate.Conversions[ArgIdx]
7302 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007303 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007304 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007305 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007306 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007307 /*InOverloadResolution=*/false,
7308 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007309 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007310 }
John McCall0d1da222010-01-12 00:44:57 +00007311 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007312 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007313 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007314 break;
7315 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007316 }
7317}
7318
Craig Toppercd7b0332013-07-01 06:29:40 +00007319namespace {
7320
Douglas Gregora11693b2008-11-12 17:17:38 +00007321/// BuiltinCandidateTypeSet - A set of types that will be used for the
7322/// candidate operator functions for built-in operators (C++
7323/// [over.built]). The types are separated into pointer types and
7324/// enumeration types.
7325class BuiltinCandidateTypeSet {
7326 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007327 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7328 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007329
7330 /// PointerTypes - The set of pointer types that will be used in the
7331 /// built-in candidates.
7332 TypeSet PointerTypes;
7333
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007334 /// MemberPointerTypes - The set of member pointer types that will be
7335 /// used in the built-in candidates.
7336 TypeSet MemberPointerTypes;
7337
Douglas Gregora11693b2008-11-12 17:17:38 +00007338 /// EnumerationTypes - The set of enumeration types that will be
7339 /// used in the built-in candidates.
7340 TypeSet EnumerationTypes;
7341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007342 /// The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007343 /// candidates.
7344 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007345
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007346 /// A flag indicating non-record types are viable candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007347 bool HasNonRecordTypes;
7348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007349 /// A flag indicating whether either arithmetic or enumeration types
Chandler Carruth00a38332010-12-13 01:44:01 +00007350 /// were present in the candidate set.
7351 bool HasArithmeticOrEnumeralTypes;
7352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007353 /// A flag indicating whether the nullptr type was present in the
Douglas Gregor80af3132011-05-21 23:15:46 +00007354 /// candidate set.
7355 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007356
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007357 /// Sema - The semantic analysis instance where we are building the
7358 /// candidate type set.
7359 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007360
Douglas Gregora11693b2008-11-12 17:17:38 +00007361 /// Context - The AST context in which we will build the type sets.
7362 ASTContext &Context;
7363
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007364 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7365 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007366 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007367
7368public:
7369 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007370 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007371
Mike Stump11289f42009-09-09 15:08:12 +00007372 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007373 : HasNonRecordTypes(false),
7374 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007375 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007376 SemaRef(SemaRef),
7377 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007378
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007379 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007380 SourceLocation Loc,
7381 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007382 bool AllowExplicitConversions,
7383 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007384
7385 /// pointer_begin - First pointer type found;
7386 iterator pointer_begin() { return PointerTypes.begin(); }
7387
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007388 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007389 iterator pointer_end() { return PointerTypes.end(); }
7390
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007391 /// member_pointer_begin - First member pointer type found;
7392 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7393
7394 /// member_pointer_end - Past the last member pointer type found;
7395 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7396
Douglas Gregora11693b2008-11-12 17:17:38 +00007397 /// enumeration_begin - First enumeration type found;
7398 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7399
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007400 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007401 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007402
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007403 iterator vector_begin() { return VectorTypes.begin(); }
7404 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007405
7406 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7407 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007408 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007409};
7410
Craig Toppercd7b0332013-07-01 06:29:40 +00007411} // end anonymous namespace
7412
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007413/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007414/// the set of pointer types along with any more-qualified variants of
7415/// that type. For example, if @p Ty is "int const *", this routine
7416/// will add "int const *", "int const volatile *", "int const
7417/// restrict *", and "int const volatile restrict *" to the set of
7418/// pointer types. Returns true if the add of @p Ty itself succeeded,
7419/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007420///
7421/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007422bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007423BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7424 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007425
Douglas Gregora11693b2008-11-12 17:17:38 +00007426 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007427 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007428 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007429
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007430 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007431 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007432 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007433 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007434 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7435 PointeeTy = PTy->getPointeeType();
7436 buildObjCPtr = true;
7437 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007438 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007439 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007440
Sebastian Redl4990a632009-11-18 20:39:26 +00007441 // Don't add qualified variants of arrays. For one, they're not allowed
7442 // (the qualifier would sink to the element type), and for another, the
7443 // only overload situation where it matters is subscript or pointer +- int,
7444 // and those shouldn't have qualifier variants anyway.
7445 if (PointeeTy->isArrayType())
7446 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007447
John McCall8ccfcb52009-09-24 19:53:00 +00007448 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007449 bool hasVolatile = VisibleQuals.hasVolatile();
7450 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007451
John McCall8ccfcb52009-09-24 19:53:00 +00007452 // Iterate through all strict supersets of BaseCVR.
7453 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7454 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007455 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007456 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007457
Douglas Gregor5bee2582012-06-04 00:15:09 +00007458 // Skip over restrict if no restrict found anywhere in the types, or if
7459 // the type cannot be restrict-qualified.
7460 if ((CVR & Qualifiers::Restrict) &&
7461 (!hasRestrict ||
7462 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7463 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007464
Douglas Gregor5bee2582012-06-04 00:15:09 +00007465 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007466 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007467
Douglas Gregor5bee2582012-06-04 00:15:09 +00007468 // Build qualified pointer type.
7469 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007470 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007471 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007472 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007473 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007474
Douglas Gregor5bee2582012-06-04 00:15:09 +00007475 // Insert qualified pointer type.
7476 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007477 }
7478
7479 return true;
7480}
7481
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007482/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7483/// to the set of pointer types along with any more-qualified variants of
7484/// that type. For example, if @p Ty is "int const *", this routine
7485/// will add "int const *", "int const volatile *", "int const
7486/// restrict *", and "int const volatile restrict *" to the set of
7487/// pointer types. Returns true if the add of @p Ty itself succeeded,
7488/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007489///
7490/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007491bool
7492BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7493 QualType Ty) {
7494 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007495 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007496 return false;
7497
John McCall8ccfcb52009-09-24 19:53:00 +00007498 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7499 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007500
John McCall8ccfcb52009-09-24 19:53:00 +00007501 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007502 // Don't add qualified variants of arrays. For one, they're not allowed
7503 // (the qualifier would sink to the element type), and for another, the
7504 // only overload situation where it matters is subscript or pointer +- int,
7505 // and those shouldn't have qualifier variants anyway.
7506 if (PointeeTy->isArrayType())
7507 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007508 const Type *ClassTy = PointerTy->getClass();
7509
7510 // Iterate through all strict supersets of the pointee type's CVR
7511 // qualifiers.
7512 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7513 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7514 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
John McCall8ccfcb52009-09-24 19:53:00 +00007516 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007517 MemberPointerTypes.insert(
7518 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007519 }
7520
7521 return true;
7522}
7523
Douglas Gregora11693b2008-11-12 17:17:38 +00007524/// AddTypesConvertedFrom - Add each of the types to which the type @p
7525/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007526/// primarily interested in pointer types and enumeration types. We also
7527/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007528/// AllowUserConversions is true if we should look at the conversion
7529/// functions of a class type, and AllowExplicitConversions if we
7530/// should also include the explicit conversion functions of a class
7531/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007532void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007533BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007534 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007535 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007536 bool AllowExplicitConversions,
7537 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007538 // Only deal with canonical types.
7539 Ty = Context.getCanonicalType(Ty);
7540
7541 // Look through reference types; they aren't part of the type of an
7542 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007543 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007544 Ty = RefTy->getPointeeType();
7545
John McCall33ddac02011-01-19 10:06:00 +00007546 // If we're dealing with an array type, decay to the pointer.
7547 if (Ty->isArrayType())
7548 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7549
7550 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007551 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007552
Chandler Carruth00a38332010-12-13 01:44:01 +00007553 // Flag if we ever add a non-record type.
7554 const RecordType *TyRec = Ty->getAs<RecordType>();
7555 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7556
Chandler Carruth00a38332010-12-13 01:44:01 +00007557 // Flag if we encounter an arithmetic type.
7558 HasArithmeticOrEnumeralTypes =
7559 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7560
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007561 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7562 PointerTypes.insert(Ty);
7563 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007564 // Insert our type, and its more-qualified variants, into the set
7565 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007566 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007567 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007568 } else if (Ty->isMemberPointerType()) {
7569 // Member pointers are far easier, since the pointee can't be converted.
7570 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7571 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007572 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007573 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007574 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007575 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007576 // We treat vector types as arithmetic types in many contexts as an
7577 // extension.
7578 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007579 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007580 } else if (Ty->isNullPtrType()) {
7581 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007582 } else if (AllowUserConversions && TyRec) {
7583 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007584 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007585 return;
Mike Stump11289f42009-09-09 15:08:12 +00007586
Chandler Carruth00a38332010-12-13 01:44:01 +00007587 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007588 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007589 if (isa<UsingShadowDecl>(D))
7590 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007591
Chandler Carruth00a38332010-12-13 01:44:01 +00007592 // Skip conversion function templates; they don't tell us anything
7593 // about which builtin types we can convert to.
7594 if (isa<FunctionTemplateDecl>(D))
7595 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007596
Chandler Carruth00a38332010-12-13 01:44:01 +00007597 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7598 if (AllowExplicitConversions || !Conv->isExplicit()) {
7599 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7600 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007601 }
7602 }
7603 }
7604}
7605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007606/// Helper function for AddBuiltinOperatorCandidates() that adds
Douglas Gregor84605ae2009-08-24 13:43:27 +00007607/// the volatile- and non-volatile-qualified assignment operators for the
7608/// given type to the candidate set.
7609static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7610 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007611 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007612 OverloadCandidateSet &CandidateSet) {
7613 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007614
Douglas Gregor84605ae2009-08-24 13:43:27 +00007615 // T& operator=(T&, T)
7616 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7617 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007618 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007619 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007620
Douglas Gregor84605ae2009-08-24 13:43:27 +00007621 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7622 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007623 ParamTypes[0]
7624 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007625 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007626 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007627 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007628 }
7629}
Mike Stump11289f42009-09-09 15:08:12 +00007630
Sebastian Redl1054fae2009-10-25 17:03:50 +00007631/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7632/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007633static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7634 Qualifiers VRQuals;
7635 const RecordType *TyRec;
7636 if (const MemberPointerType *RHSMPType =
7637 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007638 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007639 else
7640 TyRec = ArgExpr->getType()->getAs<RecordType>();
7641 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007642 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007643 VRQuals.addVolatile();
7644 VRQuals.addRestrict();
7645 return VRQuals;
7646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007647
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007648 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007649 if (!ClassDecl->hasDefinition())
7650 return VRQuals;
7651
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007652 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007653 if (isa<UsingShadowDecl>(D))
7654 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7655 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007656 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7657 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7658 CanTy = ResTypeRef->getPointeeType();
7659 // Need to go down the pointer/mempointer chain and add qualifiers
7660 // as see them.
7661 bool done = false;
7662 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007663 if (CanTy.isRestrictQualified())
7664 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007665 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7666 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007668 CanTy->getAs<MemberPointerType>())
7669 CanTy = ResTypeMPtr->getPointeeType();
7670 else
7671 done = true;
7672 if (CanTy.isVolatileQualified())
7673 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007674 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7675 return VRQuals;
7676 }
7677 }
7678 }
7679 return VRQuals;
7680}
John McCall52872982010-11-13 05:51:15 +00007681
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682namespace {
John McCall52872982010-11-13 05:51:15 +00007683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007684/// Helper class to manage the addition of builtin operator overload
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007685/// candidates. It provides shared state and utility methods used throughout
7686/// the process, as well as a helper method to add each group of builtin
7687/// operator overloads from the standard to a candidate set.
7688class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007689 // Common instance state available to all overload candidate addition methods.
7690 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007691 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007692 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007693 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007694 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007695 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696
Hans Wennborg82371412017-11-15 17:11:53 +00007697 static constexpr int ArithmeticTypesCap = 24;
7698 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7699
7700 // Define some indices used to iterate over the arithemetic types in
7701 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
John McCall52872982010-11-13 05:51:15 +00007702 // types are that preserved by promotion (C++ [over.built]p2).
Hans Wennborg82371412017-11-15 17:11:53 +00007703 unsigned FirstIntegralType,
7704 LastIntegralType;
7705 unsigned FirstPromotedIntegralType,
7706 LastPromotedIntegralType;
7707 unsigned FirstPromotedArithmeticType,
7708 LastPromotedArithmeticType;
7709 unsigned NumArithmeticTypes;
John McCall52872982010-11-13 05:51:15 +00007710
Hans Wennborg82371412017-11-15 17:11:53 +00007711 void InitArithmeticTypes() {
7712 // Start of promoted types.
7713 FirstPromotedArithmeticType = 0;
7714 ArithmeticTypes.push_back(S.Context.FloatTy);
7715 ArithmeticTypes.push_back(S.Context.DoubleTy);
7716 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7717 if (S.Context.getTargetInfo().hasFloat128Type())
7718 ArithmeticTypes.push_back(S.Context.Float128Ty);
John McCall52872982010-11-13 05:51:15 +00007719
Hans Wennborg82371412017-11-15 17:11:53 +00007720 // Start of integral types.
7721 FirstIntegralType = ArithmeticTypes.size();
7722 FirstPromotedIntegralType = ArithmeticTypes.size();
7723 ArithmeticTypes.push_back(S.Context.IntTy);
7724 ArithmeticTypes.push_back(S.Context.LongTy);
7725 ArithmeticTypes.push_back(S.Context.LongLongTy);
7726 if (S.Context.getTargetInfo().hasInt128Type())
7727 ArithmeticTypes.push_back(S.Context.Int128Ty);
7728 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7729 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7730 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7731 if (S.Context.getTargetInfo().hasInt128Type())
7732 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7733 LastPromotedIntegralType = ArithmeticTypes.size();
7734 LastPromotedArithmeticType = ArithmeticTypes.size();
7735 // End of promoted types.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007736
Hans Wennborg82371412017-11-15 17:11:53 +00007737 ArithmeticTypes.push_back(S.Context.BoolTy);
7738 ArithmeticTypes.push_back(S.Context.CharTy);
7739 ArithmeticTypes.push_back(S.Context.WCharTy);
Richard Smith3a8244d2018-05-01 05:02:45 +00007740 if (S.Context.getLangOpts().Char8)
7741 ArithmeticTypes.push_back(S.Context.Char8Ty);
Hans Wennborg82371412017-11-15 17:11:53 +00007742 ArithmeticTypes.push_back(S.Context.Char16Ty);
7743 ArithmeticTypes.push_back(S.Context.Char32Ty);
7744 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7745 ArithmeticTypes.push_back(S.Context.ShortTy);
7746 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7747 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7748 LastIntegralType = ArithmeticTypes.size();
7749 NumArithmeticTypes = ArithmeticTypes.size();
7750 // End of integral types.
7751 // FIXME: What about complex? What about half?
7752
7753 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7754 "Enough inline storage for all arithmetic types.");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007755 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007757 /// Helper method to factor out the common pattern of adding overloads
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007758 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007759 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007760 bool HasVolatile,
7761 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 QualType ParamTypes[2] = {
7763 S.Context.getLValueReferenceType(CandidateTy),
7764 S.Context.IntTy
7765 };
7766
7767 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769
7770 // Use a heuristic to reduce number of builtin candidates in the set:
7771 // add volatile version only if there are conversions to a volatile type.
7772 if (HasVolatile) {
7773 ParamTypes[0] =
7774 S.Context.getLValueReferenceType(
7775 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007776 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007777 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007778
Douglas Gregor5bee2582012-06-04 00:15:09 +00007779 // Add restrict version only if there are conversions to a restrict type
7780 // and our candidate type is a non-restrict-qualified pointer.
7781 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7782 !CandidateTy.isRestrictQualified()) {
7783 ParamTypes[0]
7784 = S.Context.getLValueReferenceType(
7785 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007786 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007787
Douglas Gregor5bee2582012-06-04 00:15:09 +00007788 if (HasVolatile) {
7789 ParamTypes[0]
7790 = S.Context.getLValueReferenceType(
7791 S.Context.getCVRQualifiedType(CandidateTy,
7792 (Qualifiers::Volatile |
7793 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007795 }
7796 }
7797
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 }
7799
7800public:
7801 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007802 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007803 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007804 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007805 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007806 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007807 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007808 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007809 HasArithmeticOrEnumeralCandidateType(
7810 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007811 CandidateTypes(CandidateTypes),
7812 CandidateSet(CandidateSet) {
Hans Wennborg82371412017-11-15 17:11:53 +00007813
7814 InitArithmeticTypes();
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 }
7816
Jan Korous536d2e32018-04-18 13:38:39 +00007817 // Increment is deprecated for bool since C++17.
7818 //
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 // C++ [over.built]p3:
7820 //
Jan Korous536d2e32018-04-18 13:38:39 +00007821 // For every pair (T, VQ), where T is an arithmetic type other
7822 // than bool, and VQ is either volatile or empty, there exist
7823 // candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007824 //
7825 // VQ T& operator++(VQ T&);
7826 // T operator++(VQ T&, int);
7827 //
7828 // C++ [over.built]p4:
7829 //
7830 // For every pair (T, VQ), where T is an arithmetic type other
7831 // than bool, and VQ is either volatile or empty, there exist
7832 // candidate operator functions of the form
7833 //
7834 // VQ T& operator--(VQ T&);
7835 // T operator--(VQ T&, int);
7836 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007837 if (!HasArithmeticOrEnumeralCandidateType)
7838 return;
7839
Jan Korousd74ebe22018-04-11 13:36:29 +00007840 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7841 const auto TypeOfT = ArithmeticTypes[Arith];
Jan Korous536d2e32018-04-18 13:38:39 +00007842 if (TypeOfT == S.Context.BoolTy) {
7843 if (Op == OO_MinusMinus)
7844 continue;
7845 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7846 continue;
7847 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 addPlusPlusMinusMinusStyleOverloads(
Jan Korousd74ebe22018-04-11 13:36:29 +00007849 TypeOfT,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007850 VisibleTypeConversionsQuals.hasVolatile(),
7851 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007852 }
7853 }
7854
7855 // C++ [over.built]p5:
7856 //
7857 // For every pair (T, VQ), where T is a cv-qualified or
7858 // cv-unqualified object type, and VQ is either volatile or
7859 // empty, there exist candidate operator functions of the form
7860 //
7861 // T*VQ& operator++(T*VQ&);
7862 // T*VQ& operator--(T*VQ&);
7863 // T* operator++(T*VQ&, int);
7864 // T* operator--(T*VQ&, int);
7865 void addPlusPlusMinusMinusPointerOverloads() {
7866 for (BuiltinCandidateTypeSet::iterator
7867 Ptr = CandidateTypes[0].pointer_begin(),
7868 PtrEnd = CandidateTypes[0].pointer_end();
7869 Ptr != PtrEnd; ++Ptr) {
7870 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007871 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 continue;
7873
7874 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007875 (!(*Ptr).isVolatileQualified() &&
7876 VisibleTypeConversionsQuals.hasVolatile()),
7877 (!(*Ptr).isRestrictQualified() &&
7878 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 }
7880 }
7881
7882 // C++ [over.built]p6:
7883 // For every cv-qualified or cv-unqualified object type T, there
7884 // exist candidate operator functions of the form
7885 //
7886 // T& operator*(T*);
7887 //
7888 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007889 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007890 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007891 // T& operator*(T*);
7892 void addUnaryStarPointerOverloads() {
7893 for (BuiltinCandidateTypeSet::iterator
7894 Ptr = CandidateTypes[0].pointer_begin(),
7895 PtrEnd = CandidateTypes[0].pointer_end();
7896 Ptr != PtrEnd; ++Ptr) {
7897 QualType ParamTy = *Ptr;
7898 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007899 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7900 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007901
Douglas Gregor02824322011-01-26 19:30:28 +00007902 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7903 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7904 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905
George Burgess IVc07c3892017-06-08 18:19:25 +00007906 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007907 }
7908 }
7909
7910 // C++ [over.built]p9:
7911 // For every promoted arithmetic type T, there exist candidate
7912 // operator functions of the form
7913 //
7914 // T operator+(T);
7915 // T operator-(T);
7916 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007917 if (!HasArithmeticOrEnumeralCandidateType)
7918 return;
7919
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 for (unsigned Arith = FirstPromotedArithmeticType;
7921 Arith < LastPromotedArithmeticType; ++Arith) {
Hans Wennborg82371412017-11-15 17:11:53 +00007922 QualType ArithTy = ArithmeticTypes[Arith];
George Burgess IVc07c3892017-06-08 18:19:25 +00007923 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 }
7925
7926 // Extension: We also add these operators for vector types.
7927 for (BuiltinCandidateTypeSet::iterator
7928 Vec = CandidateTypes[0].vector_begin(),
7929 VecEnd = CandidateTypes[0].vector_end();
7930 Vec != VecEnd; ++Vec) {
7931 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007932 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007933 }
7934 }
7935
7936 // C++ [over.built]p8:
7937 // For every type T, there exist candidate operator functions of
7938 // the form
7939 //
7940 // T* operator+(T*);
7941 void addUnaryPlusPointerOverloads() {
7942 for (BuiltinCandidateTypeSet::iterator
7943 Ptr = CandidateTypes[0].pointer_begin(),
7944 PtrEnd = CandidateTypes[0].pointer_end();
7945 Ptr != PtrEnd; ++Ptr) {
7946 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007947 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007948 }
7949 }
7950
7951 // C++ [over.built]p10:
7952 // For every promoted integral type T, there exist candidate
7953 // operator functions of the form
7954 //
7955 // T operator~(T);
7956 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007957 if (!HasArithmeticOrEnumeralCandidateType)
7958 return;
7959
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007960 for (unsigned Int = FirstPromotedIntegralType;
7961 Int < LastPromotedIntegralType; ++Int) {
Hans Wennborg82371412017-11-15 17:11:53 +00007962 QualType IntTy = ArithmeticTypes[Int];
George Burgess IVc07c3892017-06-08 18:19:25 +00007963 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007964 }
7965
7966 // Extension: We also add this operator for vector types.
7967 for (BuiltinCandidateTypeSet::iterator
7968 Vec = CandidateTypes[0].vector_begin(),
7969 VecEnd = CandidateTypes[0].vector_end();
7970 Vec != VecEnd; ++Vec) {
7971 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007972 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 }
7974 }
7975
7976 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007977 // For every pointer to member type T or type std::nullptr_t, there
7978 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 //
7980 // bool operator==(T,T);
7981 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007982 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 /// Set of (canonical) types that we've already handled.
7984 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7985
Richard Smithe54c3072013-05-05 15:51:06 +00007986 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007987 for (BuiltinCandidateTypeSet::iterator
7988 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7989 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7990 MemPtr != MemPtrEnd;
7991 ++MemPtr) {
7992 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007993 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007994 continue;
7995
7996 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007997 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007998 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007999
8000 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8001 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8002 if (AddedTypes.insert(NullPtrTy).second) {
8003 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008004 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00008005 }
8006 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 }
8008 }
8009
8010 // C++ [over.built]p15:
8011 //
Richard Smith5e9746f2016-10-21 22:00:42 +00008012 // For every T, where T is an enumeration type or a pointer type,
8013 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008014 //
8015 // bool operator<(T, T);
8016 // bool operator>(T, T);
8017 // bool operator<=(T, T);
8018 // bool operator>=(T, T);
8019 // bool operator==(T, T);
8020 // bool operator!=(T, T);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008021 // R operator<=>(T, T)
8022 void addGenericBinaryPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00008023 // C++ [over.match.oper]p3:
8024 // [...]the built-in candidates include all of the candidate operator
8025 // functions defined in 13.6 that, compared to the given operator, [...]
8026 // do not have the same parameter-type-list as any non-template non-member
8027 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008028 //
Eli Friedman14f082b2012-09-18 21:52:24 +00008029 // Note that in practice, this only affects enumeration types because there
8030 // aren't any built-in candidates of record type, and a user-defined operator
8031 // must have an operand of record or enumeration type. Also, the only other
8032 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008033 // cannot be overloaded for enumeration types, so this is the only place
8034 // where we must suppress candidates like this.
8035 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8036 UserDefinedBinaryOperators;
8037
Richard Smithe54c3072013-05-05 15:51:06 +00008038 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008039 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8040 CandidateTypes[ArgIdx].enumeration_end()) {
8041 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8042 CEnd = CandidateSet.end();
8043 C != CEnd; ++C) {
8044 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8045 continue;
8046
Eli Friedman14f082b2012-09-18 21:52:24 +00008047 if (C->Function->isFunctionTemplateSpecialization())
8048 continue;
8049
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008050 QualType FirstParamType =
8051 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8052 QualType SecondParamType =
8053 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8054
8055 // Skip if either parameter isn't of enumeral type.
8056 if (!FirstParamType->isEnumeralType() ||
8057 !SecondParamType->isEnumeralType())
8058 continue;
8059
8060 // Add this operator to the set of known user-defined operators.
8061 UserDefinedBinaryOperators.insert(
8062 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8063 S.Context.getCanonicalType(SecondParamType)));
8064 }
8065 }
8066 }
8067
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008068 /// Set of (canonical) types that we've already handled.
8069 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8070
Richard Smithe54c3072013-05-05 15:51:06 +00008071 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 for (BuiltinCandidateTypeSet::iterator
8073 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8074 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8075 Ptr != PtrEnd; ++Ptr) {
8076 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008077 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008078 continue;
8079
8080 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 }
8083 for (BuiltinCandidateTypeSet::iterator
8084 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8085 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8086 Enum != EnumEnd; ++Enum) {
8087 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8088
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008089 // Don't add the same builtin candidate twice, or if a user defined
8090 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008091 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008092 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8093 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008094 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008095 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008096 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008097 }
8098 }
8099 }
8100
8101 // C++ [over.built]p13:
8102 //
8103 // For every cv-qualified or cv-unqualified object type T
8104 // there exist candidate operator functions of the form
8105 //
8106 // T* operator+(T*, ptrdiff_t);
8107 // T& operator[](T*, ptrdiff_t); [BELOW]
8108 // T* operator-(T*, ptrdiff_t);
8109 // T* operator+(ptrdiff_t, T*);
8110 // T& operator[](ptrdiff_t, T*); [BELOW]
8111 //
8112 // C++ [over.built]p14:
8113 //
8114 // For every T, where T is a pointer to object type, there
8115 // exist candidate operator functions of the form
8116 //
8117 // ptrdiff_t operator-(T, T);
8118 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8119 /// Set of (canonical) types that we've already handled.
8120 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8121
8122 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008123 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008124 S.Context.getPointerDiffType(),
8125 S.Context.getPointerDiffType(),
8126 };
8127 for (BuiltinCandidateTypeSet::iterator
8128 Ptr = CandidateTypes[Arg].pointer_begin(),
8129 PtrEnd = CandidateTypes[Arg].pointer_end();
8130 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008131 QualType PointeeTy = (*Ptr)->getPointeeType();
8132 if (!PointeeTy->isObjectType())
8133 continue;
8134
Eric Christopher9207a522015-08-21 16:24:01 +00008135 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008136 if (Arg == 0 || Op == OO_Plus) {
8137 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8138 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008139 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008140 }
8141 if (Op == OO_Minus) {
8142 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008144 continue;
8145
8146 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008148 }
8149 }
8150 }
8151 }
8152
8153 // C++ [over.built]p12:
8154 //
8155 // For every pair of promoted arithmetic types L and R, there
8156 // exist candidate operator functions of the form
8157 //
8158 // LR operator*(L, R);
8159 // LR operator/(L, R);
8160 // LR operator+(L, R);
8161 // LR operator-(L, R);
8162 // bool operator<(L, R);
8163 // bool operator>(L, R);
8164 // bool operator<=(L, R);
8165 // bool operator>=(L, R);
8166 // bool operator==(L, R);
8167 // bool operator!=(L, R);
8168 //
8169 // where LR is the result of the usual arithmetic conversions
8170 // between types L and R.
8171 //
8172 // C++ [over.built]p24:
8173 //
8174 // For every pair of promoted arithmetic types L and R, there exist
8175 // candidate operator functions of the form
8176 //
8177 // LR operator?(bool, L, R);
8178 //
8179 // where LR is the result of the usual arithmetic conversions
8180 // between types L and R.
8181 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008182 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008183 if (!HasArithmeticOrEnumeralCandidateType)
8184 return;
8185
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008186 for (unsigned Left = FirstPromotedArithmeticType;
8187 Left < LastPromotedArithmeticType; ++Left) {
8188 for (unsigned Right = FirstPromotedArithmeticType;
8189 Right < LastPromotedArithmeticType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008190 QualType LandR[2] = { ArithmeticTypes[Left],
8191 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008192 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008193 }
8194 }
8195
8196 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8197 // conditional operator for vector types.
8198 for (BuiltinCandidateTypeSet::iterator
8199 Vec1 = CandidateTypes[0].vector_begin(),
8200 Vec1End = CandidateTypes[0].vector_end();
8201 Vec1 != Vec1End; ++Vec1) {
8202 for (BuiltinCandidateTypeSet::iterator
8203 Vec2 = CandidateTypes[1].vector_begin(),
8204 Vec2End = CandidateTypes[1].vector_end();
8205 Vec2 != Vec2End; ++Vec2) {
8206 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008207 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 }
8209 }
8210 }
8211
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008212 // C++2a [over.built]p14:
8213 //
8214 // For every integral type T there exists a candidate operator function
8215 // of the form
8216 //
8217 // std::strong_ordering operator<=>(T, T)
8218 //
8219 // C++2a [over.built]p15:
8220 //
8221 // For every pair of floating-point types L and R, there exists a candidate
8222 // operator function of the form
8223 //
8224 // std::partial_ordering operator<=>(L, R);
8225 //
8226 // FIXME: The current specification for integral types doesn't play nice with
8227 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8228 // comparisons. Under the current spec this can lead to ambiguity during
8229 // overload resolution. For example:
8230 //
8231 // enum A : int {a};
8232 // auto x = (a <=> (long)42);
8233 //
8234 // error: call is ambiguous for arguments 'A' and 'long'.
8235 // note: candidate operator<=>(int, int)
8236 // note: candidate operator<=>(long, long)
8237 //
8238 // To avoid this error, this function deviates from the specification and adds
8239 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8240 // arithmetic types (the same as the generic relational overloads).
8241 //
8242 // For now this function acts as a placeholder.
8243 void addThreeWayArithmeticOverloads() {
8244 addGenericBinaryArithmeticOverloads();
8245 }
8246
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008247 // C++ [over.built]p17:
8248 //
8249 // For every pair of promoted integral types L and R, there
8250 // exist candidate operator functions of the form
8251 //
8252 // LR operator%(L, R);
8253 // LR operator&(L, R);
8254 // LR operator^(L, R);
8255 // LR operator|(L, R);
8256 // L operator<<(L, R);
8257 // L operator>>(L, R);
8258 //
8259 // where LR is the result of the usual arithmetic conversions
8260 // between types L and R.
8261 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008262 if (!HasArithmeticOrEnumeralCandidateType)
8263 return;
8264
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008265 for (unsigned Left = FirstPromotedIntegralType;
8266 Left < LastPromotedIntegralType; ++Left) {
8267 for (unsigned Right = FirstPromotedIntegralType;
8268 Right < LastPromotedIntegralType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008269 QualType LandR[2] = { ArithmeticTypes[Left],
8270 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008271 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008272 }
8273 }
8274 }
8275
8276 // C++ [over.built]p20:
8277 //
8278 // For every pair (T, VQ), where T is an enumeration or
8279 // pointer to member type and VQ is either volatile or
8280 // empty, there exist candidate operator functions of the form
8281 //
8282 // VQ T& operator=(VQ T&, T);
8283 void addAssignmentMemberPointerOrEnumeralOverloads() {
8284 /// Set of (canonical) types that we've already handled.
8285 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8286
8287 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8288 for (BuiltinCandidateTypeSet::iterator
8289 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8290 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8291 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008292 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008293 continue;
8294
Richard Smithe54c3072013-05-05 15:51:06 +00008295 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008296 }
8297
8298 for (BuiltinCandidateTypeSet::iterator
8299 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8300 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8301 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008302 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008303 continue;
8304
Richard Smithe54c3072013-05-05 15:51:06 +00008305 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008306 }
8307 }
8308 }
8309
8310 // C++ [over.built]p19:
8311 //
8312 // For every pair (T, VQ), where T is any type and VQ is either
8313 // volatile or empty, there exist candidate operator functions
8314 // of the form
8315 //
8316 // T*VQ& operator=(T*VQ&, T*);
8317 //
8318 // C++ [over.built]p21:
8319 //
8320 // For every pair (T, VQ), where T is a cv-qualified or
8321 // cv-unqualified object type and VQ is either volatile or
8322 // empty, there exist candidate operator functions of the form
8323 //
8324 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8325 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8326 void addAssignmentPointerOverloads(bool isEqualOp) {
8327 /// Set of (canonical) types that we've already handled.
8328 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8329
8330 for (BuiltinCandidateTypeSet::iterator
8331 Ptr = CandidateTypes[0].pointer_begin(),
8332 PtrEnd = CandidateTypes[0].pointer_end();
8333 Ptr != PtrEnd; ++Ptr) {
8334 // If this is operator=, keep track of the builtin candidates we added.
8335 if (isEqualOp)
8336 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008337 else if (!(*Ptr)->getPointeeType()->isObjectType())
8338 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008339
8340 // non-volatile version
8341 QualType ParamTypes[2] = {
8342 S.Context.getLValueReferenceType(*Ptr),
8343 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8344 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 /*IsAssigmentOperator=*/ isEqualOp);
8347
Douglas Gregor5bee2582012-06-04 00:15:09 +00008348 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8349 VisibleTypeConversionsQuals.hasVolatile();
8350 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008351 // volatile version
8352 ParamTypes[0] =
8353 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008355 /*IsAssigmentOperator=*/isEqualOp);
8356 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008357
Douglas Gregor5bee2582012-06-04 00:15:09 +00008358 if (!(*Ptr).isRestrictQualified() &&
8359 VisibleTypeConversionsQuals.hasRestrict()) {
8360 // restrict version
8361 ParamTypes[0]
8362 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008363 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008364 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008365
Douglas Gregor5bee2582012-06-04 00:15:09 +00008366 if (NeedVolatile) {
8367 // volatile restrict version
8368 ParamTypes[0]
8369 = S.Context.getLValueReferenceType(
8370 S.Context.getCVRQualifiedType(*Ptr,
8371 (Qualifiers::Volatile |
8372 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008373 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008374 /*IsAssigmentOperator=*/isEqualOp);
8375 }
8376 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008377 }
8378
8379 if (isEqualOp) {
8380 for (BuiltinCandidateTypeSet::iterator
8381 Ptr = CandidateTypes[1].pointer_begin(),
8382 PtrEnd = CandidateTypes[1].pointer_end();
8383 Ptr != PtrEnd; ++Ptr) {
8384 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008385 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008386 continue;
8387
Chandler Carruth8e543b32010-12-12 08:17:55 +00008388 QualType ParamTypes[2] = {
8389 S.Context.getLValueReferenceType(*Ptr),
8390 *Ptr,
8391 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008392
8393 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008394 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008395 /*IsAssigmentOperator=*/true);
8396
Douglas Gregor5bee2582012-06-04 00:15:09 +00008397 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8398 VisibleTypeConversionsQuals.hasVolatile();
8399 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008400 // volatile version
8401 ParamTypes[0] =
8402 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008403 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008404 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008405 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008406
Douglas Gregor5bee2582012-06-04 00:15:09 +00008407 if (!(*Ptr).isRestrictQualified() &&
8408 VisibleTypeConversionsQuals.hasRestrict()) {
8409 // restrict version
8410 ParamTypes[0]
8411 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008412 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008413 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008414
Douglas Gregor5bee2582012-06-04 00:15:09 +00008415 if (NeedVolatile) {
8416 // volatile restrict version
8417 ParamTypes[0]
8418 = S.Context.getLValueReferenceType(
8419 S.Context.getCVRQualifiedType(*Ptr,
8420 (Qualifiers::Volatile |
8421 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008423 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008424 }
8425 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008426 }
8427 }
8428 }
8429
8430 // C++ [over.built]p18:
8431 //
8432 // For every triple (L, VQ, R), where L is an arithmetic type,
8433 // VQ is either volatile or empty, and R is a promoted
8434 // arithmetic type, there exist candidate operator functions of
8435 // the form
8436 //
8437 // VQ L& operator=(VQ L&, R);
8438 // VQ L& operator*=(VQ L&, R);
8439 // VQ L& operator/=(VQ L&, R);
8440 // VQ L& operator+=(VQ L&, R);
8441 // VQ L& operator-=(VQ L&, R);
8442 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008443 if (!HasArithmeticOrEnumeralCandidateType)
8444 return;
8445
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008446 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8447 for (unsigned Right = FirstPromotedArithmeticType;
8448 Right < LastPromotedArithmeticType; ++Right) {
8449 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008450 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008451
8452 // Add this built-in operator as a candidate (VQ is empty).
8453 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008454 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008455 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008456 /*IsAssigmentOperator=*/isEqualOp);
8457
8458 // Add this built-in operator as a candidate (VQ is 'volatile').
8459 if (VisibleTypeConversionsQuals.hasVolatile()) {
8460 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008461 S.Context.getVolatileType(ArithmeticTypes[Left]);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008462 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008463 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008464 /*IsAssigmentOperator=*/isEqualOp);
8465 }
8466 }
8467 }
8468
8469 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8470 for (BuiltinCandidateTypeSet::iterator
8471 Vec1 = CandidateTypes[0].vector_begin(),
8472 Vec1End = CandidateTypes[0].vector_end();
8473 Vec1 != Vec1End; ++Vec1) {
8474 for (BuiltinCandidateTypeSet::iterator
8475 Vec2 = CandidateTypes[1].vector_begin(),
8476 Vec2End = CandidateTypes[1].vector_end();
8477 Vec2 != Vec2End; ++Vec2) {
8478 QualType ParamTypes[2];
8479 ParamTypes[1] = *Vec2;
8480 // Add this built-in operator as a candidate (VQ is empty).
8481 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008482 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008483 /*IsAssigmentOperator=*/isEqualOp);
8484
8485 // Add this built-in operator as a candidate (VQ is 'volatile').
8486 if (VisibleTypeConversionsQuals.hasVolatile()) {
8487 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8488 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008490 /*IsAssigmentOperator=*/isEqualOp);
8491 }
8492 }
8493 }
8494 }
8495
8496 // C++ [over.built]p22:
8497 //
8498 // For every triple (L, VQ, R), where L is an integral type, VQ
8499 // is either volatile or empty, and R is a promoted integral
8500 // type, there exist candidate operator functions of the form
8501 //
8502 // VQ L& operator%=(VQ L&, R);
8503 // VQ L& operator<<=(VQ L&, R);
8504 // VQ L& operator>>=(VQ L&, R);
8505 // VQ L& operator&=(VQ L&, R);
8506 // VQ L& operator^=(VQ L&, R);
8507 // VQ L& operator|=(VQ L&, R);
8508 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008509 if (!HasArithmeticOrEnumeralCandidateType)
8510 return;
8511
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008512 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8513 for (unsigned Right = FirstPromotedIntegralType;
8514 Right < LastPromotedIntegralType; ++Right) {
8515 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008516 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008517
8518 // Add this built-in operator as a candidate (VQ is empty).
8519 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008520 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008521 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008522 if (VisibleTypeConversionsQuals.hasVolatile()) {
8523 // Add this built-in operator as a candidate (VQ is 'volatile').
Hans Wennborg82371412017-11-15 17:11:53 +00008524 ParamTypes[0] = ArithmeticTypes[Left];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008525 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8526 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008527 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008528 }
8529 }
8530 }
8531 }
8532
8533 // C++ [over.operator]p23:
8534 //
8535 // There also exist candidate operator functions of the form
8536 //
8537 // bool operator!(bool);
8538 // bool operator&&(bool, bool);
8539 // bool operator||(bool, bool);
8540 void addExclaimOverload() {
8541 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008542 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008543 /*IsAssignmentOperator=*/false,
8544 /*NumContextualBoolArguments=*/1);
8545 }
8546 void addAmpAmpOrPipePipeOverload() {
8547 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008548 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008549 /*IsAssignmentOperator=*/false,
8550 /*NumContextualBoolArguments=*/2);
8551 }
8552
8553 // C++ [over.built]p13:
8554 //
8555 // For every cv-qualified or cv-unqualified object type T there
8556 // exist candidate operator functions of the form
8557 //
8558 // T* operator+(T*, ptrdiff_t); [ABOVE]
8559 // T& operator[](T*, ptrdiff_t);
8560 // T* operator-(T*, ptrdiff_t); [ABOVE]
8561 // T* operator+(ptrdiff_t, T*); [ABOVE]
8562 // T& operator[](ptrdiff_t, T*);
8563 void addSubscriptOverloads() {
8564 for (BuiltinCandidateTypeSet::iterator
8565 Ptr = CandidateTypes[0].pointer_begin(),
8566 PtrEnd = CandidateTypes[0].pointer_end();
8567 Ptr != PtrEnd; ++Ptr) {
8568 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8569 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008570 if (!PointeeType->isObjectType())
8571 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008572
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008573 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008574 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008575 }
8576
8577 for (BuiltinCandidateTypeSet::iterator
8578 Ptr = CandidateTypes[1].pointer_begin(),
8579 PtrEnd = CandidateTypes[1].pointer_end();
8580 Ptr != PtrEnd; ++Ptr) {
8581 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8582 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008583 if (!PointeeType->isObjectType())
8584 continue;
8585
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008586 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008587 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008588 }
8589 }
8590
8591 // C++ [over.built]p11:
8592 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8593 // C1 is the same type as C2 or is a derived class of C2, T is an object
8594 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8595 // there exist candidate operator functions of the form
8596 //
8597 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8598 //
8599 // where CV12 is the union of CV1 and CV2.
8600 void addArrowStarOverloads() {
8601 for (BuiltinCandidateTypeSet::iterator
8602 Ptr = CandidateTypes[0].pointer_begin(),
8603 PtrEnd = CandidateTypes[0].pointer_end();
8604 Ptr != PtrEnd; ++Ptr) {
8605 QualType C1Ty = (*Ptr);
8606 QualType C1;
8607 QualifierCollector Q1;
8608 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8609 if (!isa<RecordType>(C1))
8610 continue;
8611 // heuristic to reduce number of builtin candidates in the set.
8612 // Add volatile/restrict version only if there are conversions to a
8613 // volatile/restrict type.
8614 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8615 continue;
8616 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8617 continue;
8618 for (BuiltinCandidateTypeSet::iterator
8619 MemPtr = CandidateTypes[1].member_pointer_begin(),
8620 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8621 MemPtr != MemPtrEnd; ++MemPtr) {
8622 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8623 QualType C2 = QualType(mptr->getClass(), 0);
8624 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008625 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008626 break;
8627 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8628 // build CV12 T&
8629 QualType T = mptr->getPointeeType();
8630 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8631 T.isVolatileQualified())
8632 continue;
8633 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8634 T.isRestrictQualified())
8635 continue;
8636 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008638 }
8639 }
8640 }
8641
8642 // Note that we don't consider the first argument, since it has been
8643 // contextually converted to bool long ago. The candidates below are
8644 // therefore added as binary.
8645 //
8646 // C++ [over.built]p25:
8647 // For every type T, where T is a pointer, pointer-to-member, or scoped
8648 // enumeration type, there exist candidate operator functions of the form
8649 //
8650 // T operator?(bool, T, T);
8651 //
8652 void addConditionalOperatorOverloads() {
8653 /// Set of (canonical) types that we've already handled.
8654 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8655
8656 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8657 for (BuiltinCandidateTypeSet::iterator
8658 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8659 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8660 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008661 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008662 continue;
8663
8664 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008665 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008666 }
8667
8668 for (BuiltinCandidateTypeSet::iterator
8669 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8670 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8671 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008672 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008673 continue;
8674
8675 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008676 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008677 }
8678
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008679 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008680 for (BuiltinCandidateTypeSet::iterator
8681 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8682 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8683 Enum != EnumEnd; ++Enum) {
8684 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8685 continue;
8686
David Blaikie82e95a32014-11-19 07:49:47 +00008687 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008688 continue;
8689
8690 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008691 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008692 }
8693 }
8694 }
8695 }
8696};
8697
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008698} // end anonymous namespace
8699
8700/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8701/// operator overloads to the candidate set (C++ [over.built]), based
8702/// on the operator @p Op and the arguments given. For example, if the
8703/// operator is a binary '+', this routine might add "int
8704/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008705void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8706 SourceLocation OpLoc,
8707 ArrayRef<Expr *> Args,
8708 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008709 // Find all of the types that the arguments can convert to, but only
8710 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008711 // that make use of these types. Also record whether we encounter non-record
8712 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008713 Qualifiers VisibleTypeConversionsQuals;
8714 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008715 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008716 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008717
8718 bool HasNonRecordCandidateType = false;
8719 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008720 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008721 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008722 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008723 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8724 OpLoc,
8725 true,
8726 (Op == OO_Exclaim ||
8727 Op == OO_AmpAmp ||
8728 Op == OO_PipePipe),
8729 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008730 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8731 CandidateTypes[ArgIdx].hasNonRecordTypes();
8732 HasArithmeticOrEnumeralCandidateType =
8733 HasArithmeticOrEnumeralCandidateType ||
8734 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008735 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008736
Chandler Carruth00a38332010-12-13 01:44:01 +00008737 // Exit early when no non-record types have been added to the candidate set
8738 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008739 //
8740 // We can't exit early for !, ||, or &&, since there we have always have
8741 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008742 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008743 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008744 return;
8745
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008746 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008747 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008748 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008749 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008750 CandidateTypes, CandidateSet);
8751
8752 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008753 switch (Op) {
8754 case OO_None:
8755 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008756 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008757
Chandler Carruth5184de02010-12-12 08:51:33 +00008758 case OO_New:
8759 case OO_Delete:
8760 case OO_Array_New:
8761 case OO_Array_Delete:
8762 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008763 llvm_unreachable(
8764 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008765
8766 case OO_Comma:
8767 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008768 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008769 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008770 // -- For the operator ',', the unary operator '&', the
8771 // operator '->', or the operator 'co_await', the
8772 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008773 break;
8774
8775 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008776 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008777 OpBuilder.addUnaryPlusPointerOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008778 LLVM_FALLTHROUGH;
Douglas Gregord08452f2008-11-19 15:42:04 +00008779
8780 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008781 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008782 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008783 } else {
8784 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008785 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008786 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008787 break;
8788
Chandler Carruth5184de02010-12-12 08:51:33 +00008789 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008790 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008791 OpBuilder.addUnaryStarPointerOverloads();
8792 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008793 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008794 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008795
Chandler Carruth5184de02010-12-12 08:51:33 +00008796 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008797 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008798 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008799
8800 case OO_PlusPlus:
8801 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008802 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8803 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008804 break;
8805
Douglas Gregor84605ae2009-08-24 13:43:27 +00008806 case OO_EqualEqual:
8807 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008808 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008809 LLVM_FALLTHROUGH;
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008810
Douglas Gregora11693b2008-11-12 17:17:38 +00008811 case OO_Less:
8812 case OO_Greater:
8813 case OO_LessEqual:
8814 case OO_GreaterEqual:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008815 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008816 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008817 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008818
Richard Smithd30b23d2017-12-01 02:13:10 +00008819 case OO_Spaceship:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008820 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8821 OpBuilder.addThreeWayArithmeticOverloads();
8822 break;
Richard Smithd30b23d2017-12-01 02:13:10 +00008823
Douglas Gregora11693b2008-11-12 17:17:38 +00008824 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008825 case OO_Caret:
8826 case OO_Pipe:
8827 case OO_LessLess:
8828 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008829 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008830 break;
8831
Chandler Carruth5184de02010-12-12 08:51:33 +00008832 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008833 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008834 // C++ [over.match.oper]p3:
8835 // -- For the operator ',', the unary operator '&', or the
8836 // operator '->', the built-in candidates set is empty.
8837 break;
8838
8839 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8840 break;
8841
8842 case OO_Tilde:
8843 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8844 break;
8845
Douglas Gregora11693b2008-11-12 17:17:38 +00008846 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008847 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008848 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008849
8850 case OO_PlusEqual:
8851 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008852 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008853 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008854
8855 case OO_StarEqual:
8856 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008857 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008858 break;
8859
8860 case OO_PercentEqual:
8861 case OO_LessLessEqual:
8862 case OO_GreaterGreaterEqual:
8863 case OO_AmpEqual:
8864 case OO_CaretEqual:
8865 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008866 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008867 break;
8868
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008869 case OO_Exclaim:
8870 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008871 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008872
Douglas Gregora11693b2008-11-12 17:17:38 +00008873 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008874 case OO_PipePipe:
8875 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008876 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008877
8878 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008879 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008880 break;
8881
8882 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008883 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008884 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008885
8886 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008887 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008888 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008889 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008890 }
8891}
8892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008893/// Add function candidates found via argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00008894/// to the set of overloading candidates.
8895///
8896/// This routine performs argument-dependent name lookup based on the
8897/// given function name (which may also be an operator name) and adds
8898/// all of the overload candidates found by ADL to the overload
8899/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008900void
Douglas Gregore254f902009-02-04 00:32:51 +00008901Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008902 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008903 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008904 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008905 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008906 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008907 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008908
John McCall91f61fc2010-01-26 06:04:06 +00008909 // FIXME: This approach for uniquing ADL results (and removing
8910 // redundant candidates from the set) relies on pointer-equality,
8911 // which means we need to key off the canonical decl. However,
8912 // always going back to the canonical decl might not get us the
8913 // right set of default arguments. What default arguments are
8914 // we supposed to consider on ADL candidates, anyway?
8915
Douglas Gregorcabea402009-09-22 15:41:20 +00008916 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008917 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008918
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008919 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008920 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8921 CandEnd = CandidateSet.end();
8922 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008923 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008924 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008925 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008926 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008927 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008928
8929 // For each of the ADL candidates we found, add it to the overload
8930 // set.
John McCall8fe68082010-01-26 07:16:45 +00008931 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008932 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008933 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008934 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008935 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008936
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008937 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8938 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008939 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008940 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008941 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008942 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008943 }
Douglas Gregore254f902009-02-04 00:32:51 +00008944}
8945
George Burgess IV3dc166912016-05-10 01:59:34 +00008946namespace {
8947enum class Comparison { Equal, Better, Worse };
8948}
8949
8950/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8951/// overload resolution.
8952///
8953/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8954/// Cand1's first N enable_if attributes have precisely the same conditions as
8955/// Cand2's first N enable_if attributes (where N = the number of enable_if
8956/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8957///
8958/// Note that you can have a pair of candidates such that Cand1's enable_if
8959/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8960/// worse than Cand1's.
8961static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8962 const FunctionDecl *Cand2) {
8963 // Common case: One (or both) decls don't have enable_if attrs.
8964 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8965 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8966 if (!Cand1Attr || !Cand2Attr) {
8967 if (Cand1Attr == Cand2Attr)
8968 return Comparison::Equal;
8969 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8970 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008971
Michael Krusedc5ce722018-08-03 01:21:16 +00008972 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8973 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
George Burgess IV2a6150d2015-10-16 01:17:38 +00008974
8975 auto Cand1I = Cand1Attrs.begin();
8976 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Michael Krusedc5ce722018-08-03 01:21:16 +00008977 for (EnableIfAttr *Cand2A : Cand2Attrs) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00008978 Cand1ID.clear();
8979 Cand2ID.clear();
8980
Michael Krusedc5ce722018-08-03 01:21:16 +00008981 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8982 // has fewer enable_if attributes than Cand2.
8983 auto Cand1A = Cand1I++;
8984 if (Cand1A == Cand1Attrs.end())
8985 return Comparison::Worse;
8986
George Burgess IV2a6150d2015-10-16 01:17:38 +00008987 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8988 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8989 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008990 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008991 }
8992
George Burgess IV3dc166912016-05-10 01:59:34 +00008993 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008994}
8995
Erich Keane3efe0022018-07-20 14:13:28 +00008996static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8997 const OverloadCandidate &Cand2) {
8998 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
8999 !Cand2.Function->isMultiVersion())
9000 return false;
9001
9002 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9003 // cpu_dispatch, else arbitrarily based on the identifiers.
9004 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9005 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9006 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9007 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9008
9009 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9010 return false;
9011
9012 if (Cand1CPUDisp && !Cand2CPUDisp)
9013 return true;
9014 if (Cand2CPUDisp && !Cand1CPUDisp)
9015 return false;
9016
9017 if (Cand1CPUSpec && Cand2CPUSpec) {
9018 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9019 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9020
9021 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9022 FirstDiff = std::mismatch(
9023 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9024 Cand2CPUSpec->cpus_begin(),
9025 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9026 return LHS->getName() == RHS->getName();
9027 });
9028
9029 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9030 "Two different cpu-specific versions should not have the same "
9031 "identifier list, otherwise they'd be the same decl!");
9032 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9033 }
9034 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9035}
9036
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009037/// isBetterOverloadCandidate - Determines whether the first overload
9038/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00009039bool clang::isBetterOverloadCandidate(
9040 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9041 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009042 // Define viable functions to be better candidates than non-viable
9043 // functions.
9044 if (!Cand2.Viable)
9045 return Cand1.Viable;
9046 else if (!Cand1.Viable)
9047 return false;
9048
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009049 // C++ [over.match.best]p1:
9050 //
9051 // -- if F is a static member function, ICS1(F) is defined such
9052 // that ICS1(F) is neither better nor worse than ICS1(G) for
9053 // any function G, and, symmetrically, ICS1(G) is neither
9054 // better nor worse than ICS1(F).
9055 unsigned StartArg = 0;
9056 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9057 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009058
George Burgess IVfbad5b22016-09-07 20:03:19 +00009059 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9060 // We don't allow incompatible pointer conversions in C++.
9061 if (!S.getLangOpts().CPlusPlus)
9062 return ICS.isStandard() &&
9063 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9064
9065 // The only ill-formed conversion we allow in C++ is the string literal to
9066 // char* conversion, which is only considered ill-formed after C++11.
9067 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9068 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9069 };
9070
9071 // Define functions that don't require ill-formed conversions for a given
9072 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00009073 unsigned NumArgs = Cand1.Conversions.size();
9074 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00009075 bool HasBetterConversion = false;
9076 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9077 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9078 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9079 if (Cand1Bad != Cand2Bad) {
9080 if (Cand1Bad)
9081 return false;
9082 HasBetterConversion = true;
9083 }
9084 }
9085
9086 if (HasBetterConversion)
9087 return true;
9088
Douglas Gregord3cb3562009-07-07 23:38:56 +00009089 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00009090 // A viable function F1 is defined to be a better function than another
9091 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00009092 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009093 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009094 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009095 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009096 Cand2.Conversions[ArgIdx])) {
9097 case ImplicitConversionSequence::Better:
9098 // Cand1 has a better conversion sequence.
9099 HasBetterConversion = true;
9100 break;
9101
9102 case ImplicitConversionSequence::Worse:
9103 // Cand1 can't be better than Cand2.
9104 return false;
9105
9106 case ImplicitConversionSequence::Indistinguishable:
9107 // Do nothing.
9108 break;
9109 }
9110 }
9111
Mike Stump11289f42009-09-09 15:08:12 +00009112 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00009113 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009114 if (HasBetterConversion)
9115 return true;
9116
Douglas Gregora1f013e2008-11-07 22:36:19 +00009117 // -- the context is an initialization by user-defined conversion
9118 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9119 // from the return type of F1 to the destination type (i.e.,
9120 // the type of the entity being initialized) is a better
9121 // conversion sequence than the standard conversion sequence
9122 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00009123 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9124 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009125 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009126 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009127 // First check whether we prefer one of the conversion functions over the
9128 // other. This only distinguishes the results in non-standard, extension
9129 // cases such as the conversion from a lambda closure type to a function
9130 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009131 ImplicitConversionSequence::CompareKind Result =
9132 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9133 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009134 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009135 Cand1.FinalConversion,
9136 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009137
Richard Smithec2748a2014-05-17 04:36:39 +00009138 if (Result != ImplicitConversionSequence::Indistinguishable)
9139 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009140
9141 // FIXME: Compare kind of reference binding if conversion functions
9142 // convert to a reference type used in direct reference binding, per
9143 // C++14 [over.match.best]p1 section 2 bullet 3.
9144 }
9145
Richard Smith51731362017-11-01 01:37:11 +00009146 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9147 // as combined with the resolution to CWG issue 243.
9148 //
9149 // When the context is initialization by constructor ([over.match.ctor] or
9150 // either phase of [over.match.list]), a constructor is preferred over
9151 // a conversion function.
9152 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9153 Cand1.Function && Cand2.Function &&
9154 isa<CXXConstructorDecl>(Cand1.Function) !=
9155 isa<CXXConstructorDecl>(Cand2.Function))
9156 return isa<CXXConstructorDecl>(Cand1.Function);
9157
Richard Smith6fdeaab2014-05-17 01:58:45 +00009158 // -- F1 is a non-template function and F2 is a function template
9159 // specialization, or, if not that,
9160 bool Cand1IsSpecialization = Cand1.Function &&
9161 Cand1.Function->getPrimaryTemplate();
9162 bool Cand2IsSpecialization = Cand2.Function &&
9163 Cand2.Function->getPrimaryTemplate();
9164 if (Cand1IsSpecialization != Cand2IsSpecialization)
9165 return Cand2IsSpecialization;
9166
9167 // -- F1 and F2 are function template specializations, and the function
9168 // template for F1 is more specialized than the template for F2
9169 // according to the partial ordering rules described in 14.5.5.2, or,
9170 // if not that,
9171 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9172 if (FunctionTemplateDecl *BetterTemplate
9173 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9174 Cand2.Function->getPrimaryTemplate(),
9175 Loc,
9176 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9177 : TPOC_Call,
9178 Cand1.ExplicitCallArguments,
9179 Cand2.ExplicitCallArguments))
9180 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009181 }
9182
Richard Smith5179eb72016-06-28 19:03:57 +00009183 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9184 // A derived-class constructor beats an (inherited) base class constructor.
9185 bool Cand1IsInherited =
9186 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9187 bool Cand2IsInherited =
9188 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9189 if (Cand1IsInherited != Cand2IsInherited)
9190 return Cand2IsInherited;
9191 else if (Cand1IsInherited) {
9192 assert(Cand2IsInherited);
9193 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9194 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9195 if (Cand1Class->isDerivedFrom(Cand2Class))
9196 return true;
9197 if (Cand2Class->isDerivedFrom(Cand1Class))
9198 return false;
9199 // Inherited from sibling base classes: still ambiguous.
9200 }
9201
Faisal Vali81b756e2017-10-22 14:45:08 +00009202 // Check C++17 tie-breakers for deduction guides.
9203 {
9204 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9205 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9206 if (Guide1 && Guide2) {
9207 // -- F1 is generated from a deduction-guide and F2 is not
9208 if (Guide1->isImplicit() != Guide2->isImplicit())
9209 return Guide2->isImplicit();
9210
9211 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9212 if (Guide1->isCopyDeductionCandidate())
9213 return true;
9214 }
9215 }
Richard Smith67ef14f2017-09-26 18:37:55 +00009216
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009217 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009218 if (Cand1.Function && Cand2.Function) {
9219 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9220 if (Cmp != Comparison::Equal)
9221 return Cmp == Comparison::Better;
9222 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009223
Justin Lebar25c4a812016-03-29 16:24:16 +00009224 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009225 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9226 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9227 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9228 }
9229
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009230 bool HasPS1 = Cand1.Function != nullptr &&
9231 functionHasPassObjectSizeParams(Cand1.Function);
9232 bool HasPS2 = Cand2.Function != nullptr &&
9233 functionHasPassObjectSizeParams(Cand2.Function);
Erich Keane3efe0022018-07-20 14:13:28 +00009234 if (HasPS1 != HasPS2 && HasPS1)
9235 return true;
9236
9237 return isBetterMultiversionCandidate(Cand1, Cand2);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009238}
9239
Richard Smith2dbe4042015-11-04 19:26:32 +00009240/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009241/// name lookup and overload resolution. This applies when the same internal/no
9242/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009243/// the same header). In such a case, we don't consider the declarations to
9244/// declare the same entity, but we also don't want lookups with both
9245/// declarations visible to be ambiguous in some cases (this happens when using
9246/// a modularized libstdc++).
9247bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9248 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009249 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9250 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9251 if (!VA || !VB)
9252 return false;
9253
9254 // The declarations must be declaring the same name as an internal linkage
9255 // entity in different modules.
9256 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9257 VB->getDeclContext()->getRedeclContext()) ||
9258 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9259 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9260 VA->isExternallyVisible() || VB->isExternallyVisible())
9261 return false;
9262
9263 // Check that the declarations appear to be equivalent.
9264 //
9265 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9266 // For constants and functions, we should check the initializer or body is
9267 // the same. For non-constant variables, we shouldn't allow it at all.
9268 if (Context.hasSameType(VA->getType(), VB->getType()))
9269 return true;
9270
9271 // Enum constants within unnamed enumerations will have different types, but
9272 // may still be similar enough to be interchangeable for our purposes.
9273 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9274 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9275 // Only handle anonymous enums. If the enumerations were named and
9276 // equivalent, they would have been merged to the same type.
9277 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9278 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9279 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9280 !Context.hasSameType(EnumA->getIntegerType(),
9281 EnumB->getIntegerType()))
9282 return false;
9283 // Allow this only if the value is the same for both enumerators.
9284 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9285 }
9286 }
9287
9288 // Nothing else is sufficiently similar.
9289 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009290}
9291
9292void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9293 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9294 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9295
9296 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9297 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9298 << !M << (M ? M->getFullModuleName() : "");
9299
9300 for (auto *E : Equiv) {
9301 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9302 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9303 << !M << (M ? M->getFullModuleName() : "");
9304 }
Richard Smith896c66e2015-10-21 07:13:52 +00009305}
9306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009307/// Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009308/// within an overload candidate set.
9309///
James Dennettffad8b72012-06-22 08:10:18 +00009310/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009311/// which overload resolution occurs.
9312///
James Dennettffad8b72012-06-22 08:10:18 +00009313/// \param Best If overload resolution was successful or found a deleted
9314/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009315///
9316/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009317OverloadingResult
9318OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009319 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009320 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9321 std::transform(begin(), end(), std::back_inserter(Candidates),
9322 [](OverloadCandidate &Cand) { return &Cand; });
9323
Justin Lebar66a2ab92016-08-10 00:40:43 +00009324 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9325 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009326 // compilation mode only one call variant is viable. We need to
9327 // exclude non-viable overload candidates from consideration based
9328 // only on their host/device attributes. Specifically, if one
9329 // candidate call is WrongSide and the other is SameSide, we ignore
9330 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009331 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009332 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9333 bool ContainsSameSideCandidate =
9334 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9335 return Cand->Function &&
9336 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9337 Sema::CFP_SameSide;
9338 });
9339 if (ContainsSameSideCandidate) {
9340 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9341 return Cand->Function &&
9342 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9343 Sema::CFP_WrongSide;
9344 };
George Burgess IV8684b032017-01-04 19:16:29 +00009345 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009346 }
9347 }
9348
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009349 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009350 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009351 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009352 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009353 if (Best == end() ||
9354 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009355 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009356
9357 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009358 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009359 return OR_No_Viable_Function;
9360
Richard Smith2dbe4042015-11-04 19:26:32 +00009361 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009362
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009363 // Make sure that this function is better than every other viable
9364 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009365 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009366 if (Cand->Viable && Cand != Best &&
9367 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009368 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9369 Cand->Function)) {
9370 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009371 continue;
9372 }
9373
John McCall5c32be02010-08-24 20:38:10 +00009374 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009375 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009376 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009377 }
Mike Stump11289f42009-09-09 15:08:12 +00009378
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009379 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009380 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009381 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009382 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009383 return OR_Deleted;
9384
Richard Smith2dbe4042015-11-04 19:26:32 +00009385 if (!EquivalentCands.empty())
9386 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9387 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009388
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009389 return OR_Success;
9390}
9391
John McCall53262c92010-01-12 02:15:36 +00009392namespace {
9393
9394enum OverloadCandidateKind {
9395 oc_function,
9396 oc_method,
9397 oc_constructor,
9398 oc_implicit_default_constructor,
9399 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009400 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009401 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009402 oc_implicit_move_assignment,
Eric Fiselier92e523b2018-05-30 01:00:41 +00009403 oc_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00009404};
9405
Eric Fiselier92e523b2018-05-30 01:00:41 +00009406enum OverloadCandidateSelect {
9407 ocs_non_template,
9408 ocs_template,
9409 ocs_described_template,
9410};
9411
9412static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
George Burgess IVd66d37c2016-10-28 21:42:06 +00009413ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9414 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009415
Eric Fiselier92e523b2018-05-30 01:00:41 +00009416 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
John McCalle1ac8d12010-01-13 00:25:19 +00009417 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9418 isTemplate = true;
9419 Description = S.getTemplateArgumentBindingsText(
Eric Fiselier92e523b2018-05-30 01:00:41 +00009420 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
John McCalle1ac8d12010-01-13 00:25:19 +00009421 }
John McCallfd0b2f82010-01-06 09:43:14 +00009422
Eric Fiselier92e523b2018-05-30 01:00:41 +00009423 OverloadCandidateSelect Select = [&]() {
9424 if (!Description.empty())
9425 return ocs_described_template;
9426 return isTemplate ? ocs_template : ocs_non_template;
9427 }();
9428
9429 OverloadCandidateKind Kind = [&]() {
9430 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9431 if (!Ctor->isImplicit()) {
9432 if (isa<ConstructorUsingShadowDecl>(Found))
9433 return oc_inherited_constructor;
9434 else
9435 return oc_constructor;
9436 }
9437
9438 if (Ctor->isDefaultConstructor())
9439 return oc_implicit_default_constructor;
9440
9441 if (Ctor->isMoveConstructor())
9442 return oc_implicit_move_constructor;
9443
9444 assert(Ctor->isCopyConstructor() &&
9445 "unexpected sort of implicit constructor");
9446 return oc_implicit_copy_constructor;
Richard Smith5179eb72016-06-28 19:03:57 +00009447 }
Sebastian Redl08905022011-02-05 19:23:19 +00009448
Eric Fiselier92e523b2018-05-30 01:00:41 +00009449 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9450 // This actually gets spelled 'candidate function' for now, but
9451 // it doesn't hurt to split it out.
9452 if (!Meth->isImplicit())
9453 return oc_method;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009454
Eric Fiselier92e523b2018-05-30 01:00:41 +00009455 if (Meth->isMoveAssignmentOperator())
9456 return oc_implicit_move_assignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009457
Eric Fiselier92e523b2018-05-30 01:00:41 +00009458 if (Meth->isCopyAssignmentOperator())
9459 return oc_implicit_copy_assignment;
John McCallfd0b2f82010-01-06 09:43:14 +00009460
Eric Fiselier92e523b2018-05-30 01:00:41 +00009461 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9462 return oc_method;
9463 }
John McCallfd0b2f82010-01-06 09:43:14 +00009464
Eric Fiselier92e523b2018-05-30 01:00:41 +00009465 return oc_function;
9466 }();
Alexis Hunt119c10e2011-05-25 23:16:36 +00009467
Eric Fiselier92e523b2018-05-30 01:00:41 +00009468 return std::make_pair(Kind, Select);
John McCall53262c92010-01-12 02:15:36 +00009469}
9470
Richard Smith5179eb72016-06-28 19:03:57 +00009471void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9472 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9473 // set.
9474 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9475 S.Diag(FoundDecl->getLocation(),
9476 diag::note_ovl_candidate_inherited_constructor)
9477 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009478}
9479
John McCall53262c92010-01-12 02:15:36 +00009480} // end anonymous namespace
9481
George Burgess IV5f21c712015-10-12 19:57:04 +00009482static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9483 const FunctionDecl *FD) {
9484 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9485 bool AlwaysTrue;
9486 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9487 return false;
9488 if (!AlwaysTrue)
9489 return false;
9490 }
9491 return true;
9492}
9493
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009494/// Returns true if we can take the address of the function.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009495///
9496/// \param Complain - If true, we'll emit a diagnostic
9497/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9498/// we in overload resolution?
9499/// \param Loc - The location of the statement we're complaining about. Ignored
9500/// if we're not complaining, or if we're in overload resolution.
9501static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9502 bool Complain,
9503 bool InOverloadResolution,
9504 SourceLocation Loc) {
9505 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9506 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009507 if (InOverloadResolution)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009508 S.Diag(FD->getBeginLoc(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009509 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9510 else
9511 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9512 }
9513 return false;
9514 }
9515
George Burgess IV21081362016-07-24 23:12:40 +00009516 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9517 return P->hasAttr<PassObjectSizeAttr>();
9518 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009519 if (I == FD->param_end())
9520 return true;
9521
9522 if (Complain) {
9523 // Add one to ParamNo because it's user-facing
9524 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9525 if (InOverloadResolution)
9526 S.Diag(FD->getLocation(),
9527 diag::note_ovl_candidate_has_pass_object_size_params)
9528 << ParamNo;
9529 else
9530 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9531 << FD << ParamNo;
9532 }
9533 return false;
9534}
9535
9536static bool checkAddressOfCandidateIsAvailable(Sema &S,
9537 const FunctionDecl *FD) {
9538 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9539 /*InOverloadResolution=*/true,
9540 /*Loc=*/SourceLocation());
9541}
9542
9543bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9544 bool Complain,
9545 SourceLocation Loc) {
9546 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9547 /*InOverloadResolution=*/false,
9548 Loc);
9549}
9550
John McCall53262c92010-01-12 02:15:36 +00009551// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009552void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9553 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009554 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9555 return;
Erich Keane3efe0022018-07-20 14:13:28 +00009556 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9557 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +00009558 return;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009559
John McCalle1ac8d12010-01-13 00:25:19 +00009560 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009561 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9562 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009563 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009564 << (unsigned)KSPair.first << (unsigned)KSPair.second
9565 << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009566
9567 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009568 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009569 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009570}
9571
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009572// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009573// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009574void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9575 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009576 assert(OverloadedExpr->getType() == Context.OverloadTy);
9577
9578 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9579 OverloadExpr *OvlExpr = Ovl.Expression;
9580
9581 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009582 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009583 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009584 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009585 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009586 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009587 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009588 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009589 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009590 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009591 }
9592 }
9593}
9594
John McCall0d1da222010-01-12 00:44:57 +00009595/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9596/// "lead" diagnostic; it will be given two arguments, the source and
9597/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009598void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9599 Sema &S,
9600 SourceLocation CaretLoc,
9601 const PartialDiagnostic &PDiag) const {
9602 S.Diag(CaretLoc, PDiag)
9603 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009604 // FIXME: The note limiting machinery is borrowed from
9605 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9606 // refactoring here.
9607 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9608 unsigned CandsShown = 0;
9609 AmbiguousConversionSequence::const_iterator I, E;
9610 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9611 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9612 break;
9613 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009614 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009615 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009616 if (I != E)
9617 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009618}
9619
Richard Smith17c00b42014-11-12 01:24:00 +00009620static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009621 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009622 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9623 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009624 assert(Cand->Function && "for now, candidate must be a function");
9625 FunctionDecl *Fn = Cand->Function;
9626
9627 // There's a conversion slot for the object argument if this is a
9628 // non-constructor method. Note that 'I' corresponds the
9629 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009630 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009631 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009632 if (I == 0)
9633 isObjectArgument = true;
9634 else
9635 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009636 }
9637
John McCalle1ac8d12010-01-13 00:25:19 +00009638 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009639 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009640 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009641
John McCall6a61b522010-01-13 09:16:55 +00009642 Expr *FromExpr = Conv.Bad.FromExpr;
9643 QualType FromTy = Conv.Bad.getFromType();
9644 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009645
John McCallfb7ad0f2010-02-02 02:42:52 +00009646 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009647 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009648 Expr *E = FromExpr->IgnoreParens();
9649 if (isa<UnaryOperator>(E))
9650 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009651 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009652
9653 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009654 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9655 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9656 << Name << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009657 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009658 return;
9659 }
9660
John McCall6d174642010-01-23 08:10:49 +00009661 // Do some hand-waving analysis to see if the non-viability is due
9662 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009663 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9664 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9665 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9666 CToTy = RT->getPointeeType();
9667 else {
9668 // TODO: detect and diagnose the full richness of const mismatches.
9669 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009670 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9671 CFromTy = FromPT->getPointeeType();
9672 CToTy = ToPT->getPointeeType();
9673 }
John McCall47000992010-01-14 03:28:57 +00009674 }
9675
9676 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9677 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009678 Qualifiers FromQs = CFromTy.getQualifiers();
9679 Qualifiers ToQs = CToTy.getQualifiers();
9680
9681 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009683 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
Anastasia Stulovabf549bf2018-06-22 15:45:08 +00009685 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009687 return;
9688 }
9689
John McCall31168b02011-06-15 23:02:42 +00009690 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009692 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9694 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9695 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009696 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009697 return;
9698 }
9699
Douglas Gregoraec25842011-04-26 23:16:46 +00009700 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009702 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9704 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9705 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009706 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009707 return;
9708 }
9709
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009710 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9711 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009712 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9713 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9714 << FromQs.hasUnaligned() << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009716 return;
9717 }
9718
John McCall47000992010-01-14 03:28:57 +00009719 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9720 assert(CVR && "unexpected qualifiers mismatch");
9721
9722 if (isObjectArgument) {
9723 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009724 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9725 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9726 << (CVR - 1);
John McCall47000992010-01-14 03:28:57 +00009727 } else {
9728 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009729 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9730 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9731 << (CVR - 1) << I + 1;
John McCall47000992010-01-14 03:28:57 +00009732 }
Richard Smith5179eb72016-06-28 19:03:57 +00009733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009734 return;
9735 }
9736
Sebastian Redla72462c2011-09-24 17:48:32 +00009737 // Special diagnostic for failure to convert an initializer list, since
9738 // telling the user that it has type void is not useful.
9739 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009741 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9743 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009744 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009745 return;
9746 }
9747
John McCall6d174642010-01-23 08:10:49 +00009748 // Diagnose references or pointers to incomplete types differently,
9749 // since it's far from impossible that the incompleteness triggered
9750 // the failure.
9751 QualType TempFromTy = FromTy.getNonReferenceType();
9752 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9753 TempFromTy = PTy->getPointeeType();
9754 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009755 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009757 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9758 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9759 << ToTy << (unsigned)isObjectArgument << I + 1
9760 << (unsigned)(Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009761
Richard Smith5179eb72016-06-28 19:03:57 +00009762 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009763 return;
9764 }
9765
Douglas Gregor56f2e342010-06-30 23:01:39 +00009766 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009767 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009768 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9769 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9770 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9771 FromPtrTy->getPointeeType()) &&
9772 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9773 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009774 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009775 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009776 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009777 }
9778 } else if (const ObjCObjectPointerType *FromPtrTy
9779 = FromTy->getAs<ObjCObjectPointerType>()) {
9780 if (const ObjCObjectPointerType *ToPtrTy
9781 = ToTy->getAs<ObjCObjectPointerType>())
9782 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9783 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9784 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9785 FromPtrTy->getPointeeType()) &&
9786 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009787 BaseToDerivedConversion = 2;
9788 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009789 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9790 !FromTy->isIncompleteType() &&
9791 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009792 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009793 BaseToDerivedConversion = 3;
9794 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9795 ToTy.getNonReferenceType().getCanonicalType() ==
9796 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009797 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009798 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9799 << (unsigned)isObjectArgument << I + 1
9800 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
Richard Smith5179eb72016-06-28 19:03:57 +00009801 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009802 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009803 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009805
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009806 if (BaseToDerivedConversion) {
Eric Fiselier92e523b2018-05-30 01:00:41 +00009807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9808 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9809 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9810 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009811 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009812 return;
9813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009814
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009815 if (isa<ObjCObjectPointerType>(CFromTy) &&
9816 isa<PointerType>(CToTy)) {
9817 Qualifiers FromQs = CFromTy.getQualifiers();
9818 Qualifiers ToQs = CToTy.getQualifiers();
9819 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9820 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009821 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9822 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9823 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009825 return;
9826 }
9827 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009828
9829 if (TakingCandidateAddress &&
9830 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9831 return;
9832
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009833 // Emit the generic diagnostic and, optionally, add the hints to it.
9834 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
Eric Fiselier92e523b2018-05-30 01:00:41 +00009835 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9837 << ToTy << (unsigned)isObjectArgument << I + 1
9838 << (unsigned)(Cand->Fix.Kind);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009839
9840 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009841 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9842 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009843 FDiag << *HI;
9844 S.Diag(Fn->getLocation(), FDiag);
9845
Richard Smith5179eb72016-06-28 19:03:57 +00009846 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009847}
9848
Larisse Voufo98b20f12013-07-19 23:00:19 +00009849/// Additional arity mismatch diagnosis specific to a function overload
9850/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9851/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009852static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9853 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009854 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009855 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009856
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009857 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009858 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009859 // right number of arguments, because only overloaded operators have
9860 // the weird behavior of overloading member and non-member functions.
9861 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009862 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009863 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009864 return true;
9865
9866 if (NumArgs < MinParams) {
9867 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9868 (Cand->FailureKind == ovl_fail_bad_deduction &&
9869 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9870 } else {
9871 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9872 (Cand->FailureKind == ovl_fail_bad_deduction &&
9873 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9874 }
9875
9876 return false;
9877}
9878
9879/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009880static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9881 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009882 assert(isa<FunctionDecl>(D) &&
9883 "The templated declaration should at least be a function"
9884 " when diagnosing bad template argument deduction due to too many"
9885 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009886
Larisse Voufo98b20f12013-07-19 23:00:19 +00009887 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009888
Larisse Voufo98b20f12013-07-19 23:00:19 +00009889 // TODO: treat calls to a missing default constructor as a special case
9890 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9891 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009892
John McCall6a61b522010-01-13 09:16:55 +00009893 // at least / at most / exactly
9894 unsigned mode, modeCount;
9895 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009896 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9897 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009898 mode = 0; // "at least"
9899 else
9900 mode = 2; // "exactly"
9901 modeCount = MinParams;
9902 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009903 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009904 mode = 1; // "at most"
9905 else
9906 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009907 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009908 }
9909
9910 std::string Description;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009911 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009912 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009913
Richard Smith10ff50d2012-05-11 05:16:41 +00009914 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009916 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9917 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009918 else
9919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009920 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9921 << Description << mode << modeCount << NumFormalArgs;
9922
Richard Smith5179eb72016-06-28 19:03:57 +00009923 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009924}
9925
Larisse Voufo98b20f12013-07-19 23:00:19 +00009926/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009927static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9928 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009929 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009930 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009931}
Larisse Voufo47c08452013-07-19 22:53:23 +00009932
Richard Smith17c00b42014-11-12 01:24:00 +00009933static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009934 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9935 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009936 llvm_unreachable("Unsupported: Getting the described template declaration"
9937 " for bad deduction diagnosis");
9938}
9939
9940/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009941static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009942 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009943 unsigned NumArgs,
9944 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009945 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009946 NamedDecl *ParamD;
9947 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9948 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9949 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009950 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009951 case Sema::TDK_Success:
9952 llvm_unreachable("TDK_success while diagnosing bad deduction");
9953
9954 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009955 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009956 S.Diag(Templated->getLocation(),
9957 diag::note_ovl_candidate_incomplete_deduction)
9958 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009959 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009960 return;
9961 }
9962
Richard Smith4a8f3512018-07-19 19:00:37 +00009963 case Sema::TDK_IncompletePack: {
9964 assert(ParamD && "no parameter found for incomplete deduction result");
9965 S.Diag(Templated->getLocation(),
9966 diag::note_ovl_candidate_incomplete_deduction_pack)
9967 << ParamD->getDeclName()
9968 << (DeductionFailure.getFirstArg()->pack_size() + 1)
9969 << *DeductionFailure.getFirstArg();
9970 MaybeEmitInheritedConstructorNote(S, Found);
9971 return;
9972 }
9973
John McCall42d7d192010-08-05 09:05:08 +00009974 case Sema::TDK_Underqualified: {
9975 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9976 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9977
Larisse Voufo98b20f12013-07-19 23:00:19 +00009978 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009979
9980 // Param will have been canonicalized, but it should just be a
9981 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009982 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009983 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009984 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009985 assert(S.Context.hasSameType(Param, NonCanonParam));
9986
9987 // Arg has also been canonicalized, but there's nothing we can do
9988 // about that. It also doesn't matter as much, because it won't
9989 // have any template parameters in it (because deduction isn't
9990 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009991 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009992
Larisse Voufo98b20f12013-07-19 23:00:19 +00009993 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9994 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009995 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009996 return;
9997 }
9998
9999 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010000 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010001 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010002 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010003 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +000010004 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10005 // Deduction might have failed because we deduced arguments of two
10006 // different types for a non-type template parameter.
10007 // FIXME: Use a different TDK value for this.
10008 QualType T1 =
10009 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10010 QualType T2 =
10011 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
Richard Smithe54d9522018-10-09 18:49:22 +000010012 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
Richard Smith593d6a12016-12-23 01:30:39 +000010013 S.Diag(Templated->getLocation(),
10014 diag::note_ovl_candidate_inconsistent_deduction_types)
10015 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10016 << *DeductionFailure.getSecondArg() << T2;
10017 MaybeEmitInheritedConstructorNote(S, Found);
10018 return;
10019 }
10020
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010021 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +000010022 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010023 which = 2;
10024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010025
Larisse Voufo98b20f12013-07-19 23:00:19 +000010026 S.Diag(Templated->getLocation(),
10027 diag::note_ovl_candidate_inconsistent_deduction)
10028 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10029 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +000010030 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010031 return;
10032 }
Douglas Gregor02eb4832010-05-08 18:13:28 +000010033
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010034 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010035 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010036 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +000010037 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010038 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010039 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010040 else {
10041 int index = 0;
10042 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10043 index = TTP->getIndex();
10044 else if (NonTypeTemplateParmDecl *NTTP
10045 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10046 index = NTTP->getIndex();
10047 else
10048 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +000010049 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010050 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010051 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010052 }
Richard Smith5179eb72016-06-28 19:03:57 +000010053 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010054 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010055
Douglas Gregor02eb4832010-05-08 18:13:28 +000010056 case Sema::TDK_TooManyArguments:
10057 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +000010058 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +000010059 return;
Douglas Gregord09efd42010-05-08 20:07:26 +000010060
10061 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010062 S.Diag(Templated->getLocation(),
10063 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +000010064 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010065 return;
10066
10067 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +000010068 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010069 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010070 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +000010071 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +000010072 TemplateArgString = " ";
10073 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +000010074 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +000010075 }
10076
Richard Smith6f8d2c62012-05-09 05:17:00 +000010077 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010078 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +000010079 if (PDiag && PDiag->second.getDiagID() ==
10080 diag::err_typename_nested_not_found_enable_if) {
10081 // FIXME: Use the source range of the condition, and the fully-qualified
10082 // name of the enable_if template. These are both present in PDiag.
10083 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10084 << "'enable_if'" << TemplateArgString;
10085 return;
10086 }
10087
Douglas Gregor00fa10b2017-07-05 20:20:14 +000010088 // We found a specific requirement that disabled the enable_if.
10089 if (PDiag && PDiag->second.getDiagID() ==
10090 diag::err_typename_nested_not_found_requirement) {
10091 S.Diag(Templated->getLocation(),
10092 diag::note_ovl_candidate_disabled_by_requirement)
10093 << PDiag->second.getStringArg(0) << TemplateArgString;
10094 return;
10095 }
10096
Richard Smith9ca64612012-05-07 09:03:25 +000010097 // Format the SFINAE diagnostic into the argument string.
10098 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10099 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010100 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010101 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +000010102 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +000010103 SFINAEArgString = ": ";
10104 R = SourceRange(PDiag->first, PDiag->first);
10105 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10106 }
10107
Larisse Voufo98b20f12013-07-19 23:00:19 +000010108 S.Diag(Templated->getLocation(),
10109 diag::note_ovl_candidate_substitution_failure)
10110 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +000010111 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010112 return;
10113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010114
Richard Smithc92d2062017-01-05 23:02:44 +000010115 case Sema::TDK_DeducedMismatch:
10116 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +000010117 // Format the template argument list into the argument string.
10118 SmallString<128> TemplateArgString;
10119 if (TemplateArgumentList *Args =
10120 DeductionFailure.getTemplateArgumentList()) {
10121 TemplateArgString = " ";
10122 TemplateArgString += S.getTemplateArgumentBindingsText(
10123 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10124 }
10125
10126 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10127 << (*DeductionFailure.getCallArgIndex() + 1)
10128 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +000010129 << TemplateArgString
10130 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +000010131 break;
10132 }
10133
Richard Trieue3732352013-04-08 21:11:40 +000010134 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +000010135 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010136 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10137 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +000010138 if (FirstTA.getKind() == TemplateArgument::Template &&
10139 SecondTA.getKind() == TemplateArgument::Template) {
10140 TemplateName FirstTN = FirstTA.getAsTemplate();
10141 TemplateName SecondTN = SecondTA.getAsTemplate();
10142 if (FirstTN.getKind() == TemplateName::Template &&
10143 SecondTN.getKind() == TemplateName::Template) {
10144 if (FirstTN.getAsTemplateDecl()->getName() ==
10145 SecondTN.getAsTemplateDecl()->getName()) {
10146 // FIXME: This fixes a bad diagnostic where both templates are named
10147 // the same. This particular case is a bit difficult since:
10148 // 1) It is passed as a string to the diagnostic printer.
10149 // 2) The diagnostic printer only attempts to find a better
10150 // name for types, not decls.
10151 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010152 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010153 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10154 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10155 return;
10156 }
10157 }
10158 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010159
10160 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10161 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10162 return;
10163
Faisal Vali2b391ab2013-09-26 19:54:12 +000010164 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010165 // call operator, and if so, emit a prettier and more informative
10166 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +000010167 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010168 S.Diag(Templated->getLocation(),
10169 diag::note_ovl_candidate_non_deduced_mismatch)
10170 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010171 return;
Richard Trieue3732352013-04-08 21:11:40 +000010172 }
John McCall8b9ed552010-02-01 18:53:26 +000010173 // TODO: diagnose these individually, then kill off
10174 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010175 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010176 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010177 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010178 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010179 case Sema::TDK_CUDATargetMismatch:
10180 S.Diag(Templated->getLocation(),
10181 diag::note_cuda_ovl_candidate_target_mismatch);
10182 return;
John McCall8b9ed552010-02-01 18:53:26 +000010183 }
10184}
10185
Larisse Voufo98b20f12013-07-19 23:00:19 +000010186/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010187static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010188 unsigned NumArgs,
10189 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010190 unsigned TDK = Cand->DeductionFailure.Result;
10191 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10192 if (CheckArityMismatch(S, Cand, NumArgs))
10193 return;
10194 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010195 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010196 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010197}
10198
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010199/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010200static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010201 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10202 FunctionDecl *Callee = Cand->Function;
10203
10204 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10205 CalleeTarget = S.IdentifyCUDATarget(Callee);
10206
10207 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010208 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +000010209 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010210
10211 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010212 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10213 << FnDesc /* Ignored */
10214 << CalleeTarget << CallerTarget;
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010215
10216 // This could be an implicit constructor for which we could not infer the
10217 // target due to a collsion. Diagnose that case.
10218 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10219 if (Meth != nullptr && Meth->isImplicit()) {
10220 CXXRecordDecl *ParentClass = Meth->getParent();
10221 Sema::CXXSpecialMember CSM;
10222
Eric Fiselier92e523b2018-05-30 01:00:41 +000010223 switch (FnKindPair.first) {
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010224 default:
10225 return;
10226 case oc_implicit_default_constructor:
10227 CSM = Sema::CXXDefaultConstructor;
10228 break;
10229 case oc_implicit_copy_constructor:
10230 CSM = Sema::CXXCopyConstructor;
10231 break;
10232 case oc_implicit_move_constructor:
10233 CSM = Sema::CXXMoveConstructor;
10234 break;
10235 case oc_implicit_copy_assignment:
10236 CSM = Sema::CXXCopyAssignment;
10237 break;
10238 case oc_implicit_move_assignment:
10239 CSM = Sema::CXXMoveAssignment;
10240 break;
10241 };
10242
10243 bool ConstRHS = false;
10244 if (Meth->getNumParams()) {
10245 if (const ReferenceType *RT =
10246 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10247 ConstRHS = RT->getPointeeType().isConstQualified();
10248 }
10249 }
10250
10251 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10252 /* ConstRHS */ ConstRHS,
10253 /* Diagnose */ true);
10254 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010255}
10256
Richard Smith17c00b42014-11-12 01:24:00 +000010257static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010258 FunctionDecl *Callee = Cand->Function;
10259 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10260
10261 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010262 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010263 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10264}
10265
Yaxun Liu5b746652016-12-18 05:18:55 +000010266static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10267 FunctionDecl *Callee = Cand->Function;
10268
10269 S.Diag(Callee->getLocation(),
Andrew Savonichev16f16992018-10-11 13:35:34 +000010270 diag::note_ovl_candidate_disabled_by_extension)
10271 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
Yaxun Liu5b746652016-12-18 05:18:55 +000010272}
10273
John McCall8b9ed552010-02-01 18:53:26 +000010274/// Generates a 'note' diagnostic for an overload candidate. We've
10275/// already generated a primary error at the call site.
10276///
10277/// It really does need to be a single diagnostic with its caret
10278/// pointed at the candidate declaration. Yes, this creates some
10279/// major challenges of technical writing. Yes, this makes pointing
10280/// out problems with specific arguments quite awkward. It's still
10281/// better than generating twenty screens of text for every failed
10282/// overload.
10283///
10284/// It would be great to be able to express per-candidate problems
10285/// more richly for those diagnostic clients that cared, but we'd
10286/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010287static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010288 unsigned NumArgs,
10289 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010290 FunctionDecl *Fn = Cand->Function;
10291
John McCall12f97bc2010-01-08 04:41:39 +000010292 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010293 if (Cand->Viable) {
10294 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10295 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010296 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10297 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010298
George Burgess IV177399e2017-01-09 04:12:14 +000010299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010300 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10301 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
George Burgess IV177399e2017-01-09 04:12:14 +000010302 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10303 return;
10304 }
John McCall12f97bc2010-01-08 04:41:39 +000010305
George Burgess IV177399e2017-01-09 04:12:14 +000010306 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010307 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010308 return;
10309 }
John McCall0d1da222010-01-12 00:44:57 +000010310
John McCall6a61b522010-01-13 09:16:55 +000010311 switch (Cand->FailureKind) {
10312 case ovl_fail_too_many_arguments:
10313 case ovl_fail_too_few_arguments:
10314 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010315
John McCall6a61b522010-01-13 09:16:55 +000010316 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010317 return DiagnoseBadDeduction(S, Cand, NumArgs,
10318 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010319
John McCall578a1f82014-12-14 01:46:53 +000010320 case ovl_fail_illegal_constructor: {
10321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10322 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010324 return;
10325 }
10326
John McCallfe796dd2010-01-23 05:17:32 +000010327 case ovl_fail_trivial_conversion:
10328 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010329 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010330 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010331
John McCall65eb8792010-02-25 01:37:24 +000010332 case ovl_fail_bad_conversion: {
10333 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010334 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010335 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010336 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010337
John McCall6a61b522010-01-13 09:16:55 +000010338 // FIXME: this currently happens when we're called from SemaInit
10339 // when user-conversion overload fails. Figure out how to handle
10340 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010341 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010342 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010343
10344 case ovl_fail_bad_target:
10345 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010346
10347 case ovl_fail_enable_if:
10348 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010349
Yaxun Liu5b746652016-12-18 05:18:55 +000010350 case ovl_fail_ext_disabled:
10351 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10352
Richard Smithf9c59b72017-01-08 21:45:44 +000010353 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010354 // It's generally not interesting to note copy/move constructors here.
10355 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10356 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010357 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010358 diag::note_ovl_candidate_inherited_constructor_slice)
10359 << (Fn->getPrimaryTemplate() ? 1 : 0)
10360 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010361 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10362 return;
10363
George Burgess IV7204ed92016-01-07 02:26:57 +000010364 case ovl_fail_addr_not_available: {
10365 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10366 (void)Available;
10367 assert(!Available);
10368 break;
10369 }
Erich Keane281d20b2018-01-08 21:34:17 +000010370 case ovl_non_default_multiversion_function:
10371 // Do nothing, these should simply be ignored.
10372 break;
John McCall65eb8792010-02-25 01:37:24 +000010373 }
John McCalld3224162010-01-08 00:58:21 +000010374}
10375
Richard Smith17c00b42014-11-12 01:24:00 +000010376static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010377 // Desugar the type of the surrogate down to a function type,
10378 // retaining as many typedefs as possible while still showing
10379 // the function type (and, therefore, its parameter types).
10380 QualType FnType = Cand->Surrogate->getConversionType();
10381 bool isLValueReference = false;
10382 bool isRValueReference = false;
10383 bool isPointer = false;
10384 if (const LValueReferenceType *FnTypeRef =
10385 FnType->getAs<LValueReferenceType>()) {
10386 FnType = FnTypeRef->getPointeeType();
10387 isLValueReference = true;
10388 } else if (const RValueReferenceType *FnTypeRef =
10389 FnType->getAs<RValueReferenceType>()) {
10390 FnType = FnTypeRef->getPointeeType();
10391 isRValueReference = true;
10392 }
10393 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10394 FnType = FnTypePtr->getPointeeType();
10395 isPointer = true;
10396 }
10397 // Desugar down to a function type.
10398 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10399 // Reconstruct the pointer/reference as appropriate.
10400 if (isPointer) FnType = S.Context.getPointerType(FnType);
10401 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10402 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10403
10404 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10405 << FnType;
10406}
10407
Richard Smith17c00b42014-11-12 01:24:00 +000010408static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10409 SourceLocation OpLoc,
10410 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010411 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010412 std::string TypeStr("operator");
10413 TypeStr += Opc;
10414 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010415 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010416 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010417 TypeStr += ")";
10418 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10419 } else {
10420 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010421 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010422 TypeStr += ")";
10423 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10424 }
10425}
10426
Richard Smith17c00b42014-11-12 01:24:00 +000010427static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10428 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010429 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010430 if (ICS.isBad()) break; // all meaningless after first invalid
10431 if (!ICS.isAmbiguous()) continue;
10432
Richard Smithc2bebe92016-05-11 20:37:46 +000010433 ICS.DiagnoseAmbiguousConversion(
10434 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010435 }
10436}
10437
Larisse Voufo98b20f12013-07-19 23:00:19 +000010438static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010439 if (Cand->Function)
10440 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010441 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010442 return Cand->Surrogate->getLocation();
10443 return SourceLocation();
10444}
10445
Larisse Voufo98b20f12013-07-19 23:00:19 +000010446static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010447 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010448 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010449 case Sema::TDK_NonDependentConversionFailure:
10450 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010451
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010452 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010453 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +000010454 case Sema::TDK_IncompletePack:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010455 return 1;
10456
10457 case Sema::TDK_Underqualified:
10458 case Sema::TDK_Inconsistent:
10459 return 2;
10460
10461 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010462 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010463 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010464 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010465 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010466 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010467 return 3;
10468
10469 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010470 return 4;
10471
10472 case Sema::TDK_InvalidExplicitArguments:
10473 return 5;
10474
10475 case Sema::TDK_TooManyArguments:
10476 case Sema::TDK_TooFewArguments:
10477 return 6;
10478 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010479 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010480}
10481
Richard Smith17c00b42014-11-12 01:24:00 +000010482namespace {
John McCallad2587a2010-01-12 00:48:53 +000010483struct CompareOverloadCandidatesForDisplay {
10484 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010485 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010486 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010487 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010488
Richard Smith67ef14f2017-09-26 18:37:55 +000010489 CompareOverloadCandidatesForDisplay(
10490 Sema &S, SourceLocation Loc, size_t NArgs,
10491 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010492 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010493
10494 bool operator()(const OverloadCandidate *L,
10495 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010496 // Fast-path this check.
10497 if (L == R) return false;
10498
John McCall12f97bc2010-01-08 04:41:39 +000010499 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010500 if (L->Viable) {
10501 if (!R->Viable) return true;
10502
10503 // TODO: introduce a tri-valued comparison for overload
10504 // candidates. Would be more worthwhile if we had a sort
10505 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010506 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10507 return true;
10508 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10509 return false;
John McCallad2587a2010-01-12 00:48:53 +000010510 } else if (R->Viable)
10511 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010512
John McCall3712d9e2010-01-15 23:32:50 +000010513 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010514
John McCall3712d9e2010-01-15 23:32:50 +000010515 // Criteria by which we can sort non-viable candidates:
10516 if (!L->Viable) {
10517 // 1. Arity mismatches come after other candidates.
10518 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010519 L->FailureKind == ovl_fail_too_few_arguments) {
10520 if (R->FailureKind == ovl_fail_too_many_arguments ||
10521 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010522 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10523 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10524 if (LDist == RDist) {
10525 if (L->FailureKind == R->FailureKind)
10526 // Sort non-surrogates before surrogates.
10527 return !L->IsSurrogate && R->IsSurrogate;
10528 // Sort candidates requiring fewer parameters than there were
10529 // arguments given after candidates requiring more parameters
10530 // than there were arguments given.
10531 return L->FailureKind == ovl_fail_too_many_arguments;
10532 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010533 return LDist < RDist;
10534 }
John McCall3712d9e2010-01-15 23:32:50 +000010535 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010536 }
John McCall3712d9e2010-01-15 23:32:50 +000010537 if (R->FailureKind == ovl_fail_too_many_arguments ||
10538 R->FailureKind == ovl_fail_too_few_arguments)
10539 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010540
John McCallfe796dd2010-01-23 05:17:32 +000010541 // 2. Bad conversions come first and are ordered by the number
10542 // of bad conversions and quality of good conversions.
10543 if (L->FailureKind == ovl_fail_bad_conversion) {
10544 if (R->FailureKind != ovl_fail_bad_conversion)
10545 return true;
10546
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010547 // The conversion that can be fixed with a smaller number of changes,
10548 // comes first.
10549 unsigned numLFixes = L->Fix.NumConversionsFixed;
10550 unsigned numRFixes = R->Fix.NumConversionsFixed;
10551 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10552 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010553 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010554 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010555 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010556
John McCallfe796dd2010-01-23 05:17:32 +000010557 // If there's any ordering between the defined conversions...
10558 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010559 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010560
10561 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010562 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010563 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010564 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010565 L->Conversions[I],
10566 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010567 case ImplicitConversionSequence::Better:
10568 leftBetter++;
10569 break;
10570
10571 case ImplicitConversionSequence::Worse:
10572 leftBetter--;
10573 break;
10574
10575 case ImplicitConversionSequence::Indistinguishable:
10576 break;
10577 }
10578 }
10579 if (leftBetter > 0) return true;
10580 if (leftBetter < 0) return false;
10581
10582 } else if (R->FailureKind == ovl_fail_bad_conversion)
10583 return false;
10584
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010585 if (L->FailureKind == ovl_fail_bad_deduction) {
10586 if (R->FailureKind != ovl_fail_bad_deduction)
10587 return true;
10588
10589 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10590 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010591 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010592 } else if (R->FailureKind == ovl_fail_bad_deduction)
10593 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010594
John McCall3712d9e2010-01-15 23:32:50 +000010595 // TODO: others?
10596 }
10597
10598 // Sort everything else by location.
10599 SourceLocation LLoc = GetLocationForCandidate(L);
10600 SourceLocation RLoc = GetLocationForCandidate(R);
10601
10602 // Put candidates without locations (e.g. builtins) at the end.
10603 if (LLoc.isInvalid()) return false;
10604 if (RLoc.isInvalid()) return true;
10605
10606 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010607 }
10608};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010609}
John McCall12f97bc2010-01-08 04:41:39 +000010610
John McCallfe796dd2010-01-23 05:17:32 +000010611/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010612/// computes up to the first bad conversion. Produces the FixIt set if
10613/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010614static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10615 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010616 assert(!Cand->Viable);
10617
10618 // Don't do anything on failures other than bad conversion.
10619 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10620
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010621 // We only want the FixIts if all the arguments can be corrected.
10622 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010623 // Use a implicit copy initialization to check conversion fixes.
10624 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010625
Richard Smith6eedfe72017-01-09 08:01:21 +000010626 // Attempt to fix the bad conversion.
10627 unsigned ConvCount = Cand->Conversions.size();
10628 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10629 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010630 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010631 if (Cand->Conversions[ConvIdx].isInitialized() &&
10632 Cand->Conversions[ConvIdx].isBad()) {
10633 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010634 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010635 }
John McCallfe796dd2010-01-23 05:17:32 +000010636 }
10637
Douglas Gregoradc7a702010-04-16 17:45:54 +000010638 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010639 // operation somehow.
10640 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010641
Richard Smith14ead302017-01-10 20:19:21 +000010642 unsigned ConvIdx = 0;
10643 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010644
10645 if (Cand->IsSurrogate) {
10646 QualType ConvType
10647 = Cand->Surrogate->getConversionType().getNonReferenceType();
10648 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10649 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010650 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10651 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10652 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010653 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010654 ParamTypes =
10655 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010656 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010657 !isa<CXXConstructorDecl>(Cand->Function)) {
10658 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10659 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010660 }
Richard Smith14ead302017-01-10 20:19:21 +000010661 } else {
10662 // Builtin operator.
10663 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010664 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010665 }
10666
10667 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010668 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010669 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010670 // We've already checked this conversion.
10671 } else if (ArgIdx < ParamTypes.size()) {
10672 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010673 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10674 Args[ArgIdx]->getType());
10675 else {
10676 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010677 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010678 SuppressUserConversions,
10679 /*InOverloadResolution=*/true,
10680 /*AllowObjCWritebackConversion=*/
10681 S.getLangOpts().ObjCAutoRefCount);
10682 // Store the FixIt in the candidate if it exists.
10683 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10684 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10685 }
10686 } else
John McCallfe796dd2010-01-23 05:17:32 +000010687 Cand->Conversions[ConvIdx].setEllipsis();
10688 }
10689}
10690
Erich Keanec18cce42018-01-29 19:33:20 +000010691/// When overload resolution fails, prints diagnostic messages containing the
10692/// candidates in the candidate set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010693void OverloadCandidateSet::NoteCandidates(
10694 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10695 StringRef Opc, SourceLocation OpLoc,
10696 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010697 // Sort the candidates by viability and position. Sorting directly would
10698 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010699 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010700 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10701 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010702 if (!Filter(*Cand))
10703 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010704 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010705 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010706 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010707 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010708 if (Cand->Function || Cand->IsSurrogate)
10709 Cands.push_back(Cand);
10710 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10711 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010712 }
10713 }
10714
Mandeep Singh Grange66d2322017-11-14 00:22:24 +000010715 std::stable_sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010716 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010717
John McCall0d1da222010-01-12 00:44:57 +000010718 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010719
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010720 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010721 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010722 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010723 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10724 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010725
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010726 // Set an arbitrary limit on the number of candidate functions we'll spam
10727 // the user with. FIXME: This limit should depend on details of the
10728 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010729 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010730 break;
10731 }
10732 ++CandsShown;
10733
John McCalld3224162010-01-08 00:58:21 +000010734 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010735 NoteFunctionCandidate(S, Cand, Args.size(),
10736 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010737 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010738 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010739 else {
10740 assert(Cand->Viable &&
10741 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010742 // Generally we only see ambiguities including viable builtin
10743 // operators if overload resolution got screwed up by an
10744 // ambiguous user-defined conversion.
10745 //
10746 // FIXME: It's quite possible for different conversions to see
10747 // different ambiguities, though.
10748 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010749 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010750 ReportedAmbiguousConversions = true;
10751 }
John McCalld3224162010-01-08 00:58:21 +000010752
John McCall0d1da222010-01-12 00:44:57 +000010753 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010754 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010755 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010756 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010757
10758 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010759 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010760}
10761
Larisse Voufo98b20f12013-07-19 23:00:19 +000010762static SourceLocation
10763GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10764 return Cand->Specialization ? Cand->Specialization->getLocation()
10765 : SourceLocation();
10766}
10767
Richard Smith17c00b42014-11-12 01:24:00 +000010768namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010769struct CompareTemplateSpecCandidatesForDisplay {
10770 Sema &S;
10771 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10772
10773 bool operator()(const TemplateSpecCandidate *L,
10774 const TemplateSpecCandidate *R) {
10775 // Fast-path this check.
10776 if (L == R)
10777 return false;
10778
10779 // Assuming that both candidates are not matches...
10780
10781 // Sort by the ranking of deduction failures.
10782 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10783 return RankDeductionFailure(L->DeductionFailure) <
10784 RankDeductionFailure(R->DeductionFailure);
10785
10786 // Sort everything else by location.
10787 SourceLocation LLoc = GetLocationForCandidate(L);
10788 SourceLocation RLoc = GetLocationForCandidate(R);
10789
10790 // Put candidates without locations (e.g. builtins) at the end.
10791 if (LLoc.isInvalid())
10792 return false;
10793 if (RLoc.isInvalid())
10794 return true;
10795
10796 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10797 }
10798};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010799}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010800
10801/// Diagnose a template argument deduction failure.
10802/// We are treating these failures as overload failures due to bad
10803/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010804void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10805 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010806 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010807 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010808}
10809
10810void TemplateSpecCandidateSet::destroyCandidates() {
10811 for (iterator i = begin(), e = end(); i != e; ++i) {
10812 i->DeductionFailure.Destroy();
10813 }
10814}
10815
10816void TemplateSpecCandidateSet::clear() {
10817 destroyCandidates();
10818 Candidates.clear();
10819}
10820
10821/// NoteCandidates - When no template specialization match is found, prints
10822/// diagnostic messages containing the non-matching specializations that form
10823/// the candidate set.
10824/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10825/// OCD == OCD_AllCandidates and Cand->Viable == false.
10826void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10827 // Sort the candidates by position (assuming no candidate is a match).
10828 // Sorting directly would be prohibitive, so we make a set of pointers
10829 // and sort those.
10830 SmallVector<TemplateSpecCandidate *, 32> Cands;
10831 Cands.reserve(size());
10832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10833 if (Cand->Specialization)
10834 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010835 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010836 // in general, want to list every possible builtin candidate.
10837 }
10838
Fangrui Song55fab262018-09-26 22:16:28 +000010839 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
Larisse Voufo98b20f12013-07-19 23:00:19 +000010840
10841 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10842 // for generalization purposes (?).
10843 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10844
10845 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10846 unsigned CandsShown = 0;
10847 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10848 TemplateSpecCandidate *Cand = *I;
10849
10850 // Set an arbitrary limit on the number of candidates we'll spam
10851 // the user with. FIXME: This limit should depend on details of the
10852 // candidate list.
10853 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10854 break;
10855 ++CandsShown;
10856
10857 assert(Cand->Specialization &&
10858 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010859 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010860 }
10861
10862 if (I != E)
10863 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10864}
10865
Douglas Gregorb491ed32011-02-19 21:32:49 +000010866// [PossiblyAFunctionType] --> [Return]
10867// NonFunctionType --> NonFunctionType
10868// R (A) --> R(A)
10869// R (*)(A) --> R (A)
10870// R (&)(A) --> R (A)
10871// R (S::*)(A) --> R (A)
10872QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10873 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010874 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010875 PossiblyAFunctionType->getAs<PointerType>())
10876 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010877 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010878 PossiblyAFunctionType->getAs<ReferenceType>())
10879 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010880 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010881 PossiblyAFunctionType->getAs<MemberPointerType>())
10882 Ret = MemTypePtr->getPointeeType();
10883 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010884 Context.getCanonicalType(Ret).getUnqualifiedType();
10885 return Ret;
10886}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010887
Richard Smith9095e5b2016-11-01 01:31:23 +000010888static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10889 bool Complain = true) {
10890 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10891 S.DeduceReturnType(FD, Loc, Complain))
10892 return true;
10893
10894 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010895 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +000010896 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10897 !S.ResolveExceptionSpec(Loc, FPT))
10898 return true;
10899
10900 return false;
10901}
10902
Richard Smith17c00b42014-11-12 01:24:00 +000010903namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010904// A helper class to help with address of function resolution
10905// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010906class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010907 Sema& S;
10908 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010909 const QualType& TargetType;
10910 QualType TargetFunctionType; // Extracted function type from target type
10911
Douglas Gregorb491ed32011-02-19 21:32:49 +000010912 bool Complain;
10913 //DeclAccessPair& ResultFunctionAccessPair;
10914 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010915
Douglas Gregorb491ed32011-02-19 21:32:49 +000010916 bool TargetTypeIsNonStaticMemberFunction;
10917 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010918 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010919 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010920
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010921 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010922 OverloadExpr *OvlExpr;
10923 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010924 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010925 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010926
Douglas Gregorb491ed32011-02-19 21:32:49 +000010927public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010928 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10929 const QualType &TargetType, bool Complain)
10930 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10931 Complain(Complain), Context(S.getASTContext()),
10932 TargetTypeIsNonStaticMemberFunction(
10933 !!TargetType->getAs<MemberPointerType>()),
10934 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010935 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010936 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010937 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10938 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010939 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010940 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010941
David Majnemera4f7c7a2013-08-01 06:13:59 +000010942 if (TargetFunctionType->isFunctionType()) {
10943 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10944 if (!UME->isImplicitAccess() &&
10945 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10946 StaticMemberFunctionFromBoundPointer = true;
10947 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10948 DeclAccessPair dap;
10949 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10950 OvlExpr, false, &dap)) {
10951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10952 if (!Method->isStatic()) {
10953 // If the target type is a non-function type and the function found
10954 // is a non-static member function, pretend as if that was the
10955 // target, it's the only possible type to end up with.
10956 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010957
David Majnemera4f7c7a2013-08-01 06:13:59 +000010958 // And skip adding the function if its not in the proper form.
10959 // We'll diagnose this due to an empty set of functions.
10960 if (!OvlExprInfo.HasFormOfMemberPointer)
10961 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010962 }
10963
David Majnemera4f7c7a2013-08-01 06:13:59 +000010964 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010965 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010966 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010967 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010968
Douglas Gregorb491ed32011-02-19 21:32:49 +000010969 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010970 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010971
Douglas Gregorb491ed32011-02-19 21:32:49 +000010972 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10973 // C++ [over.over]p4:
10974 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010975 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010976 if (FoundNonTemplateFunction)
10977 EliminateAllTemplateMatches();
10978 else
10979 EliminateAllExceptMostSpecializedTemplate();
10980 }
10981 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010982
Justin Lebar25c4a812016-03-29 16:24:16 +000010983 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010984 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010985 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010986
10987 bool hasComplained() const { return HasComplained; }
10988
Douglas Gregorb491ed32011-02-19 21:32:49 +000010989private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010990 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10991 QualType Discard;
10992 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010993 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010994 }
10995
George Burgess IV6da4c202016-03-23 02:33:58 +000010996 /// \return true if A is considered a better overload candidate for the
10997 /// desired type than B.
10998 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10999 // If A doesn't have exactly the correct type, we don't want to classify it
11000 // as "better" than anything else. This way, the user is required to
11001 // disambiguate for us if there are multiple candidates and no exact match.
11002 return candidateHasExactlyCorrectType(A) &&
11003 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000011004 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000011005 }
11006
11007 /// \return true if we were able to eliminate all but one overload candidate,
11008 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000011009 bool eliminiateSuboptimalOverloadCandidates() {
11010 // Same algorithm as overload resolution -- one pass to pick the "best",
11011 // another pass to be sure that nothing is better than the best.
11012 auto Best = Matches.begin();
11013 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11014 if (isBetterCandidate(I->second, Best->second))
11015 Best = I;
11016
11017 const FunctionDecl *BestFn = Best->second;
11018 auto IsBestOrInferiorToBest = [this, BestFn](
11019 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11020 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11021 };
11022
11023 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11024 // option, so we can potentially give the user a better error
Fangrui Song3117b172018-10-20 17:53:42 +000011025 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
George Burgess IV2a6150d2015-10-16 01:17:38 +000011026 return false;
11027 Matches[0] = *Best;
11028 Matches.resize(1);
11029 return true;
11030 }
11031
Douglas Gregorb491ed32011-02-19 21:32:49 +000011032 bool isTargetTypeAFunction() const {
11033 return TargetFunctionType->isFunctionType();
11034 }
11035
11036 // [ToType] [Return]
11037
11038 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11039 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11040 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11041 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11042 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11043 }
11044
11045 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011046 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011047 const DeclAccessPair& CurAccessFunPair) {
11048 if (CXXMethodDecl *Method
11049 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11050 // Skip non-static function templates when converting to pointer, and
11051 // static when converting to member pointer.
11052 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11053 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011054 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011055 else if (TargetTypeIsNonStaticMemberFunction)
11056 return false;
11057
11058 // C++ [over.over]p2:
11059 // If the name is a function template, template argument deduction is
11060 // done (14.8.2.2), and if the argument deduction succeeds, the
11061 // resulting template argument list is used to generate a single
11062 // function template specialization, which is added to the set of
11063 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011064 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011065 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000011066 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011067 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011068 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011069 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000011070 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011071 // Make a note of the failed deduction for diagnostics.
11072 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011073 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011074 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000011075 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011076 }
11077
Douglas Gregor19a41f12013-04-17 08:45:07 +000011078 // Template argument deduction ensures that we have an exact match or
11079 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011080 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000011081 assert(S.isSameOrCompatibleFunctionType(
11082 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011083 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000011084
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011085 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000011086 return false;
11087
Douglas Gregorb491ed32011-02-19 21:32:49 +000011088 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11089 return true;
11090 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011091
11092 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011093 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011094 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000011095 // Skip non-static functions when converting to pointer, and static
11096 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011097 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11098 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011099 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011100 else if (TargetTypeIsNonStaticMemberFunction)
11101 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011102
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011103 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011104 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011105 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000011106 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011107 return false;
Erich Keane281d20b2018-01-08 21:34:17 +000011108 if (FunDecl->isMultiVersion()) {
11109 const auto *TA = FunDecl->getAttr<TargetAttr>();
Erich Keane3efe0022018-07-20 14:13:28 +000011110 if (TA && !TA->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +000011111 return false;
11112 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011113
Richard Smith2a7d4812013-05-04 07:00:32 +000011114 // If any candidate has a placeholder return type, trigger its deduction
11115 // now.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011116 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
Richard Smith9095e5b2016-11-01 01:31:23 +000011117 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000011118 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000011119 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011120 }
Richard Smith2a7d4812013-05-04 07:00:32 +000011121
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011122 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000011123 return false;
11124
George Burgess IV6da4c202016-03-23 02:33:58 +000011125 // If we're in C, we need to support types that aren't exactly identical.
11126 if (!S.getLangOpts().CPlusPlus ||
11127 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000011128 Matches.push_back(std::make_pair(
11129 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011130 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011131 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011132 }
Mike Stump11289f42009-09-09 15:08:12 +000011133 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011134
Douglas Gregorb491ed32011-02-19 21:32:49 +000011135 return false;
11136 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011137
Douglas Gregorb491ed32011-02-19 21:32:49 +000011138 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11139 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011140
Douglas Gregorb491ed32011-02-19 21:32:49 +000011141 // If the overload expression doesn't have the form of a pointer to
11142 // member, don't try to convert it to a pointer-to-member type.
11143 if (IsInvalidFormOfPointerToMemberFunction())
11144 return false;
11145
11146 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011147 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011148 I != E; ++I) {
11149 // Look through any using declarations to find the underlying function.
11150 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11151
11152 // C++ [over.over]p3:
11153 // Non-member functions and static member functions match
11154 // targets of type "pointer-to-function" or "reference-to-function."
11155 // Nonstatic member functions match targets of
11156 // type "pointer-to-member-function."
11157 // Note that according to DR 247, the containing class does not matter.
11158 if (FunctionTemplateDecl *FunctionTemplate
11159 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11160 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11161 Ret = true;
11162 }
11163 // If we have explicit template arguments supplied, skip non-templates.
11164 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11165 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11166 Ret = true;
11167 }
11168 assert(Ret || Matches.empty());
11169 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011170 }
11171
Douglas Gregorb491ed32011-02-19 21:32:49 +000011172 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011173 // [...] and any given function template specialization F1 is
11174 // eliminated if the set contains a second function template
11175 // specialization whose function template is more specialized
11176 // than the function template of F1 according to the partial
11177 // ordering rules of 14.5.5.2.
11178
11179 // The algorithm specified above is quadratic. We instead use a
11180 // two-pass algorithm (similar to the one used to identify the
11181 // best viable function in an overload set) that identifies the
11182 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011183
11184 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11185 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11186 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011187
Larisse Voufo98b20f12013-07-19 23:00:19 +000011188 // TODO: It looks like FailedCandidates does not serve much purpose
11189 // here, since the no_viable diagnostic has index 0.
11190 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011191 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011192 SourceExpr->getBeginLoc(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011193 S.PDiag(diag::err_addr_ovl_ambiguous)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011194 << Matches[0].second->getDeclName(),
Richard Smith5179eb72016-06-28 19:03:57 +000011195 S.PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011196 << (unsigned)oc_function << (unsigned)ocs_described_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011197 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011198
Douglas Gregorb491ed32011-02-19 21:32:49 +000011199 if (Result != MatchesCopy.end()) {
11200 // Make it the first and only element
11201 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11202 Matches[0].second = cast<FunctionDecl>(*Result);
11203 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011204 } else
11205 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011207
Douglas Gregorb491ed32011-02-19 21:32:49 +000011208 void EliminateAllTemplateMatches() {
11209 // [...] any function template specializations in the set are
11210 // eliminated if the set also contains a non-template function, [...]
11211 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011212 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011213 ++I;
11214 else {
11215 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011216 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011217 }
11218 }
11219 }
11220
Artem Belevich94a55e82015-09-22 17:22:59 +000011221 void EliminateSuboptimalCudaMatches() {
11222 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11223 }
11224
Douglas Gregorb491ed32011-02-19 21:32:49 +000011225public:
11226 void ComplainNoMatchesFound() const {
11227 assert(Matches.empty());
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011228 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011229 << OvlExpr->getName() << TargetFunctionType
11230 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011231 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011232 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11233 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011234 else {
11235 // We have some deduction failure messages. Use them to diagnose
11236 // the function templates, and diagnose the non-template candidates
11237 // normally.
11238 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11239 IEnd = OvlExpr->decls_end();
11240 I != IEnd; ++I)
11241 if (FunctionDecl *Fun =
11242 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011243 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011244 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011245 /*TakingAddress=*/true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011246 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
Richard Smith0d905472013-08-14 00:00:44 +000011247 }
11248 }
11249
Douglas Gregorb491ed32011-02-19 21:32:49 +000011250 bool IsInvalidFormOfPointerToMemberFunction() const {
11251 return TargetTypeIsNonStaticMemberFunction &&
11252 !OvlExprInfo.HasFormOfMemberPointer;
11253 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011254
Douglas Gregorb491ed32011-02-19 21:32:49 +000011255 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11256 // TODO: Should we condition this on whether any functions might
11257 // have matched, or is it more appropriate to do that in callers?
11258 // TODO: a fixit wouldn't hurt.
11259 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11260 << TargetType << OvlExpr->getSourceRange();
11261 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011262
11263 bool IsStaticMemberFunctionFromBoundPointer() const {
11264 return StaticMemberFunctionFromBoundPointer;
11265 }
11266
11267 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011268 S.Diag(OvlExpr->getBeginLoc(),
David Majnemera4f7c7a2013-08-01 06:13:59 +000011269 diag::err_invalid_form_pointer_member_function)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011270 << OvlExpr->getSourceRange();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011271 }
11272
Douglas Gregorb491ed32011-02-19 21:32:49 +000011273 void ComplainOfInvalidConversion() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011274 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11275 << OvlExpr->getName() << TargetType;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011276 }
11277
11278 void ComplainMultipleMatchesFound() const {
11279 assert(Matches.size() > 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011280 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11281 << OvlExpr->getName() << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011282 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11283 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011284 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011285
11286 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11287
Douglas Gregorb491ed32011-02-19 21:32:49 +000011288 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011289
Douglas Gregorb491ed32011-02-19 21:32:49 +000011290 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011291 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011292 return Matches[0].second;
11293 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011294
Douglas Gregorb491ed32011-02-19 21:32:49 +000011295 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011296 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011297 return &Matches[0].first;
11298 }
11299};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011300}
Richard Smith17c00b42014-11-12 01:24:00 +000011301
Douglas Gregorb491ed32011-02-19 21:32:49 +000011302/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11303/// an overloaded function (C++ [over.over]), where @p From is an
11304/// expression with overloaded function type and @p ToType is the type
11305/// we're trying to resolve to. For example:
11306///
11307/// @code
11308/// int f(double);
11309/// int f(int);
11310///
11311/// int (*pfd)(double) = f; // selects f(double)
11312/// @endcode
11313///
11314/// This routine returns the resulting FunctionDecl if it could be
11315/// resolved, and NULL otherwise. When @p Complain is true, this
11316/// routine will emit diagnostics if there is an error.
11317FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011318Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11319 QualType TargetType,
11320 bool Complain,
11321 DeclAccessPair &FoundResult,
11322 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011323 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011324
11325 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11326 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011327 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011328 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011329 bool ShouldComplain = Complain && !Resolver.hasComplained();
11330 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011331 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11332 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11333 else
11334 Resolver.ComplainNoMatchesFound();
11335 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011336 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011337 Resolver.ComplainMultipleMatchesFound();
11338 else if (NumMatches == 1) {
11339 Fn = Resolver.getMatchingFunctionDecl();
11340 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011341 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11342 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011343 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011344 if (Complain) {
11345 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11346 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11347 else
11348 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11349 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011350 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011351
11352 if (pHadMultipleCandidates)
11353 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011354 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011355}
11356
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011357/// Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011358/// resolve that function to a single function that can have its address taken.
11359/// This will modify `Pair` iff it returns non-null.
11360///
11361/// This routine can only realistically succeed if all but one candidates in the
11362/// overload set for SrcExpr cannot have their addresses taken.
11363FunctionDecl *
11364Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11365 DeclAccessPair &Pair) {
11366 OverloadExpr::FindResult R = OverloadExpr::find(E);
11367 OverloadExpr *Ovl = R.Expression;
11368 FunctionDecl *Result = nullptr;
11369 DeclAccessPair DAP;
11370 // Don't use the AddressOfResolver because we're specifically looking for
11371 // cases where we have one overload candidate that lacks
11372 // enable_if/pass_object_size/...
11373 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11374 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11375 if (!FD)
11376 return nullptr;
11377
11378 if (!checkAddressOfFunctionIsAvailable(FD))
11379 continue;
11380
11381 // We have more than one result; quit.
11382 if (Result)
11383 return nullptr;
11384 DAP = I.getPair();
11385 Result = FD;
11386 }
11387
11388 if (Result)
11389 Pair = DAP;
11390 return Result;
11391}
11392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011393/// Given an overloaded function, tries to turn it into a non-overloaded
George Burgess IVbeca4a32016-06-08 00:34:22 +000011394/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11395/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011396/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011397///
11398/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11399/// Otherwise, returns true. This may emit diagnostics and return true.
11400bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011401 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011402 Expr *E = SrcExpr.get();
11403 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11404
11405 DeclAccessPair DAP;
11406 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
Erich Keane3efe0022018-07-20 14:13:28 +000011407 if (!Found || Found->isCPUDispatchMultiVersion() ||
11408 Found->isCPUSpecificMultiVersion())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011409 return false;
11410
11411 // Emitting multiple diagnostics for a function that is both inaccessible and
11412 // unavailable is consistent with our behavior elsewhere. So, always check
11413 // for both.
11414 DiagnoseUseOfDecl(Found, E->getExprLoc());
11415 CheckAddressOfMemberAccess(E, DAP);
11416 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011417 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011418 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11419 else
11420 SrcExpr = Fixed;
11421 return true;
11422}
11423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011424/// Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011425/// resolve that overloaded function expression down to a single function.
11426///
11427/// This routine can only resolve template-ids that refer to a single function
11428/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011429/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011430/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011431///
11432/// If no template-ids are found, no diagnostics are emitted and NULL is
11433/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011434FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011435Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011436 bool Complain,
11437 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011438 // C++ [over.over]p1:
11439 // [...] [Note: any redundant set of parentheses surrounding the
11440 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011441 // C++ [over.over]p1:
11442 // [...] The overloaded function name can be preceded by the &
11443 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011444
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011445 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011446 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011447 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011448
11449 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011450 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011451 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011452
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011453 // Look through all of the overloaded functions, searching for one
11454 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011455 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011456 for (UnresolvedSetIterator I = ovl->decls_begin(),
11457 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011458 // C++0x [temp.arg.explicit]p3:
11459 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011460 // where deduction is not done, if a template argument list is
11461 // specified and it, along with any default template arguments,
11462 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011463 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011464 FunctionTemplateDecl *FunctionTemplate
11465 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011466
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011467 // C++ [over.over]p2:
11468 // If the name is a function template, template argument deduction is
11469 // done (14.8.2.2), and if the argument deduction succeeds, the
11470 // resulting template argument list is used to generate a single
11471 // function template specialization, which is added to the set of
11472 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011473 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011474 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011475 if (TemplateDeductionResult Result
11476 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011477 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011478 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011479 // Make a note of the failed deduction for diagnostics.
11480 // TODO: Actually use the failed-deduction info?
11481 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011482 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011483 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011484 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011485 }
11486
John McCall0009fcc2011-04-26 20:42:42 +000011487 assert(Specialization && "no specialization and no error?");
11488
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011489 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011490 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011491 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011492 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11493 << ovl->getName();
11494 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011495 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011496 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011497 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011498
John McCall0009fcc2011-04-26 20:42:42 +000011499 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011500 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011502
Richard Smith9095e5b2016-11-01 01:31:23 +000011503 if (Matched &&
11504 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011505 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011506
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011507 return Matched;
11508}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011509
John McCall50a2c2c2011-10-11 23:14:30 +000011510// Resolve and fix an overloaded expression that can be resolved
11511// because it identifies a single function template specialization.
11512//
Douglas Gregor1beec452011-03-12 01:48:56 +000011513// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011514//
11515// Return true if it was logically possible to so resolve the
11516// expression, regardless of whether or not it succeeded. Always
11517// returns true if 'complain' is set.
11518bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11519 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011520 bool complain, SourceRange OpRangeForComplaining,
11521 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011522 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011523 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011524
John McCall50a2c2c2011-10-11 23:14:30 +000011525 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011526
John McCall0009fcc2011-04-26 20:42:42 +000011527 DeclAccessPair found;
11528 ExprResult SingleFunctionExpression;
11529 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11530 ovl.Expression, /*complain*/ false, &found)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011531 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011532 SrcExpr = ExprError();
11533 return true;
11534 }
John McCall0009fcc2011-04-26 20:42:42 +000011535
11536 // It is only correct to resolve to an instance method if we're
11537 // resolving a form that's permitted to be a pointer to member.
11538 // Otherwise we'll end up making a bound member expression, which
11539 // is illegal in all the contexts we resolve like this.
11540 if (!ovl.HasFormOfMemberPointer &&
11541 isa<CXXMethodDecl>(fn) &&
11542 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011543 if (!complain) return false;
11544
11545 Diag(ovl.Expression->getExprLoc(),
11546 diag::err_bound_member_function)
11547 << 0 << ovl.Expression->getSourceRange();
11548
11549 // TODO: I believe we only end up here if there's a mix of
11550 // static and non-static candidates (otherwise the expression
11551 // would have 'bound member' type, not 'overload' type).
11552 // Ideally we would note which candidate was chosen and why
11553 // the static candidates were rejected.
11554 SrcExpr = ExprError();
11555 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011556 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011557
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011558 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011559 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011560 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011561
11562 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011563 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011564 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011565 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011566 if (SingleFunctionExpression.isInvalid()) {
11567 SrcExpr = ExprError();
11568 return true;
11569 }
11570 }
John McCall0009fcc2011-04-26 20:42:42 +000011571 }
11572
11573 if (!SingleFunctionExpression.isUsable()) {
11574 if (complain) {
11575 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11576 << ovl.Expression->getName()
11577 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011578 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011579 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011580 NoteAllOverloadCandidates(SrcExpr.get());
11581
11582 SrcExpr = ExprError();
11583 return true;
11584 }
11585
11586 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011587 }
11588
John McCall50a2c2c2011-10-11 23:14:30 +000011589 SrcExpr = SingleFunctionExpression;
11590 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011591}
11592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011593/// Add a single candidate to the overload set.
Douglas Gregorcabea402009-09-22 15:41:20 +000011594static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011595 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011596 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011597 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011598 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011599 bool PartialOverloading,
11600 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011601 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011602 if (isa<UsingShadowDecl>(Callee))
11603 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11604
Douglas Gregorcabea402009-09-22 15:41:20 +000011605 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011606 if (ExplicitTemplateArgs) {
11607 assert(!KnownValid && "Explicit template arguments?");
11608 return;
11609 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011610 // Prevent ill-formed function decls to be added as overload candidates.
11611 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11612 return;
11613
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011614 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11615 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011616 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011617 return;
John McCalld14a8642009-11-21 08:51:07 +000011618 }
11619
11620 if (FunctionTemplateDecl *FuncTemplate
11621 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011622 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011623 ExplicitTemplateArgs, Args, CandidateSet,
11624 /*SuppressUsedConversions=*/false,
11625 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011626 return;
11627 }
11628
Richard Smith95ce4f62011-06-26 22:19:54 +000011629 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011632/// Add the overload candidates named by callee and/or found by argument
Douglas Gregorcabea402009-09-22 15:41:20 +000011633/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011634void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011635 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011636 OverloadCandidateSet &CandidateSet,
11637 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011638
11639#ifndef NDEBUG
11640 // Verify that ArgumentDependentLookup is consistent with the rules
11641 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011642 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011643 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11644 // and let Y be the lookup set produced by argument dependent
11645 // lookup (defined as follows). If X contains
11646 //
11647 // -- a declaration of a class member, or
11648 //
11649 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011650 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011651 //
11652 // -- a declaration that is neither a function or a function
11653 // template
11654 //
11655 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011656
John McCall57500772009-12-16 12:17:52 +000011657 if (ULE->requiresADL()) {
11658 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11659 E = ULE->decls_end(); I != E; ++I) {
11660 assert(!(*I)->getDeclContext()->isRecord());
11661 assert(isa<UsingShadowDecl>(*I) ||
11662 !(*I)->getDeclContext()->isFunctionOrMethod());
11663 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011664 }
11665 }
11666#endif
11667
John McCall57500772009-12-16 12:17:52 +000011668 // It would be nice to avoid this copy.
11669 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011670 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011671 if (ULE->hasExplicitTemplateArgs()) {
11672 ULE->copyTemplateArgumentsInto(TABuffer);
11673 ExplicitTemplateArgs = &TABuffer;
11674 }
11675
11676 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11677 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011678 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11679 CandidateSet, PartialOverloading,
11680 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011681
John McCall57500772009-12-16 12:17:52 +000011682 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011683 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011684 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011685 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011686}
John McCalld681c392009-12-16 08:11:27 +000011687
Richard Smith0603bbb2013-06-12 22:56:54 +000011688/// Determine whether a declaration with the specified name could be moved into
11689/// a different namespace.
11690static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11691 switch (Name.getCXXOverloadedOperator()) {
11692 case OO_New: case OO_Array_New:
11693 case OO_Delete: case OO_Array_Delete:
11694 return false;
11695
11696 default:
11697 return true;
11698 }
11699}
11700
Richard Smith998a5912011-06-05 22:42:48 +000011701/// Attempt to recover from an ill-formed use of a non-dependent name in a
11702/// template, where the non-dependent name was declared after the template
11703/// was defined. This is common in code written for a compilers which do not
11704/// correctly implement two-stage name lookup.
11705///
11706/// Returns true if a viable candidate was found and a diagnostic was issued.
11707static bool
11708DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11709 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011710 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011711 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011712 ArrayRef<Expr *> Args,
11713 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011714 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011715 return false;
11716
11717 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011718 if (DC->isTransparentContext())
11719 continue;
11720
Richard Smith998a5912011-06-05 22:42:48 +000011721 SemaRef.LookupQualifiedName(R, DC);
11722
11723 if (!R.empty()) {
11724 R.suppressDiagnostics();
11725
11726 if (isa<CXXRecordDecl>(DC)) {
11727 // Don't diagnose names we find in classes; we get much better
11728 // diagnostics for these from DiagnoseEmptyLookup.
11729 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011730 if (DoDiagnoseEmptyLookup)
11731 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011732 return false;
11733 }
11734
Richard Smith100b24a2014-04-17 01:52:14 +000011735 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011736 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11737 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011738 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011739 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011740
11741 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011742 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011743 // No viable functions. Don't bother the user with notes for functions
11744 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011745 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011746 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011747 }
Richard Smith998a5912011-06-05 22:42:48 +000011748
11749 // Find the namespaces where ADL would have looked, and suggest
11750 // declaring the function there instead.
11751 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11752 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011753 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011754 AssociatedNamespaces,
11755 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011756 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011757 if (canBeDeclaredInNamespace(R.getLookupName())) {
11758 DeclContext *Std = SemaRef.getStdNamespace();
11759 for (Sema::AssociatedNamespaceSet::iterator
11760 it = AssociatedNamespaces.begin(),
11761 end = AssociatedNamespaces.end(); it != end; ++it) {
11762 // Never suggest declaring a function within namespace 'std'.
11763 if (Std && Std->Encloses(*it))
11764 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011765
Richard Smith0603bbb2013-06-12 22:56:54 +000011766 // Never suggest declaring a function within a namespace with a
11767 // reserved name, like __gnu_cxx.
11768 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11769 if (NS &&
11770 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11771 continue;
11772
11773 SuggestedNamespaces.insert(*it);
11774 }
Richard Smith998a5912011-06-05 22:42:48 +000011775 }
11776
11777 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11778 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011779 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011780 SemaRef.Diag(Best->Function->getLocation(),
11781 diag::note_not_found_by_two_phase_lookup)
11782 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011783 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011784 SemaRef.Diag(Best->Function->getLocation(),
11785 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011786 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011787 } else {
11788 // FIXME: It would be useful to list the associated namespaces here,
11789 // but the diagnostics infrastructure doesn't provide a way to produce
11790 // a localized representation of a list of items.
11791 SemaRef.Diag(Best->Function->getLocation(),
11792 diag::note_not_found_by_two_phase_lookup)
11793 << R.getLookupName() << 2;
11794 }
11795
11796 // Try to recover by calling this function.
11797 return true;
11798 }
11799
11800 R.clear();
11801 }
11802
11803 return false;
11804}
11805
11806/// Attempt to recover from ill-formed use of a non-dependent operator in a
11807/// template, where the non-dependent operator was declared after the template
11808/// was defined.
11809///
11810/// Returns true if a viable candidate was found and a diagnostic was issued.
11811static bool
11812DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11813 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011814 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011815 DeclarationName OpName =
11816 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11817 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11818 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011819 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011820 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011821}
11822
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011823namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011824class BuildRecoveryCallExprRAII {
11825 Sema &SemaRef;
11826public:
11827 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11828 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11829 SemaRef.IsBuildingRecoveryCallExpr = true;
11830 }
11831
11832 ~BuildRecoveryCallExprRAII() {
11833 SemaRef.IsBuildingRecoveryCallExpr = false;
11834 }
11835};
11836
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011837}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011838
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011839static std::unique_ptr<CorrectionCandidateCallback>
11840MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11841 bool HasTemplateArgs, bool AllowTypoCorrection) {
11842 if (!AllowTypoCorrection)
11843 return llvm::make_unique<NoTypoCorrectionCCC>();
11844 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11845 HasTemplateArgs, ME);
11846}
11847
John McCalld681c392009-12-16 08:11:27 +000011848/// Attempts to recover from a call where no functions were found.
11849///
11850/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011851static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011852BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011853 UnresolvedLookupExpr *ULE,
11854 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011855 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011856 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011857 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011858 // Do not try to recover if it is already building a recovery call.
11859 // This stops infinite loops for template instantiations like
11860 //
11861 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11862 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11863 //
11864 if (SemaRef.IsBuildingRecoveryCallExpr)
11865 return ExprError();
11866 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011867
11868 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011869 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011870 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011871
John McCall57500772009-12-16 12:17:52 +000011872 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011873 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011874 if (ULE->hasExplicitTemplateArgs()) {
11875 ULE->copyTemplateArgumentsInto(TABuffer);
11876 ExplicitTemplateArgs = &TABuffer;
11877 }
11878
John McCalld681c392009-12-16 08:11:27 +000011879 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11880 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011881 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011882 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011883 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011884 ExplicitTemplateArgs, Args,
11885 &DoDiagnoseEmptyLookup) &&
11886 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11887 S, SS, R,
11888 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11889 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11890 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011891 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011892
John McCall57500772009-12-16 12:17:52 +000011893 assert(!R.empty() && "lookup results empty despite recovery");
11894
Richard Smith151c4562016-12-20 21:35:28 +000011895 // If recovery created an ambiguity, just bail out.
11896 if (R.isAmbiguous()) {
11897 R.suppressDiagnostics();
11898 return ExprError();
11899 }
11900
John McCall57500772009-12-16 12:17:52 +000011901 // Build an implicit member call if appropriate. Just drop the
11902 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011903 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011904 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011905 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11906 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011907 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011908 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011909 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011910 else
11911 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11912
11913 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011914 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011915
11916 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011917 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011918 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011919 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011920 MultiExprArg(Args.data(), Args.size()),
11921 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011922}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011923
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011924/// Constructs and populates an OverloadedCandidateSet from
Sam Panzer0f384432012-08-21 00:52:01 +000011925/// the given function.
11926/// \returns true when an the ExprResult output parameter has been set.
11927bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11928 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011929 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011930 SourceLocation RParenLoc,
11931 OverloadCandidateSet *CandidateSet,
11932 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011933#ifndef NDEBUG
11934 if (ULE->requiresADL()) {
11935 // To do ADL, we must have found an unqualified name.
11936 assert(!ULE->getQualifier() && "qualified name with ADL");
11937
11938 // We don't perform ADL for implicit declarations of builtins.
11939 // Verify that this was correctly set up.
11940 FunctionDecl *F;
11941 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11942 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11943 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011944 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011945
John McCall57500772009-12-16 12:17:52 +000011946 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011947 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011948 }
John McCall57500772009-12-16 12:17:52 +000011949#endif
11950
John McCall4124c492011-10-17 18:40:02 +000011951 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011952 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011953 *Result = ExprError();
11954 return true;
11955 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011956
John McCall57500772009-12-16 12:17:52 +000011957 // Add the functions denoted by the callee to the set of candidate
11958 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011959 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011960
Hans Wennborgb2747382015-06-12 21:23:23 +000011961 if (getLangOpts().MSVCCompat &&
11962 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011963 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11964
11965 OverloadCandidateSet::iterator Best;
11966 if (CandidateSet->empty() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011967 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
Hans Wennborg64937c62015-06-11 21:21:57 +000011968 OR_No_Viable_Function) {
11969 // In Microsoft mode, if we are inside a template class member function then
11970 // create a type dependent CallExpr. The goal is to postpone name lookup
11971 // to instantiation time to be able to search into type dependent base
11972 // classes.
11973 CallExpr *CE = new (Context) CallExpr(
11974 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011975 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011976 CE->setValueDependent(true);
11977 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011978 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011979 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011980 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011981 }
John McCalld681c392009-12-16 08:11:27 +000011982
Hans Wennborg64937c62015-06-11 21:21:57 +000011983 if (CandidateSet->empty())
11984 return false;
11985
John McCall4124c492011-10-17 18:40:02 +000011986 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011987 return false;
11988}
John McCall4124c492011-10-17 18:40:02 +000011989
Sam Panzer0f384432012-08-21 00:52:01 +000011990/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11991/// the completed call expression. If overload resolution fails, emits
11992/// diagnostics and returns ExprError()
11993static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11994 UnresolvedLookupExpr *ULE,
11995 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011996 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011997 SourceLocation RParenLoc,
11998 Expr *ExecConfig,
11999 OverloadCandidateSet *CandidateSet,
12000 OverloadCandidateSet::iterator *Best,
12001 OverloadingResult OverloadResult,
12002 bool AllowTypoCorrection) {
12003 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012004 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012005 RParenLoc, /*EmptyLookup=*/true,
12006 AllowTypoCorrection);
12007
12008 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000012009 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000012010 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000012011 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012012 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12013 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012014 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012015 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12016 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000012017 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012018
Richard Smith998a5912011-06-05 22:42:48 +000012019 case OR_No_Viable_Function: {
12020 // Try to recover by looking for viable functions which the user might
12021 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000012022 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012023 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000012024 /*EmptyLookup=*/false,
12025 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000012026 if (!Recovery.isInvalid())
12027 return Recovery;
12028
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012029 // If the user passes in a function that we can't take the address of, we
12030 // generally end up emitting really bad error messages. Here, we attempt to
12031 // emit better ones.
12032 for (const Expr *Arg : Args) {
12033 if (!Arg->getType()->isFunctionType())
12034 continue;
12035 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12036 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12037 if (FD &&
12038 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12039 Arg->getExprLoc()))
12040 return ExprError();
12041 }
12042 }
12043
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012044 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012045 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012046 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012047 break;
Richard Smith998a5912011-06-05 22:42:48 +000012048 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012049
12050 case OR_Ambiguous:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012051 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12052 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012053 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012054 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012055
Sam Panzer0f384432012-08-21 00:52:01 +000012056 case OR_Deleted: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012057 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12058 << (*Best)->Function->isDeleted() << ULE->getName()
12059 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12060 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012061 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000012062
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012063 // We emitted an error for the unavailable/deleted function call but keep
Sam Panzer0f384432012-08-21 00:52:01 +000012064 // the call in the AST.
12065 FunctionDecl *FDecl = (*Best)->Function;
12066 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012067 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12068 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000012069 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012070 }
12071
Douglas Gregorb412e172010-07-25 18:17:45 +000012072 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000012073 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012074}
12075
George Burgess IV7204ed92016-01-07 02:26:57 +000012076static void markUnaddressableCandidatesUnviable(Sema &S,
12077 OverloadCandidateSet &CS) {
12078 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12079 if (I->Viable &&
12080 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12081 I->Viable = false;
12082 I->FailureKind = ovl_fail_addr_not_available;
12083 }
12084 }
12085}
12086
Sam Panzer0f384432012-08-21 00:52:01 +000012087/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12088/// (which eventually refers to the declaration Func) and the call
12089/// arguments Args/NumArgs, attempt to resolve the function call down
12090/// to a specific function. If overload resolution succeeds, returns
12091/// the call expression produced by overload resolution.
12092/// Otherwise, emits diagnostics and returns ExprError.
12093ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12094 UnresolvedLookupExpr *ULE,
12095 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012096 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012097 SourceLocation RParenLoc,
12098 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000012099 bool AllowTypoCorrection,
12100 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000012101 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12102 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000012103 ExprResult result;
12104
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012105 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12106 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000012107 return result;
12108
George Burgess IV7204ed92016-01-07 02:26:57 +000012109 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12110 // functions that aren't addressible are considered unviable.
12111 if (CalleesAddressIsTaken)
12112 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12113
Sam Panzer0f384432012-08-21 00:52:01 +000012114 OverloadCandidateSet::iterator Best;
12115 OverloadingResult OverloadResult =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012116 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
Sam Panzer0f384432012-08-21 00:52:01 +000012117
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012118 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012119 RParenLoc, ExecConfig, &CandidateSet,
12120 &Best, OverloadResult,
12121 AllowTypoCorrection);
12122}
12123
John McCall4c4c1df2010-01-26 03:27:55 +000012124static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000012125 return Functions.size() > 1 ||
12126 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12127}
12128
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012129/// Create a unary operation that may resolve to an overloaded
Douglas Gregor084d8552009-03-13 23:49:33 +000012130/// operator.
12131///
12132/// \param OpLoc The location of the operator itself (e.g., '*').
12133///
Craig Toppera92ffb02015-12-10 08:51:49 +000012134/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000012135///
James Dennett18348b62012-06-22 08:52:37 +000012136/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000012137/// considered by overload resolution. The caller needs to build this
12138/// set based on the context using, e.g.,
12139/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12140/// set should not contain any member functions; those will be added
12141/// by CreateOverloadedUnaryOp().
12142///
James Dennett91738ff2012-06-22 10:32:46 +000012143/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000012144ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000012145Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012146 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012147 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012148 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12149 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12150 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012151 // TODO: provide better source location info.
12152 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012153
John McCall4124c492011-10-17 18:40:02 +000012154 if (checkPlaceholderForOverload(*this, Input))
12155 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012156
Craig Topperc3ec1492014-05-26 06:22:03 +000012157 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012158 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012159
Douglas Gregor084d8552009-03-13 23:49:33 +000012160 // For post-increment and post-decrement, add the implicit '0' as
12161 // the second argument, so that we know this is a post-increment or
12162 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012163 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012164 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012165 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12166 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012167 NumArgs = 2;
12168 }
12169
Richard Smithe54c3072013-05-05 15:51:06 +000012170 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12171
Douglas Gregor084d8552009-03-13 23:49:33 +000012172 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012173 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012174 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
Aaron Ballmana5038552018-01-09 13:07:03 +000012175 VK_RValue, OK_Ordinary, OpLoc, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012176
Craig Topperc3ec1492014-05-26 06:22:03 +000012177 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012178 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012179 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012180 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012181 /*ADL*/ true, IsOverloaded(Fns),
12182 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012183 return new (Context)
12184 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012185 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012186 }
12187
12188 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012189 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012190
12191 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012192 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012193
12194 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012195 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012196
John McCall4c4c1df2010-01-26 03:27:55 +000012197 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000012198 if (PerformADL) {
12199 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12200 /*ExplicitTemplateArgs*/nullptr,
12201 CandidateSet);
12202 }
John McCall4c4c1df2010-01-26 03:27:55 +000012203
Douglas Gregor084d8552009-03-13 23:49:33 +000012204 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012205 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012206
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012207 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12208
Douglas Gregor084d8552009-03-13 23:49:33 +000012209 // Perform overload resolution.
12210 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012211 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012212 case OR_Success: {
12213 // We found a built-in operator or an overloaded operator.
12214 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012215
Douglas Gregor084d8552009-03-13 23:49:33 +000012216 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012217 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012218 // We matched an overloaded operator. Build a call to that
12219 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012220
Douglas Gregor084d8552009-03-13 23:49:33 +000012221 // Convert the arguments.
12222 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012223 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012224
John Wiegley01296292011-04-08 18:41:53 +000012225 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012226 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012227 Best->FoundDecl, Method);
12228 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012229 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012230 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012231 } else {
12232 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012233 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012234 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012235 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012236 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012237 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012238 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012239 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012240 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012241 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012242 }
12243
Douglas Gregor084d8552009-03-13 23:49:33 +000012244 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012245 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012246 Base, HadMultipleCandidates,
12247 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012248 if (FnExpr.isInvalid())
12249 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012250
Richard Smithc1564702013-11-15 02:58:23 +000012251 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012252 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012253 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12254 ResultTy = ResultTy.getNonLValueExprType(Context);
12255
Eli Friedman030eee42009-11-18 03:58:17 +000012256 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012257 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012258 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012259 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012260
Alp Toker314cc812014-01-25 16:55:45 +000012261 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012262 return ExprError();
12263
George Burgess IVce6284b2017-01-28 02:19:40 +000012264 if (CheckFunctionCall(FnDecl, TheCall,
12265 FnDecl->getType()->castAs<FunctionProtoType>()))
12266 return ExprError();
12267
John McCallb268a282010-08-23 23:25:46 +000012268 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012269 } else {
12270 // We matched a built-in operator. Convert the arguments, then
12271 // break out so that we will build the appropriate built-in
12272 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012273 ExprResult InputRes = PerformImplicitConversion(
Richard Smith1ef75542018-06-27 20:30:34 +000012274 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12275 CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012276 if (InputRes.isInvalid())
12277 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012278 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012279 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012280 }
John Wiegley01296292011-04-08 18:41:53 +000012281 }
12282
12283 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012284 // This is an erroneous use of an operator which can be overloaded by
12285 // a non-member function. Check for non-member operators which were
12286 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012287 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012288 // FIXME: Recover by calling the found function.
12289 return ExprError();
12290
John Wiegley01296292011-04-08 18:41:53 +000012291 // No viable function; fall through to handling this as a
12292 // built-in operator, which will produce an error message for us.
12293 break;
12294
12295 case OR_Ambiguous:
12296 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12297 << UnaryOperator::getOpcodeStr(Opc)
12298 << Input->getType()
12299 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012300 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012301 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12302 return ExprError();
12303
12304 case OR_Deleted:
12305 Diag(OpLoc, diag::err_ovl_deleted_oper)
12306 << Best->Function->isDeleted()
12307 << UnaryOperator::getOpcodeStr(Opc)
12308 << getDeletedOrUnavailableSuffix(Best->Function)
12309 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012310 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012311 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012312 return ExprError();
12313 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012314
12315 // Either we found no viable overloaded operator or we matched a
12316 // built-in operator. In either case, fall through to trying to
12317 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012318 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012319}
12320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012321/// Create a binary operation that may resolve to an overloaded
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012322/// operator.
12323///
12324/// \param OpLoc The location of the operator itself (e.g., '+').
12325///
Craig Toppera92ffb02015-12-10 08:51:49 +000012326/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012327///
James Dennett18348b62012-06-22 08:52:37 +000012328/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012329/// considered by overload resolution. The caller needs to build this
12330/// set based on the context using, e.g.,
12331/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12332/// set should not contain any member functions; those will be added
12333/// by CreateOverloadedBinOp().
12334///
12335/// \param LHS Left-hand argument.
12336/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012337ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012338Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012339 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012340 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012341 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012342 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012343 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012344
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012345 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12346 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12347
12348 // If either side is type-dependent, create an appropriate dependent
12349 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012350 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012351 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012352 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012353 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012354 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012355 return new (Context) BinaryOperator(
12356 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012357 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012358
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012359 return new (Context) CompoundAssignOperator(
12360 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12361 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012362 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012363 }
John McCall4c4c1df2010-01-26 03:27:55 +000012364
12365 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012366 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012367 // TODO: provide better source location info in DNLoc component.
12368 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012369 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012370 = UnresolvedLookupExpr::Create(Context, NamingClass,
12371 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012372 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012373 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012374 return new (Context)
12375 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012376 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012377 }
12378
John McCall4124c492011-10-17 18:40:02 +000012379 // Always do placeholder-like conversions on the RHS.
12380 if (checkPlaceholderForOverload(*this, Args[1]))
12381 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012382
John McCall526ab472011-10-25 17:37:35 +000012383 // Do placeholder-like conversion on the LHS; note that we should
12384 // not get here with a PseudoObject LHS.
12385 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012386 if (checkPlaceholderForOverload(*this, Args[0]))
12387 return ExprError();
12388
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012389 // If this is the assignment operator, we only perform overload resolution
12390 // if the left-hand side is a class or enumeration type. This is actually
12391 // a hack. The standard requires that we do overload resolution between the
12392 // various built-in candidates, but as DR507 points out, this can lead to
12393 // problems. So we do it this way, which pretty much follows what GCC does.
12394 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012395 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012396 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012397
John McCalle26a8722010-12-04 08:14:53 +000012398 // If this is the .* operator, which is not overloadable, just
12399 // create a built-in binary operator.
12400 if (Opc == BO_PtrMemD)
12401 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12402
Douglas Gregor084d8552009-03-13 23:49:33 +000012403 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012404 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012405
12406 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012407 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012408
12409 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012410 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012411
Richard Smith0daabd72014-09-23 20:31:39 +000012412 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12413 // performed for an assignment operator (nor for operator[] nor operator->,
12414 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012415 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012416 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12417 /*ExplicitTemplateArgs*/ nullptr,
12418 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012419
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012420 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012421 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012422
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012423 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12424
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012425 // Perform overload resolution.
12426 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012427 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012428 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012429 // We found a built-in operator or an overloaded operator.
12430 FunctionDecl *FnDecl = Best->Function;
12431
12432 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012433 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012434 // We matched an overloaded operator. Build a call to that
12435 // operator.
12436
12437 // Convert the arguments.
12438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012439 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012440 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012441
Chandler Carruth8e543b32010-12-12 08:17:55 +000012442 ExprResult Arg1 =
12443 PerformCopyInitialization(
12444 InitializedEntity::InitializeParameter(Context,
12445 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012446 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012447 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012448 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012449
John Wiegley01296292011-04-08 18:41:53 +000012450 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012451 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012452 Best->FoundDecl, Method);
12453 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012454 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012455 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012456 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012457 } else {
12458 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012459 ExprResult Arg0 = PerformCopyInitialization(
12460 InitializedEntity::InitializeParameter(Context,
12461 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012462 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012463 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012464 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012465
Chandler Carruth8e543b32010-12-12 08:17:55 +000012466 ExprResult Arg1 =
12467 PerformCopyInitialization(
12468 InitializedEntity::InitializeParameter(Context,
12469 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012470 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012471 if (Arg1.isInvalid())
12472 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012473 Args[0] = LHS = Arg0.getAs<Expr>();
12474 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012475 }
12476
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012477 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012478 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012479 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012480 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012481 if (FnExpr.isInvalid())
12482 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012483
Richard Smithc1564702013-11-15 02:58:23 +000012484 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012485 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012486 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12487 ResultTy = ResultTy.getNonLValueExprType(Context);
12488
John McCallb268a282010-08-23 23:25:46 +000012489 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012490 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012491 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012492 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012493
Alp Toker314cc812014-01-25 16:55:45 +000012494 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012495 FnDecl))
12496 return ExprError();
12497
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012498 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012499 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012500 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012501 if (isa<CXXMethodDecl>(FnDecl)) {
12502 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012503 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012504 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012505
12506 // Check for a self move.
12507 if (Op == OO_Equal)
12508 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12509
George Burgess IVce6284b2017-01-28 02:19:40 +000012510 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12511 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12512 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012513
John McCallb268a282010-08-23 23:25:46 +000012514 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012515 } else {
12516 // We matched a built-in operator. Convert the arguments, then
12517 // break out so that we will build the appropriate built-in
12518 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012519 ExprResult ArgsRes0 = PerformImplicitConversion(
12520 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12521 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012522 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012523 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012524 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012525
Richard Smith1ef75542018-06-27 20:30:34 +000012526 ExprResult ArgsRes1 = PerformImplicitConversion(
12527 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12528 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012529 if (ArgsRes1.isInvalid())
12530 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012531 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012532 break;
12533 }
12534 }
12535
Douglas Gregor66950a32009-09-30 21:46:01 +000012536 case OR_No_Viable_Function: {
12537 // C++ [over.match.oper]p9:
12538 // If the operator is the operator , [...] and there are no
12539 // viable functions, then the operator is assumed to be the
12540 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012541 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012542 break;
12543
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012544 // For class as left operand for assignment or compound assignment
Chandler Carruth8e543b32010-12-12 08:17:55 +000012545 // operator do not fall through to handling in built-in, but report that
12546 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012547 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012548 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012549 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012550 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12551 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012552 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012553 if (Args[0]->getType()->isIncompleteType()) {
12554 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12555 << Args[0]->getType()
12556 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12557 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012558 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012559 // This is an erroneous use of an operator which can be overloaded by
12560 // a non-member function. Check for non-member operators which were
12561 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012562 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012563 // FIXME: Recover by calling the found function.
12564 return ExprError();
12565
Douglas Gregor66950a32009-09-30 21:46:01 +000012566 // No viable function; try to create a built-in operation, which will
12567 // produce an error. Then, show the non-viable candidates.
12568 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012570 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012571 "C++ binary operator overloading is missing candidates!");
12572 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012573 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012574 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012575 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012576 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012577
12578 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012579 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012580 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012581 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012582 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012583 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012584 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012585 return ExprError();
12586
12587 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012588 if (isImplicitlyDeleted(Best->Function)) {
12589 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12590 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012591 << Context.getRecordType(Method->getParent())
12592 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012593
Richard Smithde1a4872012-12-28 12:23:24 +000012594 // The user probably meant to call this special member. Just
12595 // explain why it's deleted.
12596 NoteDeletedFunction(Method);
12597 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012598 } else {
12599 Diag(OpLoc, diag::err_ovl_deleted_oper)
12600 << Best->Function->isDeleted()
12601 << BinaryOperator::getOpcodeStr(Opc)
12602 << getDeletedOrUnavailableSuffix(Best->Function)
12603 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12604 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012606 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012607 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012608 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012609
Douglas Gregor66950a32009-09-30 21:46:01 +000012610 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012611 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012612}
12613
John McCalldadc5752010-08-24 06:29:42 +000012614ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012615Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12616 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012617 Expr *Base, Expr *Idx) {
12618 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012619 DeclarationName OpName =
12620 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12621
12622 // If either side is type-dependent, create an appropriate dependent
12623 // expression.
12624 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12625
Craig Topperc3ec1492014-05-26 06:22:03 +000012626 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012627 // CHECKME: no 'operator' keyword?
12628 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12629 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012630 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012631 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012632 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012633 /*ADL*/ true, /*Overloaded*/ false,
12634 UnresolvedSetIterator(),
12635 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012636 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012637
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012638 return new (Context)
12639 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012640 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012641 }
12642
John McCall4124c492011-10-17 18:40:02 +000012643 // Handle placeholders on both operands.
12644 if (checkPlaceholderForOverload(*this, Args[0]))
12645 return ExprError();
12646 if (checkPlaceholderForOverload(*this, Args[1]))
12647 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012648
Sebastian Redladba46e2009-10-29 20:17:01 +000012649 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012650 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012651
12652 // Subscript can only be overloaded as a member function.
12653
12654 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012655 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012656
12657 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012658 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012659
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012660 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12661
Sebastian Redladba46e2009-10-29 20:17:01 +000012662 // Perform overload resolution.
12663 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012664 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012665 case OR_Success: {
12666 // We found a built-in operator or an overloaded operator.
12667 FunctionDecl *FnDecl = Best->Function;
12668
12669 if (FnDecl) {
12670 // We matched an overloaded operator. Build a call to that
12671 // operator.
12672
John McCalla0296f72010-03-19 07:35:19 +000012673 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012674
Sebastian Redladba46e2009-10-29 20:17:01 +000012675 // Convert the arguments.
12676 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012677 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012678 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012679 Best->FoundDecl, Method);
12680 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012681 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012682 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012683
Anders Carlssona68e51e2010-01-29 18:37:50 +000012684 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012685 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012686 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012687 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012688 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012689 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012690 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012691 if (InputInit.isInvalid())
12692 return ExprError();
12693
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012694 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012695
Sebastian Redladba46e2009-10-29 20:17:01 +000012696 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012697 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12698 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012699 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012700 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012701 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012702 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012703 OpLocInfo.getLoc(),
12704 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012705 if (FnExpr.isInvalid())
12706 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012707
Richard Smithc1564702013-11-15 02:58:23 +000012708 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012709 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012710 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12711 ResultTy = ResultTy.getNonLValueExprType(Context);
12712
John McCallb268a282010-08-23 23:25:46 +000012713 CXXOperatorCallExpr *TheCall =
12714 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012715 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012716 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012717 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012718
Alp Toker314cc812014-01-25 16:55:45 +000012719 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012720 return ExprError();
12721
George Burgess IVce6284b2017-01-28 02:19:40 +000012722 if (CheckFunctionCall(Method, TheCall,
12723 Method->getType()->castAs<FunctionProtoType>()))
12724 return ExprError();
12725
John McCallb268a282010-08-23 23:25:46 +000012726 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012727 } else {
12728 // We matched a built-in operator. Convert the arguments, then
12729 // break out so that we will build the appropriate built-in
12730 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012731 ExprResult ArgsRes0 = PerformImplicitConversion(
12732 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12733 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012734 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012735 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012736 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012737
Richard Smith1ef75542018-06-27 20:30:34 +000012738 ExprResult ArgsRes1 = PerformImplicitConversion(
12739 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12740 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012741 if (ArgsRes1.isInvalid())
12742 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012743 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012744
12745 break;
12746 }
12747 }
12748
12749 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012750 if (CandidateSet.empty())
12751 Diag(LLoc, diag::err_ovl_no_oper)
12752 << Args[0]->getType() << /*subscript*/ 0
12753 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12754 else
12755 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12756 << Args[0]->getType()
12757 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012758 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012759 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012760 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012761 }
12762
12763 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012764 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012765 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012766 << Args[0]->getType() << Args[1]->getType()
12767 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012768 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012769 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012770 return ExprError();
12771
12772 case OR_Deleted:
12773 Diag(LLoc, diag::err_ovl_deleted_oper)
12774 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012775 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012776 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012777 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012778 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012779 return ExprError();
12780 }
12781
12782 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012783 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012784}
12785
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012786/// BuildCallToMemberFunction - Build a call to a member
12787/// function. MemExpr is the expression that refers to the member
12788/// function (and includes the object parameter), Args/NumArgs are the
12789/// arguments to the function call (not including the object
12790/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012791/// expression refers to a non-static member function or an overloaded
12792/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012793ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012794Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012795 SourceLocation LParenLoc,
12796 MultiExprArg Args,
12797 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012798 assert(MemExprE->getType() == Context.BoundMemberTy ||
12799 MemExprE->getType() == Context.OverloadTy);
12800
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012801 // Dig out the member expression. This holds both the object
12802 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012803 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012804
John McCall0009fcc2011-04-26 20:42:42 +000012805 // Determine whether this is a call to a pointer-to-member function.
12806 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12807 assert(op->getType() == Context.BoundMemberTy);
12808 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12809
12810 QualType fnType =
12811 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12812
12813 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12814 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012815 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012816
12817 // Check that the object type isn't more qualified than the
12818 // member function we're calling.
12819 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12820
12821 QualType objectType = op->getLHS()->getType();
12822 if (op->getOpcode() == BO_PtrMemI)
12823 objectType = objectType->castAs<PointerType>()->getPointeeType();
12824 Qualifiers objectQuals = objectType.getQualifiers();
12825
12826 Qualifiers difference = objectQuals - funcQuals;
12827 difference.removeObjCGCAttr();
12828 difference.removeAddressSpace();
12829 if (difference) {
12830 std::string qualsString = difference.getAsString();
12831 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12832 << fnType.getUnqualifiedType()
12833 << qualsString
12834 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12835 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012836
John McCall0009fcc2011-04-26 20:42:42 +000012837 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012838 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012839 resultType, valueKind, RParenLoc);
12840
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012841 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012842 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012843 return ExprError();
12844
Craig Topperc3ec1492014-05-26 06:22:03 +000012845 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012846 return ExprError();
12847
Richard Trieu9be9c682013-06-22 02:30:38 +000012848 if (CheckOtherCall(call, proto))
12849 return ExprError();
12850
John McCall0009fcc2011-04-26 20:42:42 +000012851 return MaybeBindToTemporary(call);
12852 }
12853
David Majnemerced8bdf2015-02-25 17:36:15 +000012854 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12855 return new (Context)
12856 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12857
John McCall4124c492011-10-17 18:40:02 +000012858 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012859 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012860 return ExprError();
12861
John McCall10eae182009-11-30 22:42:35 +000012862 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012863 CXXMethodDecl *Method = nullptr;
12864 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12865 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012866 if (isa<MemberExpr>(NakedMemExpr)) {
12867 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012868 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012869 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012870 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012871 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012872 } else {
12873 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012874 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012875
John McCall6e9f8f62009-12-03 04:06:58 +000012876 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012877 Expr::Classification ObjectClassification
12878 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12879 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012880
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012881 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012882 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12883 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012884
John McCall2d74de92009-12-01 22:10:20 +000012885 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012886 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012887 if (UnresExpr->hasExplicitTemplateArgs()) {
12888 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12889 TemplateArgs = &TemplateArgsBuffer;
12890 }
12891
John McCall10eae182009-11-30 22:42:35 +000012892 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12893 E = UnresExpr->decls_end(); I != E; ++I) {
12894
John McCall6e9f8f62009-12-03 04:06:58 +000012895 NamedDecl *Func = *I;
12896 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12897 if (isa<UsingShadowDecl>(Func))
12898 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12899
Douglas Gregor02824322011-01-26 19:30:28 +000012900
Francois Pichet64225792011-01-18 05:04:39 +000012901 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012902 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012903 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012904 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012905 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012906 // If explicit template arguments were provided, we can't call a
12907 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012908 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012909 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012910
John McCalla0296f72010-03-19 07:35:19 +000012911 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012912 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012913 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012914 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012915 AddMethodTemplateCandidate(
12916 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012917 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012918 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012919 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012920 }
Mike Stump11289f42009-09-09 15:08:12 +000012921
John McCall10eae182009-11-30 22:42:35 +000012922 DeclarationName DeclName = UnresExpr->getMemberName();
12923
John McCall4124c492011-10-17 18:40:02 +000012924 UnbridgedCasts.restore();
12925
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012926 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012927 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012928 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012929 case OR_Success:
12930 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012931 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012932 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012933 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12934 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012935 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012936 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012937 // called on both.
12938 // FIXME: This would be more comprehensively addressed by modifying
12939 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12940 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012941 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012942 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12943 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012944 break;
12945
12946 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012947 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012948 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012949 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012951 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012952 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012953
12954 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012955 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012956 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012958 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012959 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012960
12961 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012962 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012963 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012964 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012965 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012966 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012967 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012968 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012969 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012970 }
12971
John McCall16df1e52010-03-30 21:47:33 +000012972 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012973
John McCall2d74de92009-12-01 22:10:20 +000012974 // If overload resolution picked a static member, build a
12975 // non-member call based on that function.
12976 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012977 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12978 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012979 }
12980
John McCall10eae182009-11-30 22:42:35 +000012981 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012982 }
12983
Alp Toker314cc812014-01-25 16:55:45 +000012984 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012985 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12986 ResultType = ResultType.getNonLValueExprType(Context);
12987
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012988 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012989 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012990 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012991 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012992
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012993 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012994 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012995 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012996 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012997
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012998 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012999 // We only need to do this if there was actually an overload; otherwise
13000 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000013001 if (!Method->isStatic()) {
13002 ExprResult ObjectArg =
13003 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13004 FoundDecl, Method);
13005 if (ObjectArg.isInvalid())
13006 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013007 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000013008 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013009
13010 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000013011 const FunctionProtoType *Proto =
13012 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013013 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013014 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000013015 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013016
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013017 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013018
Richard Smith55ce3522012-06-25 20:30:08 +000013019 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000013020 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000013021
George Burgess IVaea6ade2015-09-25 17:53:16 +000013022 // In the case the method to call was not selected by the overloading
13023 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000013024 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000013025 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000013026 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000013027 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000013028 diag::err_ovl_no_viable_member_function_in_call)
13029 << Method << Method->getSourceRange();
13030 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000013031 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000013032 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13033 return ExprError();
13034 }
13035 }
13036
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013037 if ((isa<CXXConstructorDecl>(CurContext) ||
13038 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000013039 TheCall->getMethodDecl()->isPure()) {
13040 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13041
Davide Italianoccb37382015-07-14 23:36:10 +000013042 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13043 MemExpr->performsVirtualDispatch(getLangOpts())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013044 Diag(MemExpr->getBeginLoc(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000013045 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013046 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13047 << MD->getParent()->getDeclName();
Anders Carlsson47061ee2011-05-06 14:25:31 +000013048
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013049 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000013050 if (getLangOpts().AppleKext)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013051 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13052 << MD->getParent()->getDeclName() << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000013053 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000013054 }
Nico Weber5a9259c2016-01-15 21:45:31 +000013055
13056 if (CXXDestructorDecl *DD =
13057 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13058 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000013059 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013060 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
Nico Weber5a9259c2016-01-15 21:45:31 +000013061 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13062 MemExpr->getMemberLoc());
13063 }
13064
John McCallb268a282010-08-23 23:25:46 +000013065 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013066}
13067
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013068/// BuildCallToObjectOfClassType - Build a call to an object of class
13069/// type (C++ [over.call.object]), which can end up invoking an
13070/// overloaded function call operator (@c operator()) or performing a
13071/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000013072ExprResult
John Wiegley01296292011-04-08 18:41:53 +000013073Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000013074 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013075 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013076 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000013077 if (checkPlaceholderForOverload(*this, Obj))
13078 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013079 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000013080
13081 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013082 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000013083 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013084
Nico Weberb58e51c2014-11-19 05:21:39 +000013085 assert(Object.get()->getType()->isRecordType() &&
13086 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000013087 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000013088
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013089 // C++ [over.call.object]p1:
13090 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000013091 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013092 // candidate functions includes at least the function call
13093 // operators of T. The function call operators of T are obtained by
13094 // ordinary lookup of the name operator() in the context of
13095 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000013096 OverloadCandidateSet CandidateSet(LParenLoc,
13097 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000013098 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013099
John Wiegley01296292011-04-08 18:41:53 +000013100 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013101 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013102 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013103
John McCall27b18f82009-11-17 02:14:36 +000013104 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13105 LookupQualifiedName(R, Record->getDecl());
13106 R.suppressDiagnostics();
13107
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013108 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000013109 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000013110 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000013111 Object.get()->Classify(Context), Args, CandidateSet,
13112 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000013113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013114
Douglas Gregorab7897a2008-11-19 22:57:39 +000013115 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013116 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013117 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000013118 //
13119 // operator conversion-type-id () cv-qualifier;
13120 //
13121 // where cv-qualifier is the same cv-qualification as, or a
13122 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000013123 // denotes the type "pointer to function of (P1,...,Pn) returning
13124 // R", or the type "reference to pointer to function of
13125 // (P1,...,Pn) returning R", or the type "reference to function
13126 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000013127 // is also considered as a candidate function. Similarly,
13128 // surrogate call functions are added to the set of candidate
13129 // functions for each conversion function declared in an
13130 // accessible base class provided the function is not hidden
13131 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000013132 const auto &Conversions =
13133 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13134 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000013135 NamedDecl *D = *I;
13136 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13137 if (isa<UsingShadowDecl>(D))
13138 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013139
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013140 // Skip over templated conversion functions; they aren't
13141 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000013142 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013143 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000013144
John McCall6e9f8f62009-12-03 04:06:58 +000013145 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013146 if (!Conv->isExplicit()) {
13147 // Strip the reference type (if any) and then the pointer type (if
13148 // any) to get down to what might be a function type.
13149 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13150 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13151 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013152
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013153 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13154 {
13155 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013156 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013157 }
13158 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013159 }
Mike Stump11289f42009-09-09 15:08:12 +000013160
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013161 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13162
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013163 // Perform overload resolution.
13164 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013165 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
Richard Smith67ef14f2017-09-26 18:37:55 +000013166 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013167 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013168 // Overload resolution succeeded; we'll build the appropriate call
13169 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013170 break;
13171
13172 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013173 if (CandidateSet.empty())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013174 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13175 << Object.get()->getType() << /*call*/ 1
13176 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013177 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013178 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13179 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013180 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013181 break;
13182
13183 case OR_Ambiguous:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013184 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13185 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013186 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013187 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013188
13189 case OR_Deleted:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013190 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13191 << Best->Function->isDeleted() << Object.get()->getType()
13192 << getDeletedOrUnavailableSuffix(Best->Function)
13193 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013195 break;
Mike Stump11289f42009-09-09 15:08:12 +000013196 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013197
Douglas Gregorb412e172010-07-25 18:17:45 +000013198 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013199 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013200
John McCall4124c492011-10-17 18:40:02 +000013201 UnbridgedCasts.restore();
13202
Craig Topperc3ec1492014-05-26 06:22:03 +000013203 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013204 // Since there is no function declaration, this is one of the
13205 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013206 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013207 = cast<CXXConversionDecl>(
13208 Best->Conversions[0].UserDefined.ConversionFunction);
13209
Craig Topperc3ec1492014-05-26 06:22:03 +000013210 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13211 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013212 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13213 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013214 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013215 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013216 // We selected one of the surrogate functions that converts the
13217 // object parameter to a function pointer. Perform the conversion
13218 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013219
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013220 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013221 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013222 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13223 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013224 if (Call.isInvalid())
13225 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013226 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013227 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13228 CK_UserDefinedConversion, Call.get(),
13229 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013230
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013231 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013232 }
13233
Craig Topperc3ec1492014-05-26 06:22:03 +000013234 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013235
Douglas Gregorab7897a2008-11-19 22:57:39 +000013236 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13237 // that calls this method, using Object for the implicit object
13238 // parameter and passing along the remaining arguments.
13239 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013240
13241 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013242 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013243 return ExprError();
13244
Chandler Carruth8e543b32010-12-12 08:17:55 +000013245 const FunctionProtoType *Proto =
13246 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013247
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013248 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013249
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013250 DeclarationNameInfo OpLocInfo(
13251 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13252 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013253 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013254 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013255 OpLocInfo.getLoc(),
13256 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013257 if (NewFn.isInvalid())
13258 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013259
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013260 // Build the full argument list for the method call (the implicit object
13261 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013262 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013263 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013264 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013265
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013266 // Once we've built TheCall, all of the expressions are properly
13267 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013268 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013269 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13270 ResultTy = ResultTy.getNonLValueExprType(Context);
13271
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013272 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013273 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013274 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013275
Alp Toker314cc812014-01-25 16:55:45 +000013276 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013277 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013278
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013279 // We may have default arguments. If so, we need to allocate more
13280 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013281 if (Args.size() < NumParams)
13282 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013283
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013284 bool IsError = false;
13285
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013286 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013287 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013288 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013289 Best->FoundDecl, Method);
13290 if (ObjRes.isInvalid())
13291 IsError = true;
13292 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013293 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013294 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013295
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013296 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013297 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013298 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013299 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013300 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013301
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013302 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013303
John McCalldadc5752010-08-24 06:29:42 +000013304 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013305 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013306 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013307 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013308 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013309
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013310 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013311 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013312 } else {
John McCalldadc5752010-08-24 06:29:42 +000013313 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013314 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13315 if (DefArg.isInvalid()) {
13316 IsError = true;
13317 break;
13318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013319
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013320 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013321 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013322
13323 TheCall->setArg(i + 1, Arg);
13324 }
13325
13326 // If this is a variadic call, handle args passed through "...".
13327 if (Proto->isVariadic()) {
13328 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013329 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013330 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13331 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013332 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013333 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013334 }
13335 }
13336
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013337 if (IsError) return true;
13338
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013339 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013340
Richard Smith55ce3522012-06-25 20:30:08 +000013341 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013342 return true;
13343
John McCalle172be52010-08-24 06:09:16 +000013344 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013345}
13346
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013347/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013348/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013349/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013350ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013351Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13352 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013353 assert(Base->getType()->isRecordType() &&
13354 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013355
John McCall4124c492011-10-17 18:40:02 +000013356 if (checkPlaceholderForOverload(*this, Base))
13357 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013358
John McCallbc077cf2010-02-08 23:07:23 +000013359 SourceLocation Loc = Base->getExprLoc();
13360
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013361 // C++ [over.ref]p1:
13362 //
13363 // [...] An expression x->m is interpreted as (x.operator->())->m
13364 // for a class object x of type T if T::operator->() exists and if
13365 // the operator is selected as the best match function by the
13366 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013367 DeclarationName OpName =
13368 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013369 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013370 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013371
John McCallbc077cf2010-02-08 23:07:23 +000013372 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013373 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013374 return ExprError();
13375
John McCall27b18f82009-11-17 02:14:36 +000013376 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13377 LookupQualifiedName(R, BaseRecord->getDecl());
13378 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013379
13380 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013381 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013382 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013383 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013384 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013385
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013386 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13387
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013388 // Perform overload resolution.
13389 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013390 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013391 case OR_Success:
13392 // Overload resolution succeeded; we'll build the call below.
13393 break;
13394
13395 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013396 if (CandidateSet.empty()) {
13397 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013398 if (NoArrowOperatorFound) {
13399 // Report this specific error to the caller instead of emitting a
13400 // diagnostic, as requested.
13401 *NoArrowOperatorFound = true;
13402 return ExprError();
13403 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013404 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13405 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013406 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013407 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013408 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013409 }
13410 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013411 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013412 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013414 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013415
13416 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013417 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13418 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013419 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013420 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013421
13422 case OR_Deleted:
13423 Diag(OpLoc, diag::err_ovl_deleted_oper)
13424 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013425 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013426 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013427 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013428 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013429 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013430 }
13431
Craig Topperc3ec1492014-05-26 06:22:03 +000013432 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013433
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013434 // Convert the object parameter.
13435 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013436 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013437 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013438 Best->FoundDecl, Method);
13439 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013441 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013442
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013443 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013444 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013445 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013446 if (FnExpr.isInvalid())
13447 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013448
Alp Toker314cc812014-01-25 16:55:45 +000013449 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013450 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13451 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013452 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013453 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013454 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013455
Alp Toker314cc812014-01-25 16:55:45 +000013456 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013457 return ExprError();
13458
13459 if (CheckFunctionCall(Method, TheCall,
13460 Method->getType()->castAs<FunctionProtoType>()))
13461 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013462
13463 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013464}
13465
Richard Smithbcc22fc2012-03-09 08:00:36 +000013466/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13467/// a literal operator described by the provided lookup results.
13468ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13469 DeclarationNameInfo &SuffixInfo,
13470 ArrayRef<Expr*> Args,
13471 SourceLocation LitEndLoc,
13472 TemplateArgumentListInfo *TemplateArgs) {
13473 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013474
Richard Smith100b24a2014-04-17 01:52:14 +000013475 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13476 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013477 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13478 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013479
Richard Smithbcc22fc2012-03-09 08:00:36 +000013480 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13481
Richard Smithbcc22fc2012-03-09 08:00:36 +000013482 // Perform overload resolution. This will usually be trivial, but might need
13483 // to perform substitutions for a literal operator template.
13484 OverloadCandidateSet::iterator Best;
13485 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13486 case OR_Success:
13487 case OR_Deleted:
13488 break;
13489
13490 case OR_No_Viable_Function:
13491 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13492 << R.getLookupName();
13493 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13494 return ExprError();
13495
13496 case OR_Ambiguous:
13497 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13498 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13499 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013500 }
13501
Richard Smithbcc22fc2012-03-09 08:00:36 +000013502 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013503 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013504 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013505 SuffixInfo.getLoc(),
13506 SuffixInfo.getInfo());
13507 if (Fn.isInvalid())
13508 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013509
13510 // Check the argument types. This should almost always be a no-op, except
13511 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013512 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013514 ExprResult InputInit = PerformCopyInitialization(
13515 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13516 SourceLocation(), Args[ArgIdx]);
13517 if (InputInit.isInvalid())
13518 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013519 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013520 }
13521
Alp Toker314cc812014-01-25 16:55:45 +000013522 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013523 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13524 ResultTy = ResultTy.getNonLValueExprType(Context);
13525
Richard Smithc67fdd42012-03-07 08:35:16 +000013526 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013527 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013528 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013529 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13530
Alp Toker314cc812014-01-25 16:55:45 +000013531 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013532 return ExprError();
13533
Craig Topperc3ec1492014-05-26 06:22:03 +000013534 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013535 return ExprError();
13536
13537 return MaybeBindToTemporary(UDL);
13538}
13539
Sam Panzer0f384432012-08-21 00:52:01 +000013540/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13541/// given LookupResult is non-empty, it is assumed to describe a member which
13542/// will be invoked. Otherwise, the function will be found via argument
13543/// dependent lookup.
13544/// CallExpr is set to a valid expression and FRS_Success returned on success,
13545/// otherwise CallExpr is set to ExprError() and some non-success value
13546/// is returned.
13547Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013548Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13549 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013550 const DeclarationNameInfo &NameInfo,
13551 LookupResult &MemberLookup,
13552 OverloadCandidateSet *CandidateSet,
13553 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013554 Scope *S = nullptr;
13555
Richard Smith67ef14f2017-09-26 18:37:55 +000013556 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013557 if (!MemberLookup.empty()) {
13558 ExprResult MemberRef =
13559 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13560 /*IsPtr=*/false, CXXScopeSpec(),
13561 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013562 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013563 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013564 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013565 if (MemberRef.isInvalid()) {
13566 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013567 return FRS_DiagnosticIssued;
13568 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013569 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013570 if (CallExpr->isInvalid()) {
13571 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013572 return FRS_DiagnosticIssued;
13573 }
13574 } else {
13575 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013576 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013577 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013578 NestedNameSpecifierLoc(), NameInfo,
13579 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013580 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013581
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013582 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013583 CandidateSet, CallExpr);
13584 if (CandidateSet->empty() || CandidateSetError) {
13585 *CallExpr = ExprError();
13586 return FRS_NoViableFunction;
13587 }
13588 OverloadCandidateSet::iterator Best;
13589 OverloadingResult OverloadResult =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013590 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
Sam Panzer0f384432012-08-21 00:52:01 +000013591
13592 if (OverloadResult == OR_No_Viable_Function) {
13593 *CallExpr = ExprError();
13594 return FRS_NoViableFunction;
13595 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013596 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013597 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013598 OverloadResult,
13599 /*AllowTypoCorrection=*/false);
13600 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13601 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013602 return FRS_DiagnosticIssued;
13603 }
13604 }
13605 return FRS_Success;
13606}
13607
13608
Douglas Gregorcd695e52008-11-10 20:40:00 +000013609/// FixOverloadedFunctionReference - E is an expression that refers to
13610/// a C++ overloaded function (possibly with some parentheses and
13611/// perhaps a '&' around it). We have resolved the overloaded function
13612/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013613/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013614Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013615 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013616 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013617 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13618 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013619 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013620 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013621
Douglas Gregor51c538b2009-11-20 19:42:02 +000013622 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013623 }
13624
Douglas Gregor51c538b2009-11-20 19:42:02 +000013625 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013626 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13627 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013628 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013629 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013630 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013631 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013632 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013633 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013634
13635 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013636 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013637 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013638 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013639 }
13640
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013641 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13642 if (!GSE->isResultDependent()) {
13643 Expr *SubExpr =
13644 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13645 if (SubExpr == GSE->getResultExpr())
13646 return GSE;
13647
13648 // Replace the resulting type information before rebuilding the generic
13649 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013650 ArrayRef<Expr *> A = GSE->getAssocExprs();
13651 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013652 unsigned ResultIdx = GSE->getResultIndex();
13653 AssocExprs[ResultIdx] = SubExpr;
13654
13655 return new (Context) GenericSelectionExpr(
13656 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13657 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13658 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13659 ResultIdx);
13660 }
13661 // Rather than fall through to the unreachable, return the original generic
13662 // selection expression.
13663 return GSE;
13664 }
13665
Douglas Gregor51c538b2009-11-20 19:42:02 +000013666 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013667 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013668 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13670 if (Method->isStatic()) {
13671 // Do nothing: static member functions aren't any different
13672 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013673 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013674 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013675 // UnresolvedLookupExpr holding an overloaded member function
13676 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013677 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13678 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013679 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013680 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013681
John McCalld14a8642009-11-21 08:51:07 +000013682 assert(isa<DeclRefExpr>(SubExpr)
13683 && "fixed to something other than a decl ref");
13684 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13685 && "fixed to a member ref with no nested name qualifier");
13686
13687 // We have taken the address of a pointer to member
13688 // function. Perform the computation here so that we get the
13689 // appropriate pointer to member type.
13690 QualType ClassType
13691 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13692 QualType MemPtrType
13693 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013694 // Under the MS ABI, lock down the inheritance model now.
13695 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13696 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013697
John McCall7decc9e2010-11-18 06:31:45 +000013698 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13699 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013700 UnOp->getOperatorLoc(), false);
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013701 }
13702 }
John McCall16df1e52010-03-30 21:47:33 +000013703 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13704 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013705 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013706 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013707
John McCalle3027922010-08-25 11:45:40 +000013708 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013709 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013710 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013711 UnOp->getOperatorLoc(), false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013712 }
John McCalld14a8642009-11-21 08:51:07 +000013713
Richard Smith84a0b6d2016-10-18 23:39:12 +000013714 // C++ [except.spec]p17:
13715 // An exception-specification is considered to be needed when:
13716 // - in an expression the function is the unique lookup result or the
13717 // selected member of a set of overloaded functions
13718 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13719 ResolveExceptionSpec(E->getExprLoc(), FPT);
13720
John McCalld14a8642009-11-21 08:51:07 +000013721 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013722 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013724 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013725 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13726 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013727 }
13728
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013729 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13730 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013731 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013732 Fn,
John McCall113bee02012-03-10 09:33:50 +000013733 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013734 ULE->getNameLoc(),
13735 Fn->getType(),
13736 VK_LValue,
13737 Found.getDecl(),
13738 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013739 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013740 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13741 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013742 }
13743
John McCall10eae182009-11-30 22:42:35 +000013744 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013745 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013746 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013747 if (MemExpr->hasExplicitTemplateArgs()) {
13748 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13749 TemplateArgs = &TemplateArgsBuffer;
13750 }
John McCall6b51f282009-11-23 01:53:49 +000013751
John McCall2d74de92009-12-01 22:10:20 +000013752 Expr *Base;
13753
John McCall7decc9e2010-11-18 06:31:45 +000013754 // If we're filling in a static method where we used to have an
13755 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013756 if (MemExpr->isImplicitAccess()) {
13757 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013758 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13759 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013760 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013761 Fn,
John McCall113bee02012-03-10 09:33:50 +000013762 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013763 MemExpr->getMemberLoc(),
13764 Fn->getType(),
13765 VK_LValue,
13766 Found.getDecl(),
13767 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013768 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013769 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13770 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013771 } else {
13772 SourceLocation Loc = MemExpr->getMemberLoc();
13773 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013774 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013775 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013776 Base = new (Context) CXXThisExpr(Loc,
13777 MemExpr->getBaseType(),
13778 /*isImplicit=*/true);
13779 }
John McCall2d74de92009-12-01 22:10:20 +000013780 } else
John McCallc3007a22010-10-26 07:05:15 +000013781 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013782
John McCall4adb38c2011-04-27 00:36:17 +000013783 ExprValueKind valueKind;
13784 QualType type;
13785 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13786 valueKind = VK_LValue;
13787 type = Fn->getType();
13788 } else {
13789 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013790 type = Context.BoundMemberTy;
13791 }
13792
13793 MemberExpr *ME = MemberExpr::Create(
13794 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13795 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13796 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13797 OK_Ordinary);
13798 ME->setHadMultipleCandidates(true);
13799 MarkMemberReferenced(ME);
13800 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013802
John McCallc3007a22010-10-26 07:05:15 +000013803 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013804}
13805
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013806ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013807 DeclAccessPair Found,
13808 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013809 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013810}