blob: a0b9498cdfa16020440a8c3a3b707a80d8e98e52 [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) ||
Alp Toker314cc812014-01-25 16:55:45 +00001108 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001109 return true;
1110
1111 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001112 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001113 //
1114 // As part of this, also check whether one of the member functions
1115 // is static, in which case they are not overloads (C++
1116 // 13.1p2). While not part of the definition of the signature,
1117 // this check is important to determine whether these functions
1118 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001119 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1120 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001121 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001122 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1123 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001124 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001125 (OldMethod->getRefQualifier() == RQ_None ||
1126 NewMethod->getRefQualifier() == RQ_None)) {
1127 // C++0x [over.load]p2:
1128 // - Member function declarations with the same name and the same
1129 // parameter-type-list as well as member function template
1130 // declarations with the same name, the same parameter-type-list, and
1131 // the same template parameter lists cannot be overloaded if any of
1132 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001133 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001134 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001135 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001136 }
1137 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Richard Smith574f4f62013-01-14 05:37:29 +00001140 // We may not have applied the implicit const for a constexpr member
1141 // function yet (because we haven't yet resolved whether this is a static
1142 // or non-static member function). Add it now, on the assumption that this
1143 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001144 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001145 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001146 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001147 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001148 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001149
1150 // We do not allow overloading based off of '__restrict'.
1151 OldQuals &= ~Qualifiers::Restrict;
1152 NewQuals &= ~Qualifiers::Restrict;
1153 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001154 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001157 // Though pass_object_size is placed on parameters and takes an argument, we
1158 // consider it to be a function-level modifier for the sake of function
1159 // identity. Either the function has one or more parameters with
1160 // pass_object_size or it doesn't.
1161 if (functionHasPassObjectSizeParams(New) !=
1162 functionHasPassObjectSizeParams(Old))
1163 return true;
1164
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001165 // enable_if attributes are an order-sensitive part of the signature.
1166 for (specific_attr_iterator<EnableIfAttr>
1167 NewI = New->specific_attr_begin<EnableIfAttr>(),
1168 NewE = New->specific_attr_end<EnableIfAttr>(),
1169 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1170 OldE = Old->specific_attr_end<EnableIfAttr>();
1171 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1172 if (NewI == NewE || OldI == OldE)
1173 return true;
1174 llvm::FoldingSetNodeID NewID, OldID;
1175 NewI->getCond()->Profile(NewID, Context, true);
1176 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001177 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001178 return true;
1179 }
1180
Justin Lebarba122ab2016-03-30 23:30:21 +00001181 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001182 // Don't allow overloading of destructors. (In theory we could, but it
1183 // would be a giant change to clang.)
1184 if (isa<CXXDestructorDecl>(New))
1185 return false;
1186
Artem Belevich94a55e82015-09-22 17:22:59 +00001187 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1188 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001189 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001190 return false;
1191
1192 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1193
Justin Lebar53b000af2016-10-03 16:48:27 +00001194 // Allow overloading of functions with same signature and different CUDA
1195 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001196 return NewTarget != OldTarget;
1197 }
1198
John McCall1f82f242009-11-18 22:49:29 +00001199 // The signatures match; this is not an overload.
1200 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001201}
1202
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001203/// Checks availability of the function depending on the current
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001204/// function context. Inside an unavailable function, unavailability is ignored.
1205///
1206/// \returns true if \arg FD is unavailable and current context is inside
1207/// an available function, false otherwise.
1208bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001209 if (!FD->isUnavailable())
1210 return false;
1211
1212 // Walk up the context of the caller.
1213 Decl *C = cast<Decl>(CurContext);
1214 do {
1215 if (C->isUnavailable())
1216 return false;
1217 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1218 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001219}
1220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001221/// Tries a user-defined conversion from From to ToType.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001222///
1223/// Produces an implicit conversion sequence for when a standard conversion
1224/// is not an option. See TryImplicitConversion for more information.
1225static ImplicitConversionSequence
1226TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
1228 bool AllowExplicit,
1229 bool InOverloadResolution,
1230 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001233 ImplicitConversionSequence ICS;
1234
1235 if (SuppressUserConversions) {
1236 // We're not in the case above, so there is no conversion that
1237 // we can perform.
1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1239 return ICS;
1240 }
1241
1242 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001243 OverloadCandidateSet Conversions(From->getExprLoc(),
1244 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001245 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1246 Conversions, AllowExplicit,
1247 AllowObjCConversionOnExplicit)) {
1248 case OR_Success:
1249 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001250 ICS.setUserDefined();
1251 // C++ [over.ics.user]p4:
1252 // A conversion of an expression of class type to the same class
1253 // type is given Exact Match rank, and a conversion of an
1254 // expression of class type to a base class of that type is
1255 // given Conversion rank, in spite of the fact that a copy
1256 // constructor (i.e., a user-defined conversion function) is
1257 // called for those cases.
1258 if (CXXConstructorDecl *Constructor
1259 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1260 QualType FromCanon
1261 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1262 QualType ToCanon
1263 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1264 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001265 (FromCanon == ToCanon ||
1266 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001267 // Turn this into a "standard" conversion sequence, so that it
1268 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001269 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001270 ICS.setStandard();
1271 ICS.Standard.setAsIdentityConversion();
1272 ICS.Standard.setFromType(From->getType());
1273 ICS.Standard.setAllToTypes(ToType);
1274 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001275 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001276 if (ToCanon != FromCanon)
1277 ICS.Standard.Second = ICK_Derived_To_Base;
1278 }
1279 }
Richard Smith48372b62015-01-27 03:30:40 +00001280 break;
1281
1282 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001283 ICS.setAmbiguous();
1284 ICS.Ambiguous.setFromType(From->getType());
1285 ICS.Ambiguous.setToType(ToType);
1286 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1287 Cand != Conversions.end(); ++Cand)
1288 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001289 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001290 break;
Richard Smith48372b62015-01-27 03:30:40 +00001291
1292 // Fall through.
1293 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001295 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001296 }
1297
1298 return ICS;
1299}
1300
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001301/// TryImplicitConversion - Attempt to perform an implicit conversion
1302/// from the given expression (Expr) to the given type (ToType). This
1303/// function returns an implicit conversion sequence that can be used
1304/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305///
1306/// void f(float f);
1307/// void g(int i) { f(i); }
1308///
1309/// this routine would produce an implicit conversion sequence to
1310/// describe the initialization of f from i, which will be a standard
1311/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1312/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1313//
1314/// Note that this routine only determines how the conversion can be
1315/// performed; it does not actually perform the conversion. As such,
1316/// it will not produce any diagnostics if no conversion is available,
1317/// but will instead return an implicit conversion sequence of kind
1318/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001319///
1320/// If @p SuppressUserConversions, then user-defined conversions are
1321/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001322/// If @p AllowExplicit, then explicit user-defined conversions are
1323/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001324///
1325/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1326/// writeback conversion, which allows __autoreleasing id* parameters to
1327/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001328static ImplicitConversionSequence
1329TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1330 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001332 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001333 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001334 bool AllowObjCWritebackConversion,
1335 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001337 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001338 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001339 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001340 return ICS;
1341 }
1342
David Blaikiebbafb8a2012-03-11 07:00:24 +00001343 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001344 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001345 return ICS;
1346 }
1347
Douglas Gregor836a7e82010-08-11 02:15:33 +00001348 // C++ [over.ics.user]p4:
1349 // A conversion of an expression of class type to the same class
1350 // type is given Exact Match rank, and a conversion of an
1351 // expression of class type to a base class of that type is
1352 // given Conversion rank, in spite of the fact that a copy/move
1353 // constructor (i.e., a user-defined conversion function) is
1354 // called for those cases.
1355 QualType FromType = From->getType();
1356 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001357 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001358 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001359 ICS.setStandard();
1360 ICS.Standard.setAsIdentityConversion();
1361 ICS.Standard.setFromType(FromType);
1362 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregor5ab11652010-04-17 22:01:05 +00001364 // We don't actually check at this point whether there is a valid
1365 // copy/move constructor, since overloading just assumes that it
1366 // exists. When we actually perform initialization, we'll find the
1367 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001368 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
Douglas Gregor5ab11652010-04-17 22:01:05 +00001370 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001371 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001372 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
Douglas Gregor836a7e82010-08-11 02:15:33 +00001374 return ICS;
1375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001377 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1378 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001379 AllowObjCWritebackConversion,
1380 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001381}
1382
John McCall31168b02011-06-15 23:02:42 +00001383ImplicitConversionSequence
1384Sema::TryImplicitConversion(Expr *From, QualType ToType,
1385 bool SuppressUserConversions,
1386 bool AllowExplicit,
1387 bool InOverloadResolution,
1388 bool CStyle,
1389 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001390 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001391 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001392 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001393 AllowObjCWritebackConversion,
1394 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001395}
1396
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001397/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001398/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001399/// converted expression. Flavor is the kind of conversion we're
1400/// performing, used in the error message. If @p AllowExplicit,
1401/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001402ExprResult
1403Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001404 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001405 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001406 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001407}
1408
John Wiegley01296292011-04-08 18:41:53 +00001409ExprResult
1410Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001411 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001412 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001413 if (checkPlaceholderForOverload(*this, From))
1414 return ExprError();
1415
John McCall31168b02011-06-15 23:02:42 +00001416 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1417 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001418 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001419 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001420 if (getLangOpts().ObjC1)
1421 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1422 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001423 ICS = ::TryImplicitConversion(*this, From, ToType,
1424 /*SuppressUserConversions=*/false,
1425 AllowExplicit,
1426 /*InOverloadResolution=*/false,
1427 /*CStyle=*/false,
1428 AllowObjCWritebackConversion,
1429 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001430 return PerformImplicitConversion(From, ToType, ICS, Action);
1431}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001433/// Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001434/// conversion that strips "noexcept" or "noreturn" off the nested function
1435/// type.
1436bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001437 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001438 if (Context.hasSameUnqualifiedType(FromType, ToType))
1439 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001440
John McCall991eb4b2010-12-21 00:44:39 +00001441 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001442 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001443 // where F adds one of the following at most once:
1444 // - a pointer
1445 // - a member pointer
1446 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001447 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001448 CanQualType CanTo = Context.getCanonicalType(ToType);
1449 CanQualType CanFrom = Context.getCanonicalType(FromType);
1450 Type::TypeClass TyClass = CanTo->getTypeClass();
1451 if (TyClass != CanFrom->getTypeClass()) return false;
1452 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1453 if (TyClass == Type::Pointer) {
1454 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1455 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1456 } else if (TyClass == Type::BlockPointer) {
1457 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1458 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1459 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001460 auto ToMPT = CanTo.getAs<MemberPointerType>();
1461 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1462 // A function pointer conversion cannot change the class of the function.
1463 if (ToMPT->getClass() != FromMPT->getClass())
1464 return false;
1465 CanTo = ToMPT->getPointeeType();
1466 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001467 } else {
1468 return false;
1469 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001470
John McCall991eb4b2010-12-21 00:44:39 +00001471 TyClass = CanTo->getTypeClass();
1472 if (TyClass != CanFrom->getTypeClass()) return false;
1473 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1474 return false;
1475 }
1476
Richard Smith3c4f8d22016-10-16 17:54:23 +00001477 const auto *FromFn = cast<FunctionType>(CanFrom);
1478 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001479
Richard Smith6f427402016-10-20 00:01:36 +00001480 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001481 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1482
1483 bool Changed = false;
1484
1485 // Drop 'noreturn' if not present in target type.
1486 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1487 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1488 Changed = true;
1489 }
1490
1491 // Drop 'noexcept' if not present in target type.
1492 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001493 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001494 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00001495 FromFn = cast<FunctionType>(
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00001496 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1497 EST_None)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001498 .getTypePtr());
1499 Changed = true;
1500 }
Artem Belevich55ebd6c2018-04-03 18:29:31 +00001501
Akira Hatanaka98a49332017-09-22 00:41:05 +00001502 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1503 // only if the ExtParameterInfo lists of the two function prototypes can be
1504 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1505 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1506 bool CanUseToFPT, CanUseFromFPT;
1507 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1508 CanUseFromFPT, NewParamInfos) &&
1509 CanUseToFPT && !CanUseFromFPT) {
1510 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1511 ExtInfo.ExtParameterInfos =
1512 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1513 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1514 FromFPT->getParamTypes(), ExtInfo);
1515 FromFn = QT->getAs<FunctionType>();
1516 Changed = true;
1517 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001518 }
1519
1520 if (!Changed)
1521 return false;
1522
John McCall991eb4b2010-12-21 00:44:39 +00001523 assert(QualType(FromFn, 0).isCanonical());
1524 if (QualType(FromFn, 0) != CanTo) return false;
1525
1526 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001527 return true;
1528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001529
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001530/// Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor46188682010-05-18 22:42:18 +00001531/// vector conversion.
1532///
1533/// \param ICK Will be set to the vector conversion kind, if this is a vector
1534/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001535static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001537 // We need at least one of these types to be a vector type to have a vector
1538 // conversion.
1539 if (!ToType->isVectorType() && !FromType->isVectorType())
1540 return false;
1541
1542 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001543 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001544 return false;
1545
1546 // There are no conversions between extended vector types, only identity.
1547 if (ToType->isExtVectorType()) {
1548 // There are no conversions between extended vector types other than the
1549 // identity conversion.
1550 if (FromType->isExtVectorType())
1551 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregor46188682010-05-18 22:42:18 +00001553 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001554 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001555 ICK = ICK_Vector_Splat;
1556 return true;
1557 }
1558 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001559
1560 // We can perform the conversion between vector types in the following cases:
1561 // 1)vector types are equivalent AltiVec and GCC vector types
1562 // 2)lax vector conversions are permitted and the vector types are of the
1563 // same size
1564 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001565 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1566 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001567 ICK = ICK_Vector_Conversion;
1568 return true;
1569 }
Douglas Gregor46188682010-05-18 22:42:18 +00001570 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001571
Douglas Gregor46188682010-05-18 22:42:18 +00001572 return false;
1573}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001574
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001575static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1576 bool InOverloadResolution,
1577 StandardConversionSequence &SCS,
1578 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001579
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580/// IsStandardConversion - Determines whether there is a standard
1581/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1582/// expression From to the type ToType. Standard conversion sequences
1583/// only consider non-class types; for conversions that involve class
1584/// types, use TryImplicitConversion. If a conversion exists, SCS will
1585/// contain the standard conversion sequence required to perform this
1586/// conversion and this routine will return true. Otherwise, this
1587/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001588static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1589 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001590 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001591 bool CStyle,
1592 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001596 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001597 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001598 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001599 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001601 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001602 // abort early. When overloading in C, however, we do permit them.
1603 if (S.getLangOpts().CPlusPlus &&
1604 (FromType->isRecordType() || ToType->isRecordType()))
1605 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001606
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001607 // The first conversion can be an lvalue-to-rvalue conversion,
1608 // array-to-pointer conversion, or function-to-pointer conversion
1609 // (C++ 4p1).
1610
John McCall5c32be02010-08-24 20:38:10 +00001611 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001612 DeclAccessPair AccessPair;
1613 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001615 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001616 // We were able to resolve the address of the overloaded function,
1617 // so we can convert to the type of that function.
1618 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001619 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001620
1621 // we can sometimes resolve &foo<int> regardless of ToType, so check
1622 // if the type matches (identity) or we are converting to bool
1623 if (!S.Context.hasSameUnqualifiedType(
1624 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1625 QualType resultTy;
1626 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001627 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001628 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001629 // otherwise, only a boolean conversion is standard
1630 if (!ToType->isBooleanType())
1631 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633
Chandler Carruthffce2452011-03-29 08:08:18 +00001634 // Check if the "from" expression is taking the address of an overloaded
1635 // function and recompute the FromType accordingly. Take advantage of the
1636 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001637 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1639 if (Method && !Method->isStatic()) {
1640 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1641 "Non-unary operator on non-static member address");
1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1643 == UO_AddrOf &&
1644 "Non-address-of operator on non-static member address");
1645 const Type *ClassType
1646 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1647 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001648 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1649 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1650 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001651 "Non-address-of operator for overloaded function expression");
1652 FromType = S.Context.getPointerType(FromType);
1653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654
Douglas Gregor980fb162010-04-29 18:24:40 +00001655 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001656 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1657 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001658 assert(S.Context.hasSameType(
1659 FromType,
1660 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001661 } else {
1662 return false;
1663 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001664 }
John McCall154a2fd2011-08-30 00:57:29 +00001665 // Lvalue-to-rvalue conversion (C++11 4.1):
1666 // A glvalue (3.10) of a non-function, non-array type T can
1667 // be converted to a prvalue.
1668 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001669 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001670 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001671 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673
Douglas Gregorc79862f2012-04-12 17:51:55 +00001674 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001675 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001676 // of the type of the lvalue ...
1677 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1678 FromType = Atomic->getValueType();
1679
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680 // If T is a non-class type, the type of the rvalue is the
1681 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001682 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1683 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001684 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001685 } else if (FromType->isArrayType()) {
1686 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001687 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688
1689 // An lvalue or rvalue of type "array of N T" or "array of unknown
1690 // bound of T" can be converted to an rvalue of type "pointer to
1691 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001692 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693
John McCall5c32be02010-08-24 20:38:10 +00001694 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001695 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001696 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697
1698 // For the purpose of ranking in overload resolution
1699 // (13.3.3.1.1), this conversion is considered an
1700 // array-to-pointer conversion followed by a qualification
1701 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001702 SCS.Second = ICK_Identity;
1703 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001704 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001705 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001707 }
John McCall086a4642010-11-24 05:12:34 +00001708 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001709 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001710 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001712 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1713 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1714 if (!S.checkAddressOfFunctionIsAvailable(FD))
1715 return false;
1716
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 // An lvalue of function type T can be converted to an rvalue of
1718 // type "pointer to T." The result is a pointer to the
1719 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001720 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001721 } else {
1722 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001723 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001725 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726
1727 // The second conversion can be an integral promotion, floating
1728 // point promotion, integral conversion, floating point conversion,
1729 // floating-integral conversion, pointer conversion,
1730 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001731 // For overloading in C, this can also be a "compatible-type"
1732 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001733 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001734 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001735 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001736 // The unqualified versions of the types are the same: there's no
1737 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001738 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001739 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001740 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001741 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001743 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001744 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001745 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001747 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001748 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001749 SCS.Second = ICK_Complex_Promotion;
1750 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001751 } else if (ToType->isBooleanType() &&
1752 (FromType->isArithmeticType() ||
1753 FromType->isAnyPointerType() ||
1754 FromType->isBlockPointerType() ||
1755 FromType->isMemberPointerType() ||
1756 FromType->isNullPtrType())) {
1757 // Boolean conversions (C++ 4.12).
1758 SCS.Second = ICK_Boolean_Conversion;
1759 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001760 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001761 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001762 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001763 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001765 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001766 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001767 SCS.Second = ICK_Complex_Conversion;
1768 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001769 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1770 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001771 // Complex-real conversions (C99 6.3.1.7)
1772 SCS.Second = ICK_Complex_Real;
1773 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001774 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001775 // FIXME: disable conversions between long double and __float128 if
1776 // their representation is different until there is back end support
1777 // We of course allow this conversion if long double is really double.
1778 if (&S.Context.getFloatTypeSemantics(FromType) !=
1779 &S.Context.getFloatTypeSemantics(ToType)) {
1780 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1781 ToType == S.Context.LongDoubleTy) ||
1782 (FromType == S.Context.LongDoubleTy &&
1783 ToType == S.Context.Float128Ty));
1784 if (Float128AndLongDouble &&
Benjamin Kramer98057952018-01-17 22:56:57 +00001785 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1786 &llvm::APFloat::PPCDoubleDouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001787 return false;
1788 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001789 // Floating point conversions (C++ 4.8).
1790 SCS.Second = ICK_Floating_Conversion;
1791 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001793 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001794 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001795 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001796 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001797 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001799 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001800 SCS.Second = ICK_Block_Pointer_Conversion;
1801 } else if (AllowObjCWritebackConversion &&
1802 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1803 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001804 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1805 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001806 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001807 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001808 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001809 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001811 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001812 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001813 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001814 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001815 SCS.Second = SecondICK;
1816 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001818 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001819 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001820 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001821 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001822 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1823 InOverloadResolution,
1824 SCS, CStyle)) {
1825 SCS.Second = ICK_TransparentUnionConversion;
1826 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001827 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1828 CStyle)) {
1829 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001830 // appropriately.
1831 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001832 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001833 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001834 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001835 SCS.Second = ICK_Zero_Event_Conversion;
1836 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001837 } else if (ToType->isQueueT() &&
1838 From->isIntegerConstantExpr(S.getASTContext()) &&
1839 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1840 SCS.Second = ICK_Zero_Queue_Conversion;
1841 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842 } else {
1843 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001844 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001846 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001847
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001848 // The third conversion can be a function pointer conversion or a
1849 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001850 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001851 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1852 // Function pointer conversions (removing 'noexcept') including removal of
1853 // 'noreturn' (Clang extension).
1854 SCS.Third = ICK_Function_Conversion;
1855 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1856 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001857 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001858 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001859 FromType = ToType;
1860 } else {
1861 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001862 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001863 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001864
1865 // C++ [over.best.ics]p6:
1866 // [...] Any difference in top-level cv-qualification is
1867 // subsumed by the initialization itself and does not constitute
1868 // a conversion. [...]
1869 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1870 QualType CanonTo = S.Context.getCanonicalType(ToType);
1871 if (CanonFrom.getLocalUnqualifiedType()
1872 == CanonTo.getLocalUnqualifiedType() &&
1873 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1874 FromType = ToType;
1875 CanonFrom = CanonTo;
1876 }
1877
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001878 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001879
George Burgess IV45461812015-10-11 20:13:20 +00001880 if (CanonFrom == CanonTo)
1881 return true;
1882
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001884 // this is a bad conversion sequence, unless we're resolving an overload in C.
1885 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001886 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001887
George Burgess IV45461812015-10-11 20:13:20 +00001888 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001889 Sema::AssignConvertType Conv =
1890 S.CheckSingleAssignmentConstraints(ToType, ER,
1891 /*Diagnose=*/false,
1892 /*DiagnoseCFAudited=*/false,
1893 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001894 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001895 switch (Conv) {
1896 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001897 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001898 break;
1899 // For our purposes, discarding qualifiers is just as bad as using an
1900 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1901 // qualifiers, as well.
1902 case Sema::CompatiblePointerDiscardsQualifiers:
1903 case Sema::IncompatiblePointer:
1904 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001905 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001906 break;
1907 default:
George Burgess IV45461812015-10-11 20:13:20 +00001908 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001909 }
George Burgess IV45461812015-10-11 20:13:20 +00001910
George Burgess IV6098fd12016-09-03 00:28:25 +00001911 // First can only be an lvalue conversion, so we pretend that this was the
1912 // second conversion. First should already be valid from earlier in the
1913 // function.
1914 SCS.Second = SecondConv;
1915 SCS.setToType(1, ToType);
1916
1917 // Third is Identity, because Second should rank us worse than any other
1918 // conversion. This could also be ICK_Qualification, but it's simpler to just
1919 // lump everything in with the second conversion, and we don't gain anything
1920 // from making this ICK_Qualification.
1921 SCS.Third = ICK_Identity;
1922 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001923 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001924}
George Burgess IV2099b542016-09-02 22:59:57 +00001925
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001926static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001927IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001928 QualType &ToType,
1929 bool InOverloadResolution,
1930 StandardConversionSequence &SCS,
1931 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001932
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001933 const RecordType *UT = ToType->getAsUnionType();
1934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1935 return false;
1936 // The field to initialize within the transparent union.
1937 RecordDecl *UD = UT->getDecl();
1938 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001939 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001940 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1941 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001942 ToType = it->getType();
1943 return true;
1944 }
1945 }
1946 return false;
1947}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001948
1949/// IsIntegralPromotion - Determines whether the conversion from the
1950/// expression From (whose potentially-adjusted type is FromType) to
1951/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1952/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001953bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001954 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001955 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001956 if (!To) {
1957 return false;
1958 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001959
1960 // An rvalue of type char, signed char, unsigned char, short int, or
1961 // unsigned short int can be converted to an rvalue of type int if
1962 // int can represent all the values of the source type; otherwise,
1963 // the source rvalue can be converted to an rvalue of type unsigned
1964 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001965 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1966 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001967 if (// We can promote any signed, promotable integer type to an int
1968 (FromType->isSignedIntegerType() ||
1969 // We can promote any unsigned integer type whose size is
1970 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001971 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001972 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001973 }
1974
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001975 return To->getKind() == BuiltinType::UInt;
1976 }
1977
Richard Smithb9c5a602012-09-13 21:18:54 +00001978 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979 // A prvalue of an unscoped enumeration type whose underlying type is not
1980 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1981 // following types that can represent all the values of the enumeration
1982 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1983 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001984 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001986 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987 // with lowest integer conversion rank (4.13) greater than the rank of long
1988 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001989 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001990 // C++11 [conv.prom]p4:
1991 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1992 // can be converted to a prvalue of its underlying type. Moreover, if
1993 // integral promotion can be applied to its underlying type, a prvalue of an
1994 // unscoped enumeration type whose underlying type is fixed can also be
1995 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001996 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1997 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1998 // provided for a scoped enumeration.
1999 if (FromEnumType->getDecl()->isScoped())
2000 return false;
2001
Richard Smithb9c5a602012-09-13 21:18:54 +00002002 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00002003 // even if that's not the promoted type. Note that the check for promoting
2004 // the underlying type is based on the type alone, and does not consider
2005 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00002006 if (FromEnumType->getDecl()->isFixed()) {
2007 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2008 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00002009 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00002010 }
2011
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002012 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00002014 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00002015 return Context.hasSameUnqualifiedType(
2016 ToType, FromEnumType->getDecl()->getPromotionType());
Richard Smithaadb2542018-06-28 21:17:55 +00002017
2018 // C++ [conv.prom]p5:
2019 // If the bit-field has an enumerated type, it is treated as any other
2020 // value of that type for promotion purposes.
2021 //
2022 // ... so do not fall through into the bit-field checks below in C++.
2023 if (getLangOpts().CPlusPlus)
2024 return false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00002025 }
John McCall56774992009-12-09 09:09:27 +00002026
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002027 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2029 // to an rvalue a prvalue of the first of the following types that can
2030 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002031 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002033 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002035 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002036 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002037 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002038 // Determine whether the type we're converting from is signed or
2039 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002040 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002041 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002043 // The types we'll try to promote to, in the appropriate
2044 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002045 QualType PromoteTypes[6] = {
2046 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002047 Context.LongTy, Context.UnsignedLongTy ,
2048 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002049 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002050 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002051 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2052 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002053 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002054 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2055 // We found the type that we can promote to. If this is the
2056 // type we wanted, we have a promotion. Otherwise, no
2057 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002058 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002059 }
2060 }
2061 }
2062
2063 // An rvalue for an integral bit-field (9.6) can be converted to an
2064 // rvalue of type int if int can represent all the values of the
2065 // bit-field; otherwise, it can be converted to unsigned int if
2066 // unsigned int can represent all the values of the bit-field. If
2067 // the bit-field is larger yet, no integral promotion applies to
2068 // it. If the bit-field has an enumerated type, it is treated as any
2069 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002070 // FIXME: We should delay checking of bit-fields until we actually perform the
2071 // conversion.
Richard Smithaadb2542018-06-28 21:17:55 +00002072 //
2073 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2074 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2075 // bit-fields and those whose underlying type is larger than int) for GCC
2076 // compatibility.
Richard Smith88f4bba2015-03-26 00:16:07 +00002077 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002078 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002079 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002080 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002081 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002082 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002083 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002084
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002085 // Are we promoting to an int from a bitfield that fits in an int?
2086 if (BitWidth < ToSize ||
2087 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2088 return To->getKind() == BuiltinType::Int;
2089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002091 // Are we promoting to an unsigned int from an unsigned bitfield
2092 // that fits into an unsigned int?
2093 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2094 return To->getKind() == BuiltinType::UInt;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002097 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002098 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002099 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102 // An rvalue of type bool can be converted to an rvalue of type int,
2103 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002104 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002105 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002106 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002107
2108 return false;
2109}
2110
2111/// IsFloatingPointPromotion - Determines whether the conversion from
2112/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2113/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002114bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002115 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2116 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002117 /// An rvalue of type float can be converted to an rvalue of type
2118 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002119 if (FromBuiltin->getKind() == BuiltinType::Float &&
2120 ToBuiltin->getKind() == BuiltinType::Double)
2121 return true;
2122
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002123 // C99 6.3.1.5p1:
2124 // When a float is promoted to double or long double, or a
2125 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002126 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002127 (FromBuiltin->getKind() == BuiltinType::Float ||
2128 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002129 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2130 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002131 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002132
2133 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002134 if (!getLangOpts().NativeHalfType &&
2135 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002136 ToBuiltin->getKind() == BuiltinType::Float)
2137 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002138 }
2139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002140 return false;
2141}
2142
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002143/// Determine if a conversion is a complex promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002144///
2145/// A complex promotion is defined as a complex -> complex conversion
2146/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002147/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002148bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002149 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002150 if (!FromComplex)
2151 return false;
2152
John McCall9dd450b2009-09-21 23:43:11 +00002153 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002154 if (!ToComplex)
2155 return false;
2156
2157 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002158 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002159 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002160 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002161}
2162
Douglas Gregor237f96c2008-11-26 23:31:11 +00002163/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2164/// the pointer type FromPtr to a pointer to type ToPointee, with the
2165/// same type qualifiers as FromPtr has on its pointee type. ToType,
2166/// if non-empty, will be a pointer to ToType that may or may not have
2167/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002168///
Mike Stump11289f42009-09-09 15:08:12 +00002169static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002170BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002171 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002172 ASTContext &Context,
2173 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002174 assert((FromPtr->getTypeClass() == Type::Pointer ||
2175 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2176 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177
John McCall31168b02011-06-15 23:02:42 +00002178 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002179 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002180 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002181
2182 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002183 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002184 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002185 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall31168b02011-06-15 23:02:42 +00002187 if (StripObjCLifetime)
2188 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002189
Mike Stump11289f42009-09-09 15:08:12 +00002190 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002191 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002192 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002193 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002194 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002195
2196 // Build a pointer to ToPointee. It has the right qualifiers
2197 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002198 if (isa<ObjCObjectPointerType>(ToType))
2199 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002200 return Context.getPointerType(ToPointee);
2201 }
2202
2203 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002204 QualType QualifiedCanonToPointee
2205 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002207 if (isa<ObjCObjectPointerType>(ToType))
2208 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2209 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002210}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002211
Mike Stump11289f42009-09-09 15:08:12 +00002212static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002213 bool InOverloadResolution,
2214 ASTContext &Context) {
2215 // Handle value-dependent integral null pointer constants correctly.
2216 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2217 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002218 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002219 return !InOverloadResolution;
2220
Douglas Gregor56751b52009-09-25 04:25:58 +00002221 return Expr->isNullPointerConstant(Context,
2222 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2223 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002224}
Mike Stump11289f42009-09-09 15:08:12 +00002225
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226/// IsPointerConversion - Determines whether the conversion of the
2227/// expression From, which has the (possibly adjusted) type FromType,
2228/// can be converted to the type ToType via a pointer conversion (C++
2229/// 4.10). If so, returns true and places the converted type (that
2230/// might differ from ToType in its cv-qualifiers at some level) into
2231/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002232///
Douglas Gregora29dc052008-11-27 01:19:21 +00002233/// This routine also supports conversions to and from block pointers
2234/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2235/// pointers to interfaces. FIXME: Once we've determined the
2236/// appropriate overloading rules for Objective-C, we may want to
2237/// split the Objective-C checks into a different routine; however,
2238/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002239/// conversions, so for now they live here. IncompatibleObjC will be
2240/// set if the conversion is an allowed Objective-C conversion that
2241/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002242bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002243 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002244 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002245 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002246 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002247 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2248 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002249 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002250
Mike Stump11289f42009-09-09 15:08:12 +00002251 // Conversion from a null pointer constant to any Objective-C pointer type.
2252 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002253 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002254 ConvertedType = ToType;
2255 return true;
2256 }
2257
Douglas Gregor231d1c62008-11-27 00:15:41 +00002258 // Blocks: Block pointers can be converted to void*.
2259 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002260 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002261 ConvertedType = ToType;
2262 return true;
2263 }
2264 // Blocks: A null pointer constant can be converted to a block
2265 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002266 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002267 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002268 ConvertedType = ToType;
2269 return true;
2270 }
2271
Sebastian Redl576fd422009-05-10 18:38:11 +00002272 // If the left-hand-side is nullptr_t, the right side can be a null
2273 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002274 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002275 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002276 ConvertedType = ToType;
2277 return true;
2278 }
2279
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002280 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002281 if (!ToTypePtr)
2282 return false;
2283
2284 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002285 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002286 ConvertedType = ToType;
2287 return true;
2288 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002289
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002291 // , including objective-c pointers.
2292 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002293 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002294 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002295 ConvertedType = BuildSimilarlyQualifiedPointerType(
2296 FromType->getAs<ObjCObjectPointerType>(),
2297 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002298 ToType, Context);
2299 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002300 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002301 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002302 if (!FromTypePtr)
2303 return false;
2304
2305 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002306
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002308 // pointer conversion, so don't do all of the work below.
2309 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2310 return false;
2311
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002312 // An rvalue of type "pointer to cv T," where T is an object type,
2313 // can be converted to an rvalue of type "pointer to cv void" (C++
2314 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002315 if (FromPointeeType->isIncompleteOrObjectType() &&
2316 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002318 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002319 ToType, Context,
2320 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002321 return true;
2322 }
2323
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002324 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002325 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002326 ToPointeeType->isVoidType()) {
2327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2328 ToPointeeType,
2329 ToType, Context);
2330 return true;
2331 }
2332
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002333 // When we're overloading in C, we allow a special kind of pointer
2334 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002335 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002336 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002338 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002339 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002340 return true;
2341 }
2342
Douglas Gregor5c407d92008-10-23 00:40:37 +00002343 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002344 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002345 // An rvalue of type "pointer to cv D," where D is a class type,
2346 // can be converted to an rvalue of type "pointer to cv B," where
2347 // B is a base class (clause 10) of D. If B is an inaccessible
2348 // (clause 11) or ambiguous (10.2) base class of D, a program that
2349 // necessitates this conversion is ill-formed. The result of the
2350 // conversion is a pointer to the base class sub-object of the
2351 // derived class object. The null pointer value is converted to
2352 // the null pointer value of the destination type.
2353 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002354 // Note that we do not check for ambiguity or inaccessibility
2355 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002356 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002357 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002358 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002359 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002361 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002362 ToType, Context);
2363 return true;
2364 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002365
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002366 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2367 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2369 ToPointeeType,
2370 ToType, Context);
2371 return true;
2372 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002373
Douglas Gregora119f102008-12-19 19:13:09 +00002374 return false;
2375}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002376
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002377/// Adopt the given qualifiers for the given type.
Douglas Gregoraec25842011-04-26 23:16:46 +00002378static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2379 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002380
Douglas Gregoraec25842011-04-26 23:16:46 +00002381 // Check whether qualifiers already match.
2382 if (TQs == Qs)
2383 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002384
Douglas Gregoraec25842011-04-26 23:16:46 +00002385 if (Qs.compatiblyIncludes(TQs))
2386 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002387
Douglas Gregoraec25842011-04-26 23:16:46 +00002388 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2389}
Douglas Gregora119f102008-12-19 19:13:09 +00002390
2391/// isObjCPointerConversion - Determines whether this is an
2392/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2393/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002394bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002395 QualType& ConvertedType,
2396 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002397 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002398 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002399
Douglas Gregoraec25842011-04-26 23:16:46 +00002400 // The set of qualifiers on the type we're converting from.
2401 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002402
Steve Naroff7cae42b2009-07-10 23:34:53 +00002403 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002404 const ObjCObjectPointerType* ToObjCPtr =
2405 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002406 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002407 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002408
Steve Naroff7cae42b2009-07-10 23:34:53 +00002409 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002410 // If the pointee types are the same (ignoring qualifications),
2411 // then this is not a pointer conversion.
2412 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2413 FromObjCPtr->getPointeeType()))
2414 return false;
2415
Douglas Gregorab209d82015-07-07 03:58:42 +00002416 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002417 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002418 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2419 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002420 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002421 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2422 FromObjCPtr->getPointeeType()))
2423 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002425 ToObjCPtr->getPointeeType(),
2426 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002427 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002428 return true;
2429 }
2430
2431 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2432 // Okay: this is some kind of implicit downcast of Objective-C
2433 // interfaces, which is permitted. However, we're going to
2434 // complain about it.
2435 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002437 ToObjCPtr->getPointeeType(),
2438 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002440 return true;
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002443 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002444 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002445 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002446 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002447 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002448 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002449 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002450 // to a block pointer type.
2451 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002452 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002453 return true;
2454 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002455 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002458 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002460 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002461 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002462 return true;
2463 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002464 else
Douglas Gregora119f102008-12-19 19:13:09 +00002465 return false;
2466
Douglas Gregor033f56d2008-12-23 00:53:59 +00002467 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002468 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002469 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002470 else if (const BlockPointerType *FromBlockPtr =
2471 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002472 FromPointeeType = FromBlockPtr->getPointeeType();
2473 else
Douglas Gregora119f102008-12-19 19:13:09 +00002474 return false;
2475
Douglas Gregora119f102008-12-19 19:13:09 +00002476 // If we have pointers to pointers, recursively check whether this
2477 // is an Objective-C conversion.
2478 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2479 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2480 IncompatibleObjC)) {
2481 // We always complain about this conversion.
2482 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002483 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002485 return true;
2486 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002487 // Allow conversion of pointee being objective-c pointer to another one;
2488 // as in I* to id.
2489 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2490 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2492 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002493
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002494 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002495 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002496 return true;
2497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498
Douglas Gregor033f56d2008-12-23 00:53:59 +00002499 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002500 // differences in the argument and result types are in Objective-C
2501 // pointer conversions. If so, we permit the conversion (but
2502 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002503 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002504 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002505 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002506 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002507 if (FromFunctionType && ToFunctionType) {
2508 // If the function types are exactly the same, this isn't an
2509 // Objective-C pointer conversion.
2510 if (Context.getCanonicalType(FromPointeeType)
2511 == Context.getCanonicalType(ToPointeeType))
2512 return false;
2513
2514 // Perform the quick checks that will tell us whether these
2515 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002516 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002517 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2518 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2519 return false;
2520
2521 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002522 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2523 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002524 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002525 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2526 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002527 ConvertedType, IncompatibleObjC)) {
2528 // Okay, we have an Objective-C pointer conversion.
2529 HasObjCConversion = true;
2530 } else {
2531 // Function types are too different. Abort.
2532 return false;
2533 }
Mike Stump11289f42009-09-09 15:08:12 +00002534
Douglas Gregora119f102008-12-19 19:13:09 +00002535 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002536 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002537 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002538 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2539 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002540 if (Context.getCanonicalType(FromArgType)
2541 == Context.getCanonicalType(ToArgType)) {
2542 // Okay, the types match exactly. Nothing to do.
2543 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2544 ConvertedType, IncompatibleObjC)) {
2545 // Okay, we have an Objective-C pointer conversion.
2546 HasObjCConversion = true;
2547 } else {
2548 // Argument types are too different. Abort.
2549 return false;
2550 }
2551 }
2552
2553 if (HasObjCConversion) {
2554 // We had an Objective-C conversion. Allow this pointer
2555 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002556 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002557 IncompatibleObjC = true;
2558 return true;
2559 }
2560 }
2561
Sebastian Redl72b597d2009-01-25 19:43:20 +00002562 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002565/// Determine whether this is an Objective-C writeback conversion,
John McCall31168b02011-06-15 23:02:42 +00002566/// used for parameter passing when performing automatic reference counting.
2567///
2568/// \param FromType The type we're converting form.
2569///
2570/// \param ToType The type we're converting to.
2571///
2572/// \param ConvertedType The type that will be produced after applying
2573/// this conversion.
2574bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2575 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002576 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002577 Context.hasSameUnqualifiedType(FromType, ToType))
2578 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002579
John McCall31168b02011-06-15 23:02:42 +00002580 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2581 QualType ToPointee;
2582 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2583 ToPointee = ToPointer->getPointeeType();
2584 else
2585 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002586
John McCall31168b02011-06-15 23:02:42 +00002587 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002588 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002589 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002590 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002591 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002592
John McCall31168b02011-06-15 23:02:42 +00002593 // Argument must be a pointer to __strong to __weak.
2594 QualType FromPointee;
2595 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2596 FromPointee = FromPointer->getPointeeType();
2597 else
2598 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002599
John McCall31168b02011-06-15 23:02:42 +00002600 Qualifiers FromQuals = FromPointee.getQualifiers();
2601 if (!FromPointee->isObjCLifetimeType() ||
2602 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2603 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2604 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002605
John McCall31168b02011-06-15 23:02:42 +00002606 // Make sure that we have compatible qualifiers.
2607 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2608 if (!ToQuals.compatiblyIncludes(FromQuals))
2609 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002610
John McCall31168b02011-06-15 23:02:42 +00002611 // Remove qualifiers from the pointee type we're converting from; they
2612 // aren't used in the compatibility check belong, and we'll be adding back
2613 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2614 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002615
John McCall31168b02011-06-15 23:02:42 +00002616 // The unqualified form of the pointee types must be compatible.
2617 ToPointee = ToPointee.getUnqualifiedType();
2618 bool IncompatibleObjC;
2619 if (Context.typesAreCompatible(FromPointee, ToPointee))
2620 FromPointee = ToPointee;
2621 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2622 IncompatibleObjC))
2623 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002625 /// Construct the type we're converting to, which is a pointer to
John McCall31168b02011-06-15 23:02:42 +00002626 /// __autoreleasing pointee.
2627 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2628 ConvertedType = Context.getPointerType(FromPointee);
2629 return true;
2630}
2631
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002632bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2633 QualType& ConvertedType) {
2634 QualType ToPointeeType;
2635 if (const BlockPointerType *ToBlockPtr =
2636 ToType->getAs<BlockPointerType>())
2637 ToPointeeType = ToBlockPtr->getPointeeType();
2638 else
2639 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002640
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002641 QualType FromPointeeType;
2642 if (const BlockPointerType *FromBlockPtr =
2643 FromType->getAs<BlockPointerType>())
2644 FromPointeeType = FromBlockPtr->getPointeeType();
2645 else
2646 return false;
2647 // We have pointer to blocks, check whether the only
2648 // differences in the argument and result types are in Objective-C
2649 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002650
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002651 const FunctionProtoType *FromFunctionType
2652 = FromPointeeType->getAs<FunctionProtoType>();
2653 const FunctionProtoType *ToFunctionType
2654 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002655
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002656 if (!FromFunctionType || !ToFunctionType)
2657 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002658
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002659 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002660 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002661
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002662 // Perform the quick checks that will tell us whether these
2663 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002664 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002665 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2666 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002667
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002668 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2669 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2670 if (FromEInfo != ToEInfo)
2671 return false;
2672
2673 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002674 if (Context.hasSameType(FromFunctionType->getReturnType(),
2675 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002676 // Okay, the types match exactly. Nothing to do.
2677 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002678 QualType RHS = FromFunctionType->getReturnType();
2679 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002680 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002681 !RHS.hasQualifiers() && LHS.hasQualifiers())
2682 LHS = LHS.getUnqualifiedType();
2683
2684 if (Context.hasSameType(RHS,LHS)) {
2685 // OK exact match.
2686 } else if (isObjCPointerConversion(RHS, LHS,
2687 ConvertedType, IncompatibleObjC)) {
2688 if (IncompatibleObjC)
2689 return false;
2690 // Okay, we have an Objective-C pointer conversion.
2691 }
2692 else
2693 return false;
2694 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002695
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002696 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002697 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002698 ArgIdx != NumArgs; ++ArgIdx) {
2699 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002700 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2701 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002702 if (Context.hasSameType(FromArgType, ToArgType)) {
2703 // Okay, the types match exactly. Nothing to do.
2704 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2705 ConvertedType, IncompatibleObjC)) {
2706 if (IncompatibleObjC)
2707 return false;
2708 // Okay, we have an Objective-C pointer conversion.
2709 } else
2710 // Argument types are too different. Abort.
2711 return false;
2712 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002713
2714 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2715 bool CanUseToFPT, CanUseFromFPT;
2716 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2717 CanUseToFPT, CanUseFromFPT,
2718 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002719 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002720
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002721 ConvertedType = ToType;
2722 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002723}
2724
Richard Trieucaff2472011-11-23 22:32:32 +00002725enum {
2726 ft_default,
2727 ft_different_class,
2728 ft_parameter_arity,
2729 ft_parameter_mismatch,
2730 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002731 ft_qualifer_mismatch,
2732 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002733};
2734
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002735/// Attempts to get the FunctionProtoType from a Type. Handles
2736/// MemberFunctionPointers properly.
2737static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2738 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2739 return FPT;
2740
2741 if (auto *MPT = FromType->getAs<MemberPointerType>())
2742 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2743
2744 return nullptr;
2745}
2746
Richard Trieucaff2472011-11-23 22:32:32 +00002747/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2748/// function types. Catches different number of parameter, mismatch in
2749/// parameter types, and different return types.
2750void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2751 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002752 // If either type is not valid, include no extra info.
2753 if (FromType.isNull() || ToType.isNull()) {
2754 PDiag << ft_default;
2755 return;
2756 }
2757
Richard Trieucaff2472011-11-23 22:32:32 +00002758 // Get the function type from the pointers.
2759 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2760 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2761 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002762 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002763 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2764 << QualType(FromMember->getClass(), 0);
2765 return;
2766 }
2767 FromType = FromMember->getPointeeType();
2768 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002769 }
2770
Richard Trieu96ed5b62011-12-13 23:19:45 +00002771 if (FromType->isPointerType())
2772 FromType = FromType->getPointeeType();
2773 if (ToType->isPointerType())
2774 ToType = ToType->getPointeeType();
2775
2776 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002777 FromType = FromType.getNonReferenceType();
2778 ToType = ToType.getNonReferenceType();
2779
Richard Trieucaff2472011-11-23 22:32:32 +00002780 // Don't print extra info for non-specialized template functions.
2781 if (FromType->isInstantiationDependentType() &&
2782 !FromType->getAs<TemplateSpecializationType>()) {
2783 PDiag << ft_default;
2784 return;
2785 }
2786
Richard Trieu96ed5b62011-12-13 23:19:45 +00002787 // No extra info for same types.
2788 if (Context.hasSameType(FromType, ToType)) {
2789 PDiag << ft_default;
2790 return;
2791 }
2792
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002793 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2794 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002795
2796 // Both types need to be function types.
2797 if (!FromFunction || !ToFunction) {
2798 PDiag << ft_default;
2799 return;
2800 }
2801
Alp Toker9cacbab2014-01-20 20:26:09 +00002802 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2803 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2804 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002805 return;
2806 }
2807
2808 // Handle different parameter types.
2809 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002810 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002811 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002812 << ToFunction->getParamType(ArgPos)
2813 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002814 return;
2815 }
2816
2817 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002818 if (!Context.hasSameType(FromFunction->getReturnType(),
2819 ToFunction->getReturnType())) {
2820 PDiag << ft_return_type << ToFunction->getReturnType()
2821 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002822 return;
2823 }
2824
2825 unsigned FromQuals = FromFunction->getTypeQuals(),
2826 ToQuals = ToFunction->getTypeQuals();
2827 if (FromQuals != ToQuals) {
2828 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2829 return;
2830 }
2831
Richard Smith3c4f8d22016-10-16 17:54:23 +00002832 // Handle exception specification differences on canonical type (in C++17
2833 // onwards).
2834 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002835 ->isNothrow() !=
Richard Smith3c4f8d22016-10-16 17:54:23 +00002836 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002837 ->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00002838 PDiag << ft_noexcept;
2839 return;
2840 }
2841
Richard Trieucaff2472011-11-23 22:32:32 +00002842 // Unable to find a difference, so add no extra info.
2843 PDiag << ft_default;
2844}
2845
Alp Toker9cacbab2014-01-20 20:26:09 +00002846/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002847/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002848/// they have same number of arguments. If the parameters are different,
2849/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002850bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2851 const FunctionProtoType *NewType,
2852 unsigned *ArgPos) {
2853 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2854 N = NewType->param_type_begin(),
2855 E = OldType->param_type_end();
2856 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002857 if (!Context.hasSameType(O->getUnqualifiedType(),
2858 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002859 if (ArgPos)
2860 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002861 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002862 }
2863 }
2864 return true;
2865}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002866
Douglas Gregor39c16d42008-10-24 04:54:22 +00002867/// CheckPointerConversion - Check the pointer conversion from the
2868/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002869/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002870/// conversions for which IsPointerConversion has already returned
2871/// true. It returns true and produces a diagnostic if there was an
2872/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002873bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002874 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002875 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002876 bool IgnoreBaseAccess,
2877 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002878 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002879 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002880
John McCall8cb679e2010-11-15 09:13:47 +00002881 Kind = CK_BitCast;
2882
George Burgess IV60bc9722016-01-13 23:36:34 +00002883 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002884 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002885 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002886 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2887 DiagRuntimeBehavior(From->getExprLoc(), From,
2888 PDiag(diag::warn_impcast_bool_to_null_pointer)
2889 << ToType << From->getSourceRange());
2890 else if (!isUnevaluatedContext())
2891 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2892 << ToType << From->getSourceRange();
2893 }
John McCall9320b872011-09-09 05:25:32 +00002894 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2895 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002896 QualType FromPointeeType = FromPtrType->getPointeeType(),
2897 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002898
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002899 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2900 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002901 // We must have a derived-to-base conversion. Check an
2902 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002903 unsigned InaccessibleID = 0;
2904 unsigned AmbigiousID = 0;
2905 if (Diagnose) {
2906 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2907 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2908 }
2909 if (CheckDerivedToBaseConversion(
2910 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2911 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2912 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002915 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002916 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002917 }
David Majnemer6bf02822015-10-31 08:42:14 +00002918
George Burgess IV60bc9722016-01-13 23:36:34 +00002919 if (Diagnose && !IsCStyleOrFunctionalCast &&
2920 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002921 assert(getLangOpts().MSVCCompat &&
2922 "this should only be possible with MSVCCompat!");
2923 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2924 << From->getSourceRange();
2925 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002926 }
John McCall9320b872011-09-09 05:25:32 +00002927 } else if (const ObjCObjectPointerType *ToPtrType =
2928 ToType->getAs<ObjCObjectPointerType>()) {
2929 if (const ObjCObjectPointerType *FromPtrType =
2930 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002931 // Objective-C++ conversions are always okay.
2932 // FIXME: We should have a different class of conversions for the
2933 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002934 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002935 return false;
John McCall9320b872011-09-09 05:25:32 +00002936 } else if (FromType->isBlockPointerType()) {
2937 Kind = CK_BlockPointerToObjCPointerCast;
2938 } else {
2939 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002940 }
John McCall9320b872011-09-09 05:25:32 +00002941 } else if (ToType->isBlockPointerType()) {
2942 if (!FromType->isBlockPointerType())
2943 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002944 }
John McCall8cb679e2010-11-15 09:13:47 +00002945
2946 // We shouldn't fall into this case unless it's valid for other
2947 // reasons.
2948 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2949 Kind = CK_NullToPointer;
2950
Douglas Gregor39c16d42008-10-24 04:54:22 +00002951 return false;
2952}
2953
Sebastian Redl72b597d2009-01-25 19:43:20 +00002954/// IsMemberPointerConversion - Determines whether the conversion of the
2955/// expression From, which has the (possibly adjusted) type FromType, can be
2956/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2957/// If so, returns true and places the converted type (that might differ from
2958/// ToType in its cv-qualifiers at some level) into ConvertedType.
2959bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002961 bool InOverloadResolution,
2962 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002963 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002964 if (!ToTypePtr)
2965 return false;
2966
2967 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002968 if (From->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002971 ConvertedType = ToType;
2972 return true;
2973 }
2974
2975 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002977 if (!FromTypePtr)
2978 return false;
2979
2980 // A pointer to member of B can be converted to a pointer to member of D,
2981 // where D is derived from B (C++ 4.11p2).
2982 QualType FromClass(FromTypePtr->getClass(), 0);
2983 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002984
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002985 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002986 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002987 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2988 ToClass.getTypePtr());
2989 return true;
2990 }
2991
2992 return false;
2993}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Sebastian Redl72b597d2009-01-25 19:43:20 +00002995/// CheckMemberPointerConversion - Check the member pointer conversion from the
2996/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002997/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002998/// for which IsMemberPointerConversion has already returned true. It returns
2999/// true and produces a diagnostic if there was an error, or returns false
3000/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003001bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00003002 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00003003 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00003004 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00003005 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003006 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00003007 if (!FromPtrType) {
3008 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00003010 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00003011 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00003012 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00003013 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00003014 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00003015
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003016 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00003017 assert(ToPtrType && "No member pointer cast has a target type "
3018 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003019
Sebastian Redled8f2002009-01-28 18:33:18 +00003020 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3021 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00003022
Sebastian Redled8f2002009-01-28 18:33:18 +00003023 // FIXME: What about dependent types?
3024 assert(FromClass->isRecordType() && "Pointer into non-class.");
3025 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003026
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003028 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00003029 bool DerivationOkay =
3030 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003031 assert(DerivationOkay &&
3032 "Should not have been called if derivation isn't OK.");
3033 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003034
Sebastian Redled8f2002009-01-28 18:33:18 +00003035 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3036 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003037 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3038 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3039 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3040 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003041 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003042
Douglas Gregor89ee6822009-02-28 01:32:25 +00003043 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003044 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3045 << FromClass << ToClass << QualType(VBase, 0)
3046 << From->getSourceRange();
3047 return true;
3048 }
3049
John McCall5b0829a2010-02-10 09:31:12 +00003050 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003051 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3052 Paths.front(),
3053 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003054
Anders Carlssond7923c62009-08-22 23:33:40 +00003055 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003056 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003057 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003058 return false;
3059}
3060
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003061/// Determine whether the lifetime conversion between the two given
3062/// qualifiers sets is nontrivial.
3063static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3064 Qualifiers ToQuals) {
3065 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003066 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003067 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3068 return false;
3069
3070 return true;
3071}
3072
Douglas Gregor9a657932008-10-21 23:43:52 +00003073/// IsQualificationConversion - Determines whether the conversion from
3074/// an rvalue of type FromType to ToType is a qualification conversion
3075/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003076///
3077/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3078/// when the qualification conversion involves a change in the Objective-C
3079/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003080bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003082 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003083 FromType = Context.getCanonicalType(FromType);
3084 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003085 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003086
Douglas Gregor9a657932008-10-21 23:43:52 +00003087 // If FromType and ToType are the same type, this is not a
3088 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003089 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003090 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003091
Douglas Gregor9a657932008-10-21 23:43:52 +00003092 // (C++ 4.4p4):
3093 // A conversion can add cv-qualifiers at levels other than the first
3094 // in multi-level pointers, subject to the following rules: [...]
3095 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003096 bool UnwrappedAnyPointer = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00003097 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003098 // Within each iteration of the loop, we check the qualifiers to
3099 // determine if this still looks like a qualification
3100 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003101 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003102 // until there are no more pointers or pointers-to-members left to
3103 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003104 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003105
Douglas Gregor90609aa2011-04-25 18:40:17 +00003106 Qualifiers FromQuals = FromType.getQualifiers();
3107 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003108
3109 // Ignore __unaligned qualifier if this type is void.
3110 if (ToType.getUnqualifiedType()->isVoidType())
3111 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003112
John McCall31168b02011-06-15 23:02:42 +00003113 // Objective-C ARC:
3114 // Check Objective-C lifetime conversions.
3115 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3116 UnwrappedAnyPointer) {
3117 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003118 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3119 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003120 FromQuals.removeObjCLifetime();
3121 ToQuals.removeObjCLifetime();
3122 } else {
3123 // Qualification conversions cannot cast between different
3124 // Objective-C lifetime qualifiers.
3125 return false;
3126 }
3127 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003128
Douglas Gregorf30053d2011-05-08 06:09:53 +00003129 // Allow addition/removal of GC attributes but not changing GC attributes.
3130 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3131 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3132 FromQuals.removeObjCGCAttr();
3133 ToQuals.removeObjCGCAttr();
3134 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003135
Douglas Gregor9a657932008-10-21 23:43:52 +00003136 // -- for every j > 0, if const is in cv 1,j then const is in cv
3137 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003138 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003139 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Douglas Gregor9a657932008-10-21 23:43:52 +00003141 // -- if the cv 1,j and cv 2,j are different, then const is in
3142 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003143 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003144 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003145 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003146
Douglas Gregor9a657932008-10-21 23:43:52 +00003147 // Keep track of whether all prior cv-qualifiers in the "to" type
3148 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003149 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003150 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003151 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003152
Yaxun Liu99a9f752018-07-20 11:32:51 +00003153 // Allows address space promotion by language rules implemented in
3154 // Type::Qualifiers::isAddressSpaceSupersetOf.
3155 Qualifiers FromQuals = FromType.getQualifiers();
3156 Qualifiers ToQuals = ToType.getQualifiers();
3157 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3158 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3159 return false;
3160 }
3161
Douglas Gregor9a657932008-10-21 23:43:52 +00003162 // We are left with FromType and ToType being the pointee types
3163 // after unwrapping the original FromType and ToType the same number
3164 // of types. If we unwrapped any pointers, and if FromType and
3165 // ToType have the same unqualified type (since we checked
3166 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003167 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003168}
3169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003170/// - Determine whether this is a conversion from a scalar type to an
Douglas Gregorc79862f2012-04-12 17:51:55 +00003171/// atomic type.
3172///
3173/// If successful, updates \c SCS's second and third steps in the conversion
3174/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003175static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3176 bool InOverloadResolution,
3177 StandardConversionSequence &SCS,
3178 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003179 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3180 if (!ToAtomic)
3181 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003182
Douglas Gregorc79862f2012-04-12 17:51:55 +00003183 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003184 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003185 InOverloadResolution, InnerSCS,
3186 CStyle, /*AllowObjCWritebackConversion=*/false))
3187 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003188
Douglas Gregorc79862f2012-04-12 17:51:55 +00003189 SCS.Second = InnerSCS.Second;
3190 SCS.setToType(1, InnerSCS.getToType(1));
3191 SCS.Third = InnerSCS.Third;
3192 SCS.QualificationIncludesObjCLifetime
3193 = InnerSCS.QualificationIncludesObjCLifetime;
3194 SCS.setToType(2, InnerSCS.getToType(2));
3195 return true;
3196}
3197
Sebastian Redle5417162012-03-27 18:33:03 +00003198static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3199 CXXConstructorDecl *Constructor,
3200 QualType Type) {
3201 const FunctionProtoType *CtorType =
3202 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003203 if (CtorType->getNumParams() > 0) {
3204 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003205 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3206 return true;
3207 }
3208 return false;
3209}
3210
Sebastian Redl82ace982012-02-11 23:51:08 +00003211static OverloadingResult
3212IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3213 CXXRecordDecl *To,
3214 UserDefinedConversionSequence &User,
3215 OverloadCandidateSet &CandidateSet,
3216 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003217 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003218 for (auto *D : S.LookupConstructors(To)) {
3219 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003220 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003221 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003222
Richard Smithc2bebe92016-05-11 20:37:46 +00003223 bool Usable = !Info.Constructor->isInvalidDecl() &&
3224 S.isInitListConstructor(Info.Constructor) &&
3225 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003226 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003227 // If the first argument is (a reference to) the target type,
3228 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003229 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3230 S.Context, Info.Constructor, ToType);
3231 if (Info.ConstructorTmpl)
3232 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3233 /*ExplicitArgs*/ nullptr, From,
3234 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003235 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3237 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003238 }
3239 }
3240
3241 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3242
3243 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003244 switch (auto Result =
3245 CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003246 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>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003311 S.IsDerivedFrom(From->getLocStart(), 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)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003379 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003380 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003381 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003382 = 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;
Richard Smith48372b62015-01-27 03:30:40 +00003419 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003420 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)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003499 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3500 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003502 if (!RequireCompleteType(From->getLocStart(), 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()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003505 Diag(From->getLocStart(), 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) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003519 if (!S.getLangOpts().ObjC1 || !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
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003903 return ImplicitConversionSequence::Indistinguishable;
3904}
3905
3906/// CompareQualificationConversions - Compares two standard conversion
3907/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003908/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003909static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003910CompareQualificationConversions(Sema &S,
3911 const StandardConversionSequence& SCS1,
3912 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003913 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003914 // -- S1 and S2 differ only in their qualification conversion and
3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3916 // cv-qualification signature of type T1 is a proper subset of
3917 // the cv-qualification signature of type T2, and S1 is not the
3918 // deprecated string literal array-to-pointer conversion (4.2).
3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3921 return ImplicitConversionSequence::Indistinguishable;
3922
3923 // FIXME: the example in the standard doesn't use a qualification
3924 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003925 QualType T1 = SCS1.getToType(2);
3926 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003927 T1 = S.Context.getCanonicalType(T1);
3928 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003929 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003932
3933 // If the types are the same, we won't learn anything by unwrapped
3934 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003936 return ImplicitConversionSequence::Indistinguishable;
3937
Chandler Carruth607f38e2009-12-29 07:16:59 +00003938 // If the type is an array type, promote the element qualifiers to the type
3939 // for comparison.
3940 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003942 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003944
Mike Stump11289f42009-09-09 15:08:12 +00003945 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003946 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003947
John McCall31168b02011-06-15 23:02:42 +00003948 // Objective-C++ ARC:
3949 // Prefer qualification conversions not involving a change in lifetime
3950 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003951 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003952 SCS2.QualificationIncludesObjCLifetime) {
3953 Result = SCS1.QualificationIncludesObjCLifetime
3954 ? ImplicitConversionSequence::Worse
3955 : ImplicitConversionSequence::Better;
3956 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003957
Richard Smitha3405ff2018-07-11 00:19:19 +00003958 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003959 // Within each iteration of the loop, we check the qualifiers to
3960 // determine if this still looks like a qualification
3961 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003962 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003963 // until there are no more pointers or pointers-to-members left
3964 // to unwrap. This essentially mimics what
3965 // IsQualificationConversion does, but here we're checking for a
3966 // strict subset of qualifiers.
3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3968 // The qualifiers are the same, so this doesn't tell us anything
3969 // about how the sequences rank.
3970 ;
3971 else if (T2.isMoreQualifiedThan(T1)) {
3972 // T1 has fewer qualifiers, so it could be the better sequence.
3973 if (Result == ImplicitConversionSequence::Worse)
3974 // Neither has qualifiers that are a subset of the other's
3975 // qualifiers.
3976 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003978 Result = ImplicitConversionSequence::Better;
3979 } else if (T1.isMoreQualifiedThan(T2)) {
3980 // T2 has fewer qualifiers, so it could be the better sequence.
3981 if (Result == ImplicitConversionSequence::Better)
3982 // Neither has qualifiers that are a subset of the other's
3983 // qualifiers.
3984 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003986 Result = ImplicitConversionSequence::Worse;
3987 } else {
3988 // Qualifiers are disjoint.
3989 return ImplicitConversionSequence::Indistinguishable;
3990 }
3991
3992 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003993 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003994 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003995 }
3996
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003997 // Check that the winning standard conversion sequence isn't using
3998 // the deprecated string literal array to pointer conversion.
3999 switch (Result) {
4000 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004001 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004002 Result = ImplicitConversionSequence::Indistinguishable;
4003 break;
4004
4005 case ImplicitConversionSequence::Indistinguishable:
4006 break;
4007
4008 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004009 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004010 Result = ImplicitConversionSequence::Indistinguishable;
4011 break;
4012 }
4013
4014 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004015}
4016
Douglas Gregor5c407d92008-10-23 00:40:37 +00004017/// CompareDerivedToBaseConversions - Compares two standard conversion
4018/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00004019/// various kinds of derived-to-base conversions (C++
4020/// [over.ics.rank]p4b3). As part of these checks, we also look at
4021/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00004022static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00004023CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00004024 const StandardConversionSequence& SCS1,
4025 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00004026 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004027 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00004028 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004029 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004030
4031 // Adjust the types we're converting from via the array-to-pointer
4032 // conversion, if we need to.
4033 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004034 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004035 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004036 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037
4038 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004039 FromType1 = S.Context.getCanonicalType(FromType1);
4040 ToType1 = S.Context.getCanonicalType(ToType1);
4041 FromType2 = S.Context.getCanonicalType(FromType2);
4042 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004043
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004044 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004045 //
4046 // If class B is derived directly or indirectly from class A and
4047 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004048 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004049 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004050 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004051 SCS2.Second == ICK_Pointer_Conversion &&
4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4053 FromType1->isPointerType() && FromType2->isPointerType() &&
4054 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004055 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004057 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004059 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004061 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004063
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004064 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004067 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004069 return ImplicitConversionSequence::Worse;
4070 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004071
4072 // -- conversion of B* to A* is better than conversion of C* to A*,
4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004075 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004077 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004078 }
4079 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4080 SCS2.Second == ICK_Pointer_Conversion) {
4081 const ObjCObjectPointerType *FromPtr1
4082 = FromType1->getAs<ObjCObjectPointerType>();
4083 const ObjCObjectPointerType *FromPtr2
4084 = FromType2->getAs<ObjCObjectPointerType>();
4085 const ObjCObjectPointerType *ToPtr1
4086 = ToType1->getAs<ObjCObjectPointerType>();
4087 const ObjCObjectPointerType *ToPtr2
4088 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004089
Douglas Gregor058d3de2011-01-31 18:51:41 +00004090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4091 // Apply the same conversion ranking rules for Objective-C pointer types
4092 // that we do for C++ pointers to class types. However, we employ the
4093 // Objective-C pseudo-subtyping relationship used for assignment of
4094 // Objective-C pointer types.
4095 bool FromAssignLeft
4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4097 bool FromAssignRight
4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4099 bool ToAssignLeft
4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4101 bool ToAssignRight
4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004103
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004104 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004105 // type is better than a conversion to 'id'.
4106 if (ToPtr1->isObjCIdType() &&
4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4108 return ImplicitConversionSequence::Worse;
4109 if (ToPtr2->isObjCIdType() &&
4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4111 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004112
4113 // A conversion to a non-id object pointer type is better than a
4114 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4116 return ImplicitConversionSequence::Worse;
4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4118 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004119
4120 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004121 // type is better than a conversion to 'Class'.
4122 if (ToPtr1->isObjCClassType() &&
4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4124 return ImplicitConversionSequence::Worse;
4125 if (ToPtr2->isObjCClassType() &&
4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4127 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004128
4129 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004130 // conversion to a qualified 'Class' type.
4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4132 return ImplicitConversionSequence::Worse;
4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4134 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004135
Douglas Gregor058d3de2011-01-31 18:51:41 +00004136 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004137 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004139 (ToAssignLeft != ToAssignRight)) {
4140 if (FromPtr1->isSpecialized()) {
4141 // "conversion of B<A> * to B * is better than conversion of B * to
4142 // C *.
4143 bool IsFirstSame =
4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4145 bool IsSecondSame =
4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4147 if (IsFirstSame) {
4148 if (!IsSecondSame)
4149 return ImplicitConversionSequence::Better;
4150 } else if (IsSecondSame)
4151 return ImplicitConversionSequence::Worse;
4152 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004153 return ToAssignLeft? ImplicitConversionSequence::Worse
4154 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004155 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004156
4157 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4159 (FromAssignLeft != FromAssignRight))
4160 return FromAssignLeft? ImplicitConversionSequence::Better
4161 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004162 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004163 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004164
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004165 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004170 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004172 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004174 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004176 ToType2->getAs<MemberPointerType>();
4177 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4178 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4179 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4180 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004185 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004188 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004190 return ImplicitConversionSequence::Better;
4191 }
4192 // conversion of B::* to C::* is better than conversion of A::* to C::*
4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004195 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004197 return ImplicitConversionSequence::Worse;
4198 }
4199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregor5ab11652010-04-17 22:01:05 +00004201 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004202 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004203 // -- binding of an expression of type C to a reference of type
4204 // B& is better than binding an expression of type C to a
4205 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004208 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004209 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004211 return ImplicitConversionSequence::Worse;
4212 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004213
Douglas Gregor2fe98832008-11-03 19:09:14 +00004214 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004215 // -- binding of an expression of type B to a reference of type
4216 // A& is better than binding an expression of type C to a
4217 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004220 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004221 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004223 return ImplicitConversionSequence::Worse;
4224 }
4225 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004226
Douglas Gregor5c407d92008-10-23 00:40:37 +00004227 return ImplicitConversionSequence::Indistinguishable;
4228}
4229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004230/// Determine whether the given type is valid, e.g., it is not an invalid
Douglas Gregor45bb4832013-03-26 23:36:30 +00004231/// C++ class.
4232static bool isTypeValid(QualType T) {
4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4234 return !Record->isInvalidDecl();
4235
4236 return true;
4237}
4238
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004239/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4240/// determine whether they are reference-related,
4241/// reference-compatible, reference-compatible with added
4242/// qualification, or incompatible, for use in C++ initialization by
4243/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4244/// type, and the first type (T1) is the pointee type of the reference
4245/// type being initialized.
4246Sema::ReferenceCompareResult
4247Sema::CompareReferenceRelationship(SourceLocation Loc,
4248 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004249 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004250 bool &ObjCConversion,
4251 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004252 assert(!OrigT1->isReferenceType() &&
4253 "T1 must be the pointee type of the reference type");
4254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4255
4256 QualType T1 = Context.getCanonicalType(OrigT1);
4257 QualType T2 = Context.getCanonicalType(OrigT2);
4258 Qualifiers T1Quals, T2Quals;
4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261
4262 // C++ [dcl.init.ref]p4:
4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4265 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004266 DerivedToBase = false;
4267 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004268 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004269 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004270 if (UnqualT1 == UnqualT2) {
4271 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004272 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004274 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004275 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004276 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4277 UnqualT2->isObjCObjectOrInterfaceType() &&
4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4279 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004280 else if (UnqualT2->isFunctionType() &&
4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4282 // C++1z [dcl.init.ref]p4:
4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4284 // function" and T1 is "function"
4285 //
4286 // We extend this to also apply to 'noreturn', so allow any function
4287 // conversion between function types.
4288 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004289 else
4290 return Ref_Incompatible;
4291
4292 // At this point, we know that T1 and T2 are reference-related (at
4293 // least).
4294
4295 // If the type is an array type, promote the element qualifiers to the type
4296 // for comparison.
4297 if (isa<ArrayType>(T1) && T1Quals)
4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299 if (isa<ArrayType>(T2) && T2Quals)
4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301
4302 // C++ [dcl.init.ref]p4:
4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4304 // reference-related to T2 and cv1 is the same cv-qualification
4305 // as, or greater cv-qualification than, cv2. For purposes of
4306 // overload resolution, cases for which cv1 is greater
4307 // cv-qualification than cv2 are identified as
4308 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004309 //
4310 // Note that we also require equivalence of Objective-C GC and address-space
4311 // qualifiers when performing these computations, so that e.g., an int in
4312 // address space 1 is not reference-compatible with an int in address
4313 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4317 ObjCLifetimeConversion = true;
4318
John McCall31168b02011-06-15 23:02:42 +00004319 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004320 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004321 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004322
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004323 // MS compiler ignores __unaligned qualifier for references; do the same.
4324 T1Quals.removeUnaligned();
4325 T2Quals.removeUnaligned();
4326
Richard Smithce766292016-10-21 23:01:55 +00004327 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004328 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004329 else
4330 return Ref_Related;
4331}
4332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004333/// Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004334/// with DeclType. Return true if something definite is found.
4335static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004336FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4337 QualType DeclType, SourceLocation DeclLoc,
4338 Expr *Init, QualType T2, bool AllowRvalues,
4339 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 assert(T2->isRecordType() && "Can only find conversions of record types.");
4341 CXXRecordDecl *T2RecordDecl
4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4343
Richard Smith67ef14f2017-09-26 18:37:55 +00004344 OverloadCandidateSet CandidateSet(
4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 NamedDecl *D = *I;
4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4350 if (isa<UsingShadowDecl>(D))
4351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4352
4353 FunctionTemplateDecl *ConvTemplate
4354 = dyn_cast<FunctionTemplateDecl>(D);
4355 CXXConversionDecl *Conv;
4356 if (ConvTemplate)
4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4358 else
4359 Conv = cast<CXXConversionDecl>(D);
4360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004362 // explicit conversions, skip it.
4363 if (!AllowExplicit && Conv->isExplicit())
4364 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregor836a7e82010-08-11 02:15:33 +00004366 if (AllowRvalues) {
4367 bool DerivedToBase = false;
4368 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004369 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004370
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004371 // If we are initializing an rvalue reference, don't permit conversion
4372 // functions that return lvalues.
4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4374 const ReferenceType *RefType
4375 = Conv->getConversionType()->getAs<LValueReferenceType>();
4376 if (RefType && !RefType->getPointeeType()->isFunctionType())
4377 continue;
4378 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004379
Douglas Gregor836a7e82010-08-11 02:15:33 +00004380 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004381 S.CompareReferenceRelationship(
4382 DeclLoc,
4383 Conv->getConversionType().getNonReferenceType()
4384 .getUnqualifiedType(),
4385 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004387 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004388 continue;
4389 } else {
4390 // If the conversion function doesn't return a reference type,
4391 // it can't be considered for this conversion. An rvalue reference
4392 // is only acceptable if its referencee is a function type.
4393
4394 const ReferenceType *RefType =
4395 Conv->getConversionType()->getAs<ReferenceType>();
4396 if (!RefType ||
4397 (!RefType->isLValueReferenceType() &&
4398 !RefType->getPointeeType()->isFunctionType()))
4399 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor836a7e82010-08-11 02:15:33 +00004402 if (ConvTemplate)
4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004404 Init, DeclType, CandidateSet,
4405 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004406 else
4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004408 DeclType, CandidateSet,
4409 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004410 }
4411
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004412 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4413
Sebastian Redld92badf2010-06-30 18:13:39 +00004414 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004416 case OR_Success:
4417 // C++ [over.ics.ref]p1:
4418 //
4419 // [...] If the parameter binds directly to the result of
4420 // applying a conversion function to the argument
4421 // expression, the implicit conversion sequence is a
4422 // user-defined conversion sequence (13.3.3.1.2), with the
4423 // second standard conversion sequence either an identity
4424 // conversion or, if the conversion function returns an
4425 // entity of a type that is a derived class of the parameter
4426 // type, a derived-to-base Conversion.
4427 if (!Best->FinalConversion.DirectBinding)
4428 return false;
4429
4430 ICS.setUserDefined();
4431 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4432 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004434 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004436 ICS.UserDefined.EllipsisConversion = false;
4437 assert(ICS.UserDefined.After.ReferenceBinding &&
4438 ICS.UserDefined.After.DirectBinding &&
4439 "Expected a direct reference binding!");
4440 return true;
4441
4442 case OR_Ambiguous:
4443 ICS.setAmbiguous();
4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4445 Cand != CandidateSet.end(); ++Cand)
4446 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004448 return true;
4449
4450 case OR_No_Viable_Function:
4451 case OR_Deleted:
4452 // There was no suitable conversion, or we found a deleted
4453 // conversion; continue with other checks.
4454 return false;
4455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456
David Blaikie8a40f702012-01-17 06:56:22 +00004457 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004458}
4459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004460/// Compute an implicit conversion sequence for reference
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461/// initialization.
4462static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004463TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004464 SourceLocation DeclLoc,
4465 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004466 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4468
4469 // Most paths end in a failed conversion.
4470 ImplicitConversionSequence ICS;
4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4472
4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4474 QualType T2 = Init->getType();
4475
4476 // If the initializer is the address of an overloaded function, try
4477 // to resolve the overloaded function. If all goes well, T2 is the
4478 // type of the resulting function.
4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4480 DeclAccessPair Found;
4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4482 false, Found))
4483 T2 = Fn->getType();
4484 }
4485
4486 // Compute some basic properties of the types and the initializer.
4487 bool isRValRef = DeclType->isRValueReferenceType();
4488 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004489 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004490 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004491 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004492 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004494 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004495
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496
Sebastian Redld92badf2010-06-30 18:13:39 +00004497 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004498 // A reference to type "cv1 T1" is initialized by an expression
4499 // of type "cv2 T2" as follows:
4500
Sebastian Redld92badf2010-06-30 18:13:39 +00004501 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004502 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4504 // reference-compatible with "cv2 T2," or
4505 //
4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004508 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004509 // When a parameter of reference type binds directly (8.5.3)
4510 // to an argument expression, the implicit conversion sequence
4511 // is the identity conversion, unless the argument expression
4512 // has a type that is a derived class of the parameter type,
4513 // in which case the implicit conversion sequence is a
4514 // derived-to-base Conversion (13.3.3.1).
4515 ICS.setStandard();
4516 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4518 : ObjCConversion? ICK_Compatible_Conversion
4519 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004520 ICS.Standard.Third = ICK_Identity;
4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4522 ICS.Standard.setToType(0, T2);
4523 ICS.Standard.setToType(1, T1);
4524 ICS.Standard.setToType(2, T1);
4525 ICS.Standard.ReferenceBinding = true;
4526 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004527 ICS.Standard.IsLvalueReference = !isRValRef;
4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4529 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004534
Sebastian Redld92badf2010-06-30 18:13:39 +00004535 // Nothing more to do: the inaccessibility/ambiguity check for
4536 // derived-to-base conversions is suppressed when we're
4537 // computing the implicit conversion sequence (C++
4538 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004539 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004540 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004541
Sebastian Redld92badf2010-06-30 18:13:39 +00004542 // -- has a class type (i.e., T2 is a class type), where T1 is
4543 // not reference-related to T2, and can be implicitly
4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4545 // is reference-compatible with "cv3 T3" 92) (this
4546 // conversion is selected by enumerating the applicable
4547 // conversion functions (13.3.1.6) and choosing the best
4548 // one through overload resolution (13.3)),
4549 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004550 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004551 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4553 Init, T2, /*AllowRvalues=*/false,
4554 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004555 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004556 }
4557 }
4558
Sebastian Redld92badf2010-06-30 18:13:39 +00004559 // -- Otherwise, the reference shall be an lvalue reference to a
4560 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004561 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004563 return ICS;
4564
Douglas Gregorf143cd52011-01-24 16:14:37 +00004565 // -- If the initializer expression
4566 //
4567 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004569 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004570 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4572 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004573 ICS.setStandard();
4574 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004576 : ObjCConversion? ICK_Compatible_Conversion
4577 : ICK_Identity;
4578 ICS.Standard.Third = ICK_Identity;
4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4580 ICS.Standard.setToType(0, T2);
4581 ICS.Standard.setToType(1, T1);
4582 ICS.Standard.setToType(2, T1);
4583 ICS.Standard.ReferenceBinding = true;
4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4585 // binding unless we're binding to a class prvalue.
4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4587 // allow the use of rvalue references in C++98/03 for the benefit of
4588 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004590 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004591 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004592 ICS.Standard.IsLvalueReference = !isRValRef;
4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004597 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Douglas Gregorf143cd52011-01-24 16:14:37 +00004602 // -- has a class type (i.e., T2 is a class type), where T1 is not
4603 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604 // an xvalue, class prvalue, or function lvalue of type
4605 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004606 // "cv3 T3",
4607 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004609 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004611 // class subobject).
4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4615 Init, T2, /*AllowRvalues=*/true,
4616 AllowExplicit)) {
4617 // In the second case, if the reference is an rvalue reference
4618 // and the second standard conversion sequence of the
4619 // user-defined conversion sequence includes an lvalue-to-rvalue
4620 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4624
Douglas Gregor95273c32011-01-21 16:36:05 +00004625 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Richard Smith19172c42014-07-14 02:28:44 +00004628 // A temporary of function type cannot be created; don't even try.
4629 if (T1->isFunctionType())
4630 return ICS;
4631
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004632 // -- Otherwise, a temporary of type "cv1 T1" is created and
4633 // initialized from the initializer expression using the
4634 // rules for a non-reference copy initialization (8.5). The
4635 // reference is then bound to the temporary. If T1 is
4636 // reference-related to T2, cv1 must be the same
4637 // cv-qualification as, or greater cv-qualification than,
4638 // cv2; otherwise, the program is ill-formed.
4639 if (RefRelationship == Sema::Ref_Related) {
4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4641 // we would be reference-compatible or reference-compatible with
4642 // added qualification. But that wasn't the case, so the reference
4643 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004644 //
4645 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004646 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004647 Qualifiers T1Quals = T1.getQualifiers();
4648 Qualifiers T2Quals = T2.getQualifiers();
4649 T1Quals.removeObjCGCAttr();
4650 T1Quals.removeObjCLifetime();
4651 T2Quals.removeObjCGCAttr();
4652 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004653 // MS compiler ignores __unaligned qualifier for references; do the same.
4654 T1Quals.removeUnaligned();
4655 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004656 if (!T1Quals.compatiblyIncludes(T2Quals))
4657 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004658 }
4659
4660 // If at least one of the types is a class type, the types are not
4661 // related, and we aren't allowed any user conversions, the
4662 // reference binding fails. This case is important for breaking
4663 // recursion, since TryImplicitConversion below will attempt to
4664 // create a temporary through the use of a copy constructor.
4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666 (T1->isRecordType() || T2->isRecordType()))
4667 return ICS;
4668
Douglas Gregorcba72b12011-01-21 05:18:22 +00004669 // If T1 is reference-related to T2 and the reference is an rvalue
4670 // reference, the initializer expression shall not be an lvalue.
4671 if (RefRelationship >= Sema::Ref_Related &&
4672 isRValRef && Init->Classify(S.Context).isLValue())
4673 return ICS;
4674
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004675 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004676 // When a parameter of reference type is not bound directly to
4677 // an argument expression, the conversion sequence is the one
4678 // required to convert the argument expression to the
4679 // underlying type of the reference according to
4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4681 // to copy-initializing a temporary of the underlying type with
4682 // the argument expression. Any difference in top-level
4683 // cv-qualification is subsumed by the initialization itself
4684 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4686 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004687 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004688 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004689 /*AllowObjCWritebackConversion=*/false,
4690 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004691
4692 // Of course, that's still a reference binding.
4693 if (ICS.isStandard()) {
4694 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004695 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004696 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004697 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004699 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004700 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004701 const ReferenceType *LValRefType =
4702 ICS.UserDefined.ConversionFunction->getReturnType()
4703 ->getAs<LValueReferenceType>();
4704
4705 // C++ [over.ics.ref]p3:
4706 // Except for an implicit object parameter, for which see 13.3.1, a
4707 // standard conversion sequence cannot be formed if it requires [...]
4708 // binding an rvalue reference to an lvalue other than a function
4709 // lvalue.
4710 // Note that the function case is not possible here.
4711 if (DeclType->isRValueReferenceType() && LValRefType) {
4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4714 // reference to an rvalue!
4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4716 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004717 }
Richard Smith19172c42014-07-14 02:28:44 +00004718
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004719 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004720 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004721 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004725 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004726
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004727 return ICS;
4728}
4729
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004730static ImplicitConversionSequence
4731TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4732 bool SuppressUserConversions,
4733 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004734 bool AllowObjCWritebackConversion,
4735 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004736
4737/// TryListConversion - Try to copy-initialize a value of type ToType from the
4738/// initializer list From.
4739static ImplicitConversionSequence
4740TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4741 bool SuppressUserConversions,
4742 bool InOverloadResolution,
4743 bool AllowObjCWritebackConversion) {
4744 // C++11 [over.ics.list]p1:
4745 // When an argument is an initializer list, it is not an expression and
4746 // special rules apply for converting it to a parameter type.
4747
4748 ImplicitConversionSequence Result;
4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4750
Sebastian Redl09edce02012-01-23 22:09:39 +00004751 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004752 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004753 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004754 return Result;
4755
Larisse Voufo19d08672015-01-27 18:47:05 +00004756 // Per DR1467:
4757 // If the parameter type is a class X and the initializer list has a single
4758 // element of type cv U, where U is X or a class derived from X, the
4759 // implicit conversion sequence is the one required to convert the element
4760 // to the parameter type.
4761 //
4762 // Otherwise, if the parameter type is a character array [... ]
4763 // and the initializer list has a single element that is an
4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4765 // implicit conversion sequence is the identity conversion.
4766 if (From->getNumInits() == 1) {
4767 if (ToType->isRecordType()) {
4768 QualType InitType = From->getInit(0)->getType();
4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004770 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004771 return TryCopyInitialization(S, From->getInit(0), ToType,
4772 SuppressUserConversions,
4773 InOverloadResolution,
4774 AllowObjCWritebackConversion);
4775 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004776 // FIXME: Check the other conditions here: array of character type,
4777 // initializer is a string literal.
4778 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004779 InitializedEntity Entity =
4780 InitializedEntity::InitializeParameter(S.Context, ToType,
4781 /*Consumed=*/false);
4782 if (S.CanPerformCopyInitialization(Entity, From)) {
4783 Result.setStandard();
4784 Result.Standard.setAsIdentityConversion();
4785 Result.Standard.setFromType(ToType);
4786 Result.Standard.setAllToTypes(ToType);
4787 return Result;
4788 }
4789 }
4790 }
4791
4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004793 // C++11 [over.ics.list]p2:
4794 // If the parameter type is std::initializer_list<X> or "array of X" and
4795 // all the elements can be implicitly converted to X, the implicit
4796 // conversion sequence is the worst conversion necessary to convert an
4797 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004798 //
4799 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004800 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004801 // list has exactly N elements or if it has fewer than N elements and X is
4802 // default-constructible, and if all the elements of the initializer list
4803 // can be implicitly converted to X, the implicit conversion sequence is
4804 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004805 //
4806 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004807 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004808 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004809 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004810 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004811 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004812 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004813 if (!X.isNull()) {
4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4815 Expr *Init = From->getInit(i);
4816 ImplicitConversionSequence ICS =
4817 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4818 InOverloadResolution,
4819 AllowObjCWritebackConversion);
4820 // If a single element isn't convertible, fail.
4821 if (ICS.isBad()) {
4822 Result = ICS;
4823 break;
4824 }
4825 // Otherwise, look for the worst conversion.
4826 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004827 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4828 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004829 ImplicitConversionSequence::Worse)
4830 Result = ICS;
4831 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004832
4833 // For an empty list, we won't have computed any conversion sequence.
4834 // Introduce the identity conversion sequence.
4835 if (From->getNumInits() == 0) {
4836 Result.setStandard();
4837 Result.Standard.setAsIdentityConversion();
4838 Result.Standard.setFromType(ToType);
4839 Result.Standard.setAllToTypes(ToType);
4840 }
4841
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004842 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004843 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004844 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004845
Larisse Voufo19d08672015-01-27 18:47:05 +00004846 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004847 // C++11 [over.ics.list]p3:
4848 // Otherwise, if the parameter is a non-aggregate class X and overload
4849 // resolution chooses a single best constructor [...] the implicit
4850 // conversion sequence is a user-defined conversion sequence. If multiple
4851 // constructors are viable but none is better than the others, the
4852 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004853 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4854 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004855 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4856 /*AllowExplicit=*/false,
4857 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004858 AllowObjCWritebackConversion,
4859 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004860 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004861
Larisse Voufo19d08672015-01-27 18:47:05 +00004862 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004863 // C++11 [over.ics.list]p4:
4864 // Otherwise, if the parameter has an aggregate type which can be
4865 // initialized from the initializer list [...] the implicit conversion
4866 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004867 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004868 // Type is an aggregate, argument is an init list. At this point it comes
4869 // down to checking whether the initialization works.
4870 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004871 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4872 // need to call into the initialization code here; overload resolution
4873 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004874 InitializedEntity Entity =
4875 InitializedEntity::InitializeParameter(S.Context, ToType,
4876 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004877 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004878 Result.setUserDefined();
4879 Result.UserDefined.Before.setAsIdentityConversion();
4880 // Initializer lists don't have a type.
4881 Result.UserDefined.Before.setFromType(QualType());
4882 Result.UserDefined.Before.setAllToTypes(QualType());
4883
4884 Result.UserDefined.After.setAsIdentityConversion();
4885 Result.UserDefined.After.setFromType(ToType);
4886 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004887 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004888 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004889 return Result;
4890 }
4891
Larisse Voufo19d08672015-01-27 18:47:05 +00004892 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004893 // C++11 [over.ics.list]p5:
4894 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004895 if (ToType->isReferenceType()) {
4896 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4897 // mention initializer lists in any way. So we go by what list-
4898 // initialization would do and try to extrapolate from that.
4899
4900 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4901
4902 // If the initializer list has a single element that is reference-related
4903 // to the parameter type, we initialize the reference from that.
4904 if (From->getNumInits() == 1) {
4905 Expr *Init = From->getInit(0);
4906
4907 QualType T2 = Init->getType();
4908
4909 // If the initializer is the address of an overloaded function, try
4910 // to resolve the overloaded function. If all goes well, T2 is the
4911 // type of the resulting function.
4912 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4913 DeclAccessPair Found;
4914 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4915 Init, ToType, false, Found))
4916 T2 = Fn->getType();
4917 }
4918
4919 // Compute some basic properties of the types and the initializer.
4920 bool dummy1 = false;
4921 bool dummy2 = false;
4922 bool dummy3 = false;
4923 Sema::ReferenceCompareResult RefRelationship
4924 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4925 dummy2, dummy3);
4926
Richard Smith4d2bbd72013-09-06 01:22:42 +00004927 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004928 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4929 SuppressUserConversions,
4930 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004931 }
Sebastian Redldf888642011-12-03 14:54:30 +00004932 }
4933
4934 // Otherwise, we bind the reference to a temporary created from the
4935 // initializer list.
4936 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4937 InOverloadResolution,
4938 AllowObjCWritebackConversion);
4939 if (Result.isFailure())
4940 return Result;
4941 assert(!Result.isEllipsis() &&
4942 "Sub-initialization cannot result in ellipsis conversion.");
4943
4944 // Can we even bind to a temporary?
4945 if (ToType->isRValueReferenceType() ||
4946 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4947 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4948 Result.UserDefined.After;
4949 SCS.ReferenceBinding = true;
4950 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4951 SCS.BindsToRvalue = true;
4952 SCS.BindsToFunctionLvalue = false;
4953 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4954 SCS.ObjCLifetimeConversionBinding = false;
4955 } else
4956 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4957 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004958 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004959 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004960
Larisse Voufo19d08672015-01-27 18:47:05 +00004961 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004962 // C++11 [over.ics.list]p6:
4963 // Otherwise, if the parameter type is not a class:
4964 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004965 // - if the initializer list has one element that is not itself an
4966 // initializer list, the implicit conversion sequence is the one
4967 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004968 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004969 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004970 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4971 SuppressUserConversions,
4972 InOverloadResolution,
4973 AllowObjCWritebackConversion);
4974 // - if the initializer list has no elements, the implicit conversion
4975 // sequence is the identity conversion.
4976 else if (NumInits == 0) {
4977 Result.setStandard();
4978 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004979 Result.Standard.setFromType(ToType);
4980 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004981 }
4982 return Result;
4983 }
4984
Larisse Voufo19d08672015-01-27 18:47:05 +00004985 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004986 // C++11 [over.ics.list]p7:
4987 // In all cases other than those enumerated above, no conversion is possible
4988 return Result;
4989}
4990
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004991/// TryCopyInitialization - Try to copy-initialize a value of type
4992/// ToType from the expression From. Return the implicit conversion
4993/// sequence required to pass this argument, which may be a bad
4994/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004995/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004996/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004997static ImplicitConversionSequence
4998TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005000 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005001 bool AllowObjCWritebackConversion,
5002 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00005003 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5004 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5005 InOverloadResolution,AllowObjCWritebackConversion);
5006
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005007 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005008 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005009 /*FIXME:*/From->getLocStart(),
5010 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005011 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005012
John McCall5c32be02010-08-24 20:38:10 +00005013 return TryImplicitConversion(S, From, ToType,
5014 SuppressUserConversions,
5015 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00005016 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00005017 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005018 AllowObjCWritebackConversion,
5019 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005020}
5021
Anna Zaks1b068122011-07-28 19:46:48 +00005022static bool TryCopyInitialization(const CanQualType FromQTy,
5023 const CanQualType ToQTy,
5024 Sema &S,
5025 SourceLocation Loc,
5026 ExprValueKind FromVK) {
5027 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5028 ImplicitConversionSequence ICS =
5029 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5030
5031 return !ICS.isBad();
5032}
5033
Douglas Gregor436424c2008-11-18 23:14:02 +00005034/// TryObjectArgumentInitialization - Try to initialize the object
5035/// parameter of the given member function (@c Method) from the
5036/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005037static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005038TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005039 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005040 CXXMethodDecl *Method,
5041 CXXRecordDecl *ActingContext) {
5042 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005043 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5044 // const volatile object.
5045 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5046 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005047 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005048
5049 // Set up the conversion sequence as a "bad" conversion, to allow us
5050 // to exit early.
5051 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005052
5053 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005054 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005055 FromType = PT->getPointeeType();
5056
Douglas Gregor02824322011-01-26 19:30:28 +00005057 // When we had a pointer, it's implicitly dereferenced, so we
5058 // better have an lvalue.
5059 assert(FromClassification.isLValue());
5060 }
5061
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005062 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005063
Douglas Gregor02824322011-01-26 19:30:28 +00005064 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005066 // parameter is
5067 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005068 // - "lvalue reference to cv X" for functions declared without a
5069 // ref-qualifier or with the & ref-qualifier
5070 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005071 // ref-qualifier
5072 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005074 // cv-qualification on the member function declaration.
5075 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005077 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005078 // (C++ [over.match.funcs]p5). We perform a simplified version of
5079 // reference binding here, that allows class rvalues to bind to
5080 // non-constant references.
5081
Douglas Gregor02824322011-01-26 19:30:28 +00005082 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005083 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005085 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005086 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005087 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005088 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005089 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005090 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005091
5092 // Check that we have either the same type or a derived type. It
5093 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005094 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005095 ImplicitConversionKind SecondKind;
5096 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5097 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005098 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005099 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005100 else {
John McCall65eb8792010-02-25 01:37:24 +00005101 ICS.setBad(BadConversionSequence::unrelated_class,
5102 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005103 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005104 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005105
Douglas Gregor02824322011-01-26 19:30:28 +00005106 // Check the ref-qualifier.
5107 switch (Method->getRefQualifier()) {
5108 case RQ_None:
5109 // Do nothing; we don't care about lvalueness or rvalueness.
5110 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111
Douglas Gregor02824322011-01-26 19:30:28 +00005112 case RQ_LValue:
5113 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5114 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005115 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005116 ImplicitParamType);
5117 return ICS;
5118 }
5119 break;
5120
5121 case RQ_RValue:
5122 if (!FromClassification.isRValue()) {
5123 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005125 ImplicitParamType);
5126 return ICS;
5127 }
5128 break;
5129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregor436424c2008-11-18 23:14:02 +00005131 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005132 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005133 ICS.Standard.setAsIdentityConversion();
5134 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005135 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005136 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005137 ICS.Standard.ReferenceBinding = true;
5138 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005140 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005141 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5142 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5143 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005144 return ICS;
5145}
5146
5147/// PerformObjectArgumentInitialization - Perform initialization of
5148/// the implicit object parameter for the given Method with the given
5149/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005150ExprResult
5151Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005153 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005154 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005155 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005156 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005157 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005158
Douglas Gregor02824322011-01-26 19:30:28 +00005159 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005160 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005161 FromRecordType = PT->getPointeeType();
5162 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005163 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005164 } else {
5165 FromRecordType = From->getType();
5166 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005167 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005168 }
5169
John McCall6e9f8f62009-12-03 04:06:58 +00005170 // Note that we always use the true parent context when performing
5171 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005172 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005173 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5174 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005175 if (ICS.isBad()) {
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005176 switch (ICS.Bad.Kind) {
5177 case BadConversionSequence::bad_qualifiers: {
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005178 Qualifiers FromQs = FromRecordType.getQualifiers();
5179 Qualifiers ToQs = DestType.getQualifiers();
5180 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5181 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005182 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005183 diag::err_member_function_call_bad_cvr)
5184 << Method->getDeclName() << FromRecordType << (CVR - 1)
5185 << From->getSourceRange();
5186 Diag(Method->getLocation(), diag::note_previous_decl)
5187 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005188 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005189 }
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005190 break;
5191 }
5192
5193 case BadConversionSequence::lvalue_ref_to_rvalue:
5194 case BadConversionSequence::rvalue_ref_to_lvalue: {
5195 bool IsRValueQualified =
5196 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5197 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5198 << Method->getDeclName() << FromClassification.isRValue()
5199 << IsRValueQualified;
5200 Diag(Method->getLocation(), diag::note_previous_decl)
5201 << Method->getDeclName();
5202 return ExprError();
5203 }
5204
5205 case BadConversionSequence::no_conversion:
5206 case BadConversionSequence::unrelated_class:
5207 break;
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005208 }
5209
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005210 return Diag(From->getLocStart(),
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005211 diag::err_member_function_call_bad_type)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005212 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005213 }
Mike Stump11289f42009-09-09 15:08:12 +00005214
John Wiegley01296292011-04-08 18:41:53 +00005215 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5216 ExprResult FromRes =
5217 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5218 if (FromRes.isInvalid())
5219 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005220 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005221 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005222
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005223 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005224 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005225 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005226 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005227}
5228
Douglas Gregor5fb53972009-01-14 15:45:31 +00005229/// TryContextuallyConvertToBool - Attempt to contextually convert the
5230/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005231static ImplicitConversionSequence
5232TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005233 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005234 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005235 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005236 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005237 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005238 /*AllowObjCWritebackConversion=*/false,
5239 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005240}
5241
5242/// PerformContextuallyConvertToBool - Perform a contextual conversion
5243/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005244ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005245 if (checkPlaceholderForOverload(*this, From))
5246 return ExprError();
5247
John McCall5c32be02010-08-24 20:38:10 +00005248 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005249 if (!ICS.isBad())
5250 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251
Fariborz Jahanian76197412009-11-18 18:26:29 +00005252 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005253 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005254 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005255 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005256 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005257}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Richard Smithf8379a02012-01-18 23:55:52 +00005259/// Check that the specified conversion is permitted in a converted constant
5260/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5261/// is acceptable.
5262static bool CheckConvertedConstantConversions(Sema &S,
5263 StandardConversionSequence &SCS) {
5264 // Since we know that the target type is an integral or unscoped enumeration
5265 // type, most conversion kinds are impossible. All possible First and Third
5266 // conversions are fine.
5267 switch (SCS.Second) {
5268 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005269 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005270 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005271 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005272 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005273 return true;
5274
5275 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005276 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005277 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5278 // conversion, so we allow it in a converted constant expression.
5279 //
5280 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5281 // a lot of popular code. We should at least add a warning for this
5282 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005283 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5284 SCS.getToType(2)->isBooleanType();
5285
Richard Smith410cc892014-11-26 03:26:53 +00005286 case ICK_Pointer_Conversion:
5287 case ICK_Pointer_Member:
5288 // C++1z: null pointer conversions and null member pointer conversions are
5289 // only permitted if the source type is std::nullptr_t.
5290 return SCS.getFromType()->isNullPtrType();
5291
5292 case ICK_Floating_Promotion:
5293 case ICK_Complex_Promotion:
5294 case ICK_Floating_Conversion:
5295 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005296 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005297 case ICK_Compatible_Conversion:
5298 case ICK_Derived_To_Base:
5299 case ICK_Vector_Conversion:
5300 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005301 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005302 case ICK_Block_Pointer_Conversion:
5303 case ICK_TransparentUnionConversion:
5304 case ICK_Writeback_Conversion:
5305 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005306 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005307 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005308 return false;
5309
5310 case ICK_Lvalue_To_Rvalue:
5311 case ICK_Array_To_Pointer:
5312 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005313 llvm_unreachable("found a first conversion kind in Second");
5314
Richard Smithf8379a02012-01-18 23:55:52 +00005315 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005316 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005317
5318 case ICK_Num_Conversion_Kinds:
5319 break;
5320 }
5321
5322 llvm_unreachable("unknown conversion kind");
5323}
5324
5325/// CheckConvertedConstantExpression - Check that the expression From is a
5326/// converted constant expression of type T, perform the conversion and produce
5327/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005328static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5329 QualType T, APValue &Value,
5330 Sema::CCEKind CCE,
5331 bool RequireInt) {
5332 assert(S.getLangOpts().CPlusPlus11 &&
5333 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005334
Richard Smith410cc892014-11-26 03:26:53 +00005335 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005336 return ExprError();
5337
Richard Smith410cc892014-11-26 03:26:53 +00005338 // C++1z [expr.const]p3:
5339 // A converted constant expression of type T is an expression,
5340 // implicitly converted to type T, where the converted
5341 // expression is a constant expression and the implicit conversion
5342 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005343 // C++1z [stmt.if]p2:
5344 // If the if statement is of the form if constexpr, the value of the
5345 // condition shall be a contextually converted constant expression of type
5346 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005347 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005348 CCE == Sema::CCEK_ConstexprIf
5349 ? TryContextuallyConvertToBool(S, From)
5350 : TryCopyInitialization(S, From, T,
5351 /*SuppressUserConversions=*/false,
5352 /*InOverloadResolution=*/false,
5353 /*AllowObjcWritebackConversion=*/false,
5354 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005355 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005356 switch (ICS.getKind()) {
5357 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005358 SCS = &ICS.Standard;
5359 break;
5360 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005361 // We are converting to a non-class type, so the Before sequence
5362 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005363 SCS = &ICS.UserDefined.After;
5364 break;
5365 case ImplicitConversionSequence::AmbiguousConversion:
5366 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005367 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5368 return S.Diag(From->getLocStart(),
5369 diag::err_typecheck_converted_constant_expression)
5370 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005371 return ExprError();
5372
5373 case ImplicitConversionSequence::EllipsisConversion:
5374 llvm_unreachable("ellipsis conversion in converted constant expression");
5375 }
5376
Richard Smith410cc892014-11-26 03:26:53 +00005377 // Check that we would only use permitted conversions.
5378 if (!CheckConvertedConstantConversions(S, *SCS)) {
5379 return S.Diag(From->getLocStart(),
5380 diag::err_typecheck_converted_constant_expression_disallowed)
5381 << From->getType() << From->getSourceRange() << T;
5382 }
5383 // [...] and where the reference binding (if any) binds directly.
5384 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5385 return S.Diag(From->getLocStart(),
5386 diag::err_typecheck_converted_constant_expression_indirect)
5387 << From->getType() << From->getSourceRange() << T;
5388 }
5389
5390 ExprResult Result =
5391 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005392 if (Result.isInvalid())
5393 return Result;
5394
5395 // Check for a narrowing implicit conversion.
5396 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005397 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005398 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005399 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005400 case NK_Dependent_Narrowing:
5401 // Implicit conversion to a narrower type, but the expression is
5402 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005403 case NK_Variable_Narrowing:
5404 // Implicit conversion to a narrower type, and the value is not a constant
5405 // expression. We'll diagnose this in a moment.
5406 case NK_Not_Narrowing:
5407 break;
5408
5409 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005410 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005411 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005412 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005413 break;
5414
5415 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005416 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005417 << CCE << /*Constant*/0 << From->getType() << T;
5418 break;
5419 }
5420
Richard Smith52e624f2016-12-21 21:42:57 +00005421 if (Result.get()->isValueDependent()) {
5422 Value = APValue();
5423 return Result;
5424 }
5425
Richard Smithf8379a02012-01-18 23:55:52 +00005426 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005427 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005428 Expr::EvalResult Eval;
5429 Eval.Diag = &Notes;
Reid Kleckner1a840d22018-05-10 18:57:35 +00005430 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5431 ? Expr::EvaluateForMangling
5432 : Expr::EvaluateForCodeGen;
Richard Smithf8379a02012-01-18 23:55:52 +00005433
Reid Kleckner1a840d22018-05-10 18:57:35 +00005434 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
Richard Smith410cc892014-11-26 03:26:53 +00005435 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005436 // The expression can't be folded, so we can't keep it at this position in
5437 // the AST.
5438 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005439 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005440 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005441
5442 if (Notes.empty()) {
5443 // It's a constant expression.
5444 return Result;
5445 }
Richard Smithf8379a02012-01-18 23:55:52 +00005446 }
5447
5448 // It's not a constant expression. Produce an appropriate diagnostic.
5449 if (Notes.size() == 1 &&
5450 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005451 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005452 else {
Richard Smith410cc892014-11-26 03:26:53 +00005453 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005454 << CCE << From->getSourceRange();
5455 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005456 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005457 }
Richard Smith410cc892014-11-26 03:26:53 +00005458 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005459}
5460
Richard Smith410cc892014-11-26 03:26:53 +00005461ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5462 APValue &Value, CCEKind CCE) {
5463 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5464}
5465
5466ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5467 llvm::APSInt &Value,
5468 CCEKind CCE) {
5469 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5470
5471 APValue V;
5472 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005473 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005474 Value = V.getInt();
5475 return R;
5476}
5477
5478
John McCallfec112d2011-09-09 06:11:02 +00005479/// dropPointerConversions - If the given standard conversion sequence
5480/// involves any pointer conversions, remove them. This may change
5481/// the result type of the conversion sequence.
5482static void dropPointerConversion(StandardConversionSequence &SCS) {
5483 if (SCS.Second == ICK_Pointer_Conversion) {
5484 SCS.Second = ICK_Identity;
5485 SCS.Third = ICK_Identity;
5486 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5487 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005488}
John McCall5c32be02010-08-24 20:38:10 +00005489
John McCallfec112d2011-09-09 06:11:02 +00005490/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5491/// convert the expression From to an Objective-C pointer type.
5492static ImplicitConversionSequence
5493TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5494 // Do an implicit conversion to 'id'.
5495 QualType Ty = S.Context.getObjCIdType();
5496 ImplicitConversionSequence ICS
5497 = TryImplicitConversion(S, From, Ty,
5498 // FIXME: Are these flags correct?
5499 /*SuppressUserConversions=*/false,
5500 /*AllowExplicit=*/true,
5501 /*InOverloadResolution=*/false,
5502 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005503 /*AllowObjCWritebackConversion=*/false,
5504 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005505
5506 // Strip off any final conversions to 'id'.
5507 switch (ICS.getKind()) {
5508 case ImplicitConversionSequence::BadConversion:
5509 case ImplicitConversionSequence::AmbiguousConversion:
5510 case ImplicitConversionSequence::EllipsisConversion:
5511 break;
5512
5513 case ImplicitConversionSequence::UserDefinedConversion:
5514 dropPointerConversion(ICS.UserDefined.After);
5515 break;
5516
5517 case ImplicitConversionSequence::StandardConversion:
5518 dropPointerConversion(ICS.Standard);
5519 break;
5520 }
5521
5522 return ICS;
5523}
5524
5525/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5526/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005527/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005528ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005529 if (checkPlaceholderForOverload(*this, From))
5530 return ExprError();
5531
John McCall8b07ec22010-05-15 11:32:37 +00005532 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005533 ImplicitConversionSequence ICS =
5534 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005535 if (!ICS.isBad())
5536 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005537 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005538}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005539
Richard Smith8dd34252012-02-04 07:07:42 +00005540/// Determine whether the provided type is an integral type, or an enumeration
5541/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005542bool Sema::ICEConvertDiagnoser::match(QualType T) {
5543 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5544 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005545}
5546
Larisse Voufo236bec22013-06-10 06:50:24 +00005547static ExprResult
5548diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5549 Sema::ContextualImplicitConverter &Converter,
5550 QualType T, UnresolvedSetImpl &ViableConversions) {
5551
5552 if (Converter.Suppress)
5553 return ExprError();
5554
5555 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5556 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5557 CXXConversionDecl *Conv =
5558 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5559 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5560 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5561 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005562 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005563}
5564
5565static bool
5566diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5567 Sema::ContextualImplicitConverter &Converter,
5568 QualType T, bool HadMultipleCandidates,
5569 UnresolvedSetImpl &ExplicitConversions) {
5570 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5571 DeclAccessPair Found = ExplicitConversions[0];
5572 CXXConversionDecl *Conversion =
5573 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5574
5575 // The user probably meant to invoke the given explicit
5576 // conversion; use it.
5577 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5578 std::string TypeStr;
5579 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5580
5581 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5582 << FixItHint::CreateInsertion(From->getLocStart(),
5583 "static_cast<" + TypeStr + ">(")
5584 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005585 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005586 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5587
5588 // If we aren't in a SFINAE context, build a call to the
5589 // explicit conversion function.
5590 if (SemaRef.isSFINAEContext())
5591 return true;
5592
Craig Topperc3ec1492014-05-26 06:22:03 +00005593 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005594 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5595 HadMultipleCandidates);
5596 if (Result.isInvalid())
5597 return true;
5598 // Record usage of conversion in an implicit cast.
5599 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005600 CK_UserDefinedConversion, Result.get(),
5601 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005602 }
5603 return false;
5604}
5605
5606static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5607 Sema::ContextualImplicitConverter &Converter,
5608 QualType T, bool HadMultipleCandidates,
5609 DeclAccessPair &Found) {
5610 CXXConversionDecl *Conversion =
5611 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005612 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005613
5614 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5615 if (!Converter.SuppressConversion) {
5616 if (SemaRef.isSFINAEContext())
5617 return true;
5618
5619 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5620 << From->getSourceRange();
5621 }
5622
5623 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5624 HadMultipleCandidates);
5625 if (Result.isInvalid())
5626 return true;
5627 // Record usage of conversion in an implicit cast.
5628 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005629 CK_UserDefinedConversion, Result.get(),
5630 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005631 return false;
5632}
5633
5634static ExprResult finishContextualImplicitConversion(
5635 Sema &SemaRef, SourceLocation Loc, Expr *From,
5636 Sema::ContextualImplicitConverter &Converter) {
5637 if (!Converter.match(From->getType()) && !Converter.Suppress)
5638 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5639 << From->getSourceRange();
5640
5641 return SemaRef.DefaultLvalueConversion(From);
5642}
5643
5644static void
5645collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5646 UnresolvedSetImpl &ViableConversions,
5647 OverloadCandidateSet &CandidateSet) {
5648 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5649 DeclAccessPair FoundDecl = ViableConversions[I];
5650 NamedDecl *D = FoundDecl.getDecl();
5651 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5652 if (isa<UsingShadowDecl>(D))
5653 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5654
5655 CXXConversionDecl *Conv;
5656 FunctionTemplateDecl *ConvTemplate;
5657 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5658 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5659 else
5660 Conv = cast<CXXConversionDecl>(D);
5661
5662 if (ConvTemplate)
5663 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005664 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5665 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005666 else
5667 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005668 ToType, CandidateSet,
5669 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005670 }
5671}
5672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005673/// Attempt to convert the given expression to a type which is accepted
Richard Smithccc11812013-05-21 19:05:48 +00005674/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005675///
Richard Smithccc11812013-05-21 19:05:48 +00005676/// This routine will attempt to convert an expression of class type to a
5677/// type accepted by the specified converter. In C++11 and before, the class
5678/// must have a single non-explicit conversion function converting to a matching
5679/// type. In C++1y, there can be multiple such conversion functions, but only
5680/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005681///
Douglas Gregor4799d032010-06-30 00:20:43 +00005682/// \param Loc The source location of the construct that requires the
5683/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005684///
James Dennett18348b62012-06-22 08:52:37 +00005685/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005686///
Richard Smithccc11812013-05-21 19:05:48 +00005687/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005688///
Douglas Gregor4799d032010-06-30 00:20:43 +00005689/// \returns The expression, converted to an integral or enumeration type if
5690/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005691ExprResult Sema::PerformContextualImplicitConversion(
5692 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005693 // We can't perform any more checking for type-dependent expressions.
5694 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005695 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Eli Friedman1da70392012-01-26 00:26:18 +00005697 // Process placeholders immediately.
5698 if (From->hasPlaceholderType()) {
5699 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005700 if (result.isInvalid())
5701 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005702 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005703 }
5704
Richard Smithccc11812013-05-21 19:05:48 +00005705 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005706 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005707 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005708 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709
5710 // FIXME: Check for missing '()' if T is a function type?
5711
Richard Smithccc11812013-05-21 19:05:48 +00005712 // We can only perform contextual implicit conversions on objects of class
5713 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005714 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005715 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005716 if (!Converter.Suppress)
5717 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005718 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005721 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005722 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005723 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005724 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005725
5726 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005727 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005728
Craig Toppere14c0f82014-03-12 04:55:44 +00005729 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005730 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005731 }
Richard Smithccc11812013-05-21 19:05:48 +00005732 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005733
Richard Smithdb0ac552015-12-18 22:40:25 +00005734 if (Converter.Suppress ? !isCompleteType(Loc, T)
5735 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005736 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005738 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005739 UnresolvedSet<4>
5740 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005741 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005742 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005743 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Larisse Voufo236bec22013-06-10 06:50:24 +00005745 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005746 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005747
Larisse Voufo236bec22013-06-10 06:50:24 +00005748 // To check that there is only one target type, in C++1y:
5749 QualType ToType;
5750 bool HasUniqueTargetType = true;
5751
5752 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005753 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005754 NamedDecl *D = (*I)->getUnderlyingDecl();
5755 CXXConversionDecl *Conversion;
5756 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5757 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005758 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005759 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5760 else
5761 continue; // C++11 does not consider conversion operator templates(?).
5762 } else
5763 Conversion = cast<CXXConversionDecl>(D);
5764
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005765 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005766 "Conversion operator templates are considered potentially "
5767 "viable in C++1y");
5768
5769 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5770 if (Converter.match(CurToType) || ConvTemplate) {
5771
5772 if (Conversion->isExplicit()) {
5773 // FIXME: For C++1y, do we need this restriction?
5774 // cf. diagnoseNoViableConversion()
5775 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005776 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005777 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005778 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005779 if (ToType.isNull())
5780 ToType = CurToType.getUnqualifiedType();
5781 else if (HasUniqueTargetType &&
5782 (CurToType.getUnqualifiedType() != ToType))
5783 HasUniqueTargetType = false;
5784 }
5785 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005786 }
Richard Smith8dd34252012-02-04 07:07:42 +00005787 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005790 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005791 // C++1y [conv]p6:
5792 // ... An expression e of class type E appearing in such a context
5793 // is said to be contextually implicitly converted to a specified
5794 // type T and is well-formed if and only if e can be implicitly
5795 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005796 // for conversion functions whose return type is cv T or reference to
5797 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005798 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Larisse Voufo236bec22013-06-10 06:50:24 +00005800 // If no unique T is found:
5801 if (ToType.isNull()) {
5802 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5803 HadMultipleCandidates,
5804 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005805 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005806 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005808
Larisse Voufo236bec22013-06-10 06:50:24 +00005809 // If more than one unique Ts are found:
5810 if (!HasUniqueTargetType)
5811 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5812 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005813
Larisse Voufo236bec22013-06-10 06:50:24 +00005814 // If one unique T is found:
5815 // First, build a candidate set from the previously recorded
5816 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005817 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005818 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5819 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005820
Larisse Voufo236bec22013-06-10 06:50:24 +00005821 // Then, perform overload resolution over the candidate set.
5822 OverloadCandidateSet::iterator Best;
5823 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5824 case OR_Success: {
5825 // Apply this conversion.
5826 DeclAccessPair Found =
5827 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5828 if (recordConversion(*this, Loc, From, Converter, T,
5829 HadMultipleCandidates, Found))
5830 return ExprError();
5831 break;
5832 }
5833 case OR_Ambiguous:
5834 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5835 ViableConversions);
5836 case OR_No_Viable_Function:
5837 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5838 HadMultipleCandidates,
5839 ExplicitConversions))
5840 return ExprError();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005841 LLVM_FALLTHROUGH;
Larisse Voufo236bec22013-06-10 06:50:24 +00005842 case OR_Deleted:
5843 // We'll complain below about a non-integral condition type.
5844 break;
5845 }
5846 } else {
5847 switch (ViableConversions.size()) {
5848 case 0: {
5849 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5850 HadMultipleCandidates,
5851 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005852 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
Larisse Voufo236bec22013-06-10 06:50:24 +00005854 // We'll complain below about a non-integral condition type.
5855 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005856 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005857 case 1: {
5858 // Apply this conversion.
5859 DeclAccessPair Found = ViableConversions[0];
5860 if (recordConversion(*this, Loc, From, Converter, T,
5861 HadMultipleCandidates, Found))
5862 return ExprError();
5863 break;
5864 }
5865 default:
5866 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5867 ViableConversions);
5868 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
Larisse Voufo236bec22013-06-10 06:50:24 +00005871 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005872}
5873
Richard Smith100b24a2014-04-17 01:52:14 +00005874/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5875/// an acceptable non-member overloaded operator for a call whose
5876/// arguments have types T1 (and, if non-empty, T2). This routine
5877/// implements the check in C++ [over.match.oper]p3b2 concerning
5878/// enumeration types.
5879static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5880 FunctionDecl *Fn,
5881 ArrayRef<Expr *> Args) {
5882 QualType T1 = Args[0]->getType();
5883 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5884
5885 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5886 return true;
5887
5888 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5889 return true;
5890
5891 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5892 if (Proto->getNumParams() < 1)
5893 return false;
5894
5895 if (T1->isEnumeralType()) {
5896 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5897 if (Context.hasSameUnqualifiedType(T1, ArgType))
5898 return true;
5899 }
5900
5901 if (Proto->getNumParams() < 2)
5902 return false;
5903
5904 if (!T2.isNull() && T2->isEnumeralType()) {
5905 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5906 if (Context.hasSameUnqualifiedType(T2, ArgType))
5907 return true;
5908 }
5909
5910 return false;
5911}
5912
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005913/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005914/// candidate functions, using the given function call arguments. If
5915/// @p SuppressUserConversions, then don't allow user-defined
5916/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005917///
James Dennett2a4d13c2012-06-15 07:13:21 +00005918/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005919/// based on an incomplete set of function arguments. This feature is used by
5920/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005921void
5922Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005923 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005924 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005925 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005926 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005927 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005928 bool AllowExplicit,
5929 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005930 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005931 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005932 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005933 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005934 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005935
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005937 if (!isa<CXXConstructorDecl>(Method)) {
5938 // If we get here, it's because we're calling a member function
5939 // that is named without a member access expression (e.g.,
5940 // "this->f") that was either written explicitly or created
5941 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005942 // function, e.g., X::f(). We use an empty type for the implied
5943 // object argument (C++ [over.call.func]p3), and the acting context
5944 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005945 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005946 Expr::Classification::makeSimpleLValue(), Args,
5947 CandidateSet, SuppressUserConversions,
5948 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005949 return;
5950 }
5951 // We treat a constructor like a non-member function, since its object
5952 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005953 }
5954
Douglas Gregorff7028a2009-11-13 23:59:09 +00005955 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005956 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005957
Richard Smith100b24a2014-04-17 01:52:14 +00005958 // C++ [over.match.oper]p3:
5959 // if no operand has a class type, only those non-member functions in the
5960 // lookup set that have a first parameter of type T1 or "reference to
5961 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5962 // is a right operand) a second parameter of type T2 or "reference to
5963 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5964 // candidate functions.
5965 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5966 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5967 return;
5968
Richard Smith8b86f2d2013-11-04 01:48:18 +00005969 // C++11 [class.copy]p11: [DR1402]
5970 // A defaulted move constructor that is defined as deleted is ignored by
5971 // overload resolution.
5972 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5973 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5974 Constructor->isMoveConstructor())
5975 return;
5976
Douglas Gregor27381f32009-11-23 12:27:39 +00005977 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005978 EnterExpressionEvaluationContext Unevaluated(
5979 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005980
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005981 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005982 OverloadCandidate &Candidate =
5983 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005984 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005985 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005986 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005987 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005988 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005989 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990
Erich Keane3efe0022018-07-20 14:13:28 +00005991 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00005992 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5993 Candidate.Viable = false;
5994 Candidate.FailureKind = ovl_non_default_multiversion_function;
5995 return;
5996 }
5997
John McCall578a1f82014-12-14 01:46:53 +00005998 if (Constructor) {
5999 // C++ [class.copy]p3:
6000 // A member function template is never instantiated to perform the copy
6001 // of a class object to an object of its class type.
6002 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00006003 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00006004 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00006005 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
6006 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00006007 Candidate.Viable = false;
6008 Candidate.FailureKind = ovl_fail_illegal_constructor;
6009 return;
6010 }
Richard Smith836a3b42017-01-13 20:46:54 +00006011
6012 // C++ [over.match.funcs]p8: (proposed DR resolution)
6013 // A constructor inherited from class type C that has a first parameter
6014 // of type "reference to P" (including such a constructor instantiated
6015 // from a template) is excluded from the set of candidate functions when
6016 // constructing an object of type cv D if the argument list has exactly
6017 // one argument and D is reference-related to P and P is reference-related
6018 // to C.
6019 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6020 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6021 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6022 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6023 QualType C = Context.getRecordType(Constructor->getParent());
6024 QualType D = Context.getRecordType(Shadow->getParent());
6025 SourceLocation Loc = Args.front()->getExprLoc();
6026 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6027 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6028 Candidate.Viable = false;
6029 Candidate.FailureKind = ovl_fail_inhctor_slice;
6030 return;
6031 }
6032 }
John McCall578a1f82014-12-14 01:46:53 +00006033 }
6034
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006035 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006036
6037 // (C++ 13.3.2p2): A candidate function having fewer than m
6038 // parameters is viable only if it has an ellipsis in its parameter
6039 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006040 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00006041 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006042 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006043 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006044 return;
6045 }
6046
6047 // (C++ 13.3.2p2): A candidate function having more than m parameters
6048 // is viable only if the (m+1)st parameter has a default argument
6049 // (8.3.6). For the purposes of overload resolution, the
6050 // parameter list is truncated on the right, so that there are
6051 // exactly m parameters.
6052 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006053 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006054 // Not enough arguments.
6055 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006056 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006057 return;
6058 }
6059
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006060 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006061 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006062 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006063 // Skip the check for callers that are implicit members, because in this
6064 // case we may not yet know what the member's target is; the target is
6065 // inferred for the member automatically, based on the bases and fields of
6066 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006067 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006068 Candidate.Viable = false;
6069 Candidate.FailureKind = ovl_fail_bad_target;
6070 return;
6071 }
6072
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006073 // Determine the implicit conversion sequences for each of the
6074 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006075 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006076 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6077 // We already formed a conversion sequence for this parameter during
6078 // template argument deduction.
6079 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006080 // (C++ 13.3.2p3): for F to be a viable function, there shall
6081 // exist for each argument an implicit conversion sequence
6082 // (13.3.3.1) that converts that argument to the corresponding
6083 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006084 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006085 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006086 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006088 /*InOverloadResolution=*/true,
6089 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006090 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006091 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006092 if (Candidate.Conversions[ArgIdx].isBad()) {
6093 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006094 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006095 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006096 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006097 } else {
6098 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6099 // argument for which there is no corresponding parameter is
6100 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006101 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006102 }
6103 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006104
6105 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6106 Candidate.Viable = false;
6107 Candidate.FailureKind = ovl_fail_enable_if;
6108 Candidate.DeductionFailure.Data = FailedAttr;
6109 return;
6110 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006111
6112 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6113 Candidate.Viable = false;
6114 Candidate.FailureKind = ovl_fail_ext_disabled;
6115 return;
6116 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006117}
6118
Manman Rend2a3cd72016-04-07 19:30:20 +00006119ObjCMethodDecl *
6120Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6121 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6122 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006123 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006124
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006125 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6126 bool Match = true;
6127 ObjCMethodDecl *Method = Methods[b];
6128 unsigned NumNamedArgs = Sel.getNumArgs();
6129 // Method might have more arguments than selector indicates. This is due
6130 // to addition of c-style arguments in method.
6131 if (Method->param_size() > NumNamedArgs)
6132 NumNamedArgs = Method->param_size();
6133 if (Args.size() < NumNamedArgs)
6134 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006135
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006136 for (unsigned i = 0; i < NumNamedArgs; i++) {
6137 // We can't do any type-checking on a type-dependent argument.
6138 if (Args[i]->isTypeDependent()) {
6139 Match = false;
6140 break;
6141 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006142
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006143 ParmVarDecl *param = Method->parameters()[i];
6144 Expr *argExpr = Args[i];
6145 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006146
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006147 // Strip the unbridged-cast placeholder expression off unless it's
6148 // a consumed argument.
6149 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6150 !param->hasAttr<CFConsumedAttr>())
6151 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006152
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006153 // If the parameter is __unknown_anytype, move on to the next method.
6154 if (param->getType() == Context.UnknownAnyTy) {
6155 Match = false;
6156 break;
6157 }
George Burgess IV45461812015-10-11 20:13:20 +00006158
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006159 ImplicitConversionSequence ConversionState
6160 = TryCopyInitialization(*this, argExpr, param->getType(),
6161 /*SuppressUserConversions*/false,
6162 /*InOverloadResolution=*/true,
6163 /*AllowObjCWritebackConversion=*/
6164 getLangOpts().ObjCAutoRefCount,
6165 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006166 // This function looks for a reasonably-exact match, so we consider
6167 // incompatible pointer conversions to be a failure here.
6168 if (ConversionState.isBad() ||
6169 (ConversionState.isStandard() &&
6170 ConversionState.Standard.Second ==
6171 ICK_Incompatible_Pointer_Conversion)) {
6172 Match = false;
6173 break;
6174 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006175 }
6176 // Promote additional arguments to variadic methods.
6177 if (Match && Method->isVariadic()) {
6178 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6179 if (Args[i]->isTypeDependent()) {
6180 Match = false;
6181 break;
6182 }
6183 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6184 nullptr);
6185 if (Arg.isInvalid()) {
6186 Match = false;
6187 break;
6188 }
6189 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006190 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006191 // Check for extra arguments to non-variadic methods.
6192 if (Args.size() != NumNamedArgs)
6193 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006194 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6195 // Special case when selectors have no argument. In this case, select
6196 // one with the most general result type of 'id'.
6197 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6198 QualType ReturnT = Methods[b]->getReturnType();
6199 if (ReturnT->isObjCIdType())
6200 return Methods[b];
6201 }
6202 }
6203 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006204
6205 if (Match)
6206 return Method;
6207 }
6208 return nullptr;
6209}
6210
Michael Kruse41dd6ce2018-06-25 20:06:13 +00006211// specific_attr_iterator iterates over enable_if attributes in reverse, and
6212// enable_if is order-sensitive. As a result, we need to reverse things
6213// sometimes. Size of 4 elements is arbitrary.
6214static SmallVector<EnableIfAttr *, 4>
6215getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6216 SmallVector<EnableIfAttr *, 4> Result;
6217 if (!Function->hasAttrs())
6218 return Result;
6219
6220 const auto &FuncAttrs = Function->getAttrs();
6221 for (Attr *Attr : FuncAttrs)
6222 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6223 Result.push_back(EnableIf);
6224
6225 std::reverse(Result.begin(), Result.end());
6226 return Result;
6227}
6228
George Burgess IV177399e2017-01-09 04:12:14 +00006229static bool
6230convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6231 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6232 bool MissingImplicitThis, Expr *&ConvertedThis,
6233 SmallVectorImpl<Expr *> &ConvertedArgs) {
6234 if (ThisArg) {
6235 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6236 assert(!isa<CXXConstructorDecl>(Method) &&
6237 "Shouldn't have `this` for ctors!");
6238 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6239 ExprResult R = S.PerformObjectArgumentInitialization(
6240 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6241 if (R.isInvalid())
6242 return false;
6243 ConvertedThis = R.get();
6244 } else {
6245 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6246 (void)MD;
6247 assert((MissingImplicitThis || MD->isStatic() ||
6248 isa<CXXConstructorDecl>(MD)) &&
6249 "Expected `this` for non-ctor instance methods");
6250 }
6251 ConvertedThis = nullptr;
6252 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006253
George Burgess IV458b3f32016-08-12 04:19:35 +00006254 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006255 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006256 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6257
Nick Lewyckye283c552015-08-25 22:33:16 +00006258 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006259 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006260 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006261 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6262 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006263 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006264
George Burgess IV177399e2017-01-09 04:12:14 +00006265 if (R.isInvalid())
6266 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006267
George Burgess IVe96abf72016-02-24 22:31:14 +00006268 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006269 }
6270
George Burgess IV177399e2017-01-09 04:12:14 +00006271 if (Trap.hasErrorOccurred())
6272 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006273
Nick Lewyckye283c552015-08-25 22:33:16 +00006274 // Push default arguments if needed.
6275 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6276 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6277 ParmVarDecl *P = Function->getParamDecl(i);
Ilya Biryukov1a1dffd2018-03-09 14:43:29 +00006278 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6279 ? P->getUninstantiatedDefaultArg()
6280 : P->getDefaultArg();
6281 // This can only happen in code completion, i.e. when PartialOverloading
6282 // is true.
6283 if (!DefArg)
6284 return false;
6285 ExprResult R =
6286 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6287 S.Context, Function->getParamDecl(i)),
6288 SourceLocation(), DefArg);
George Burgess IV177399e2017-01-09 04:12:14 +00006289 if (R.isInvalid())
6290 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006291 ConvertedArgs.push_back(R.get());
6292 }
6293
George Burgess IV177399e2017-01-09 04:12:14 +00006294 if (Trap.hasErrorOccurred())
6295 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006296 }
George Burgess IV177399e2017-01-09 04:12:14 +00006297 return true;
6298}
6299
6300EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6301 bool MissingImplicitThis) {
Michael Kruse41dd6ce2018-06-25 20:06:13 +00006302 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6303 getOrderedEnableIfAttrs(Function);
6304 if (EnableIfAttrs.empty())
George Burgess IV177399e2017-01-09 04:12:14 +00006305 return nullptr;
6306
6307 SFINAETrap Trap(*this);
6308 SmallVector<Expr *, 16> ConvertedArgs;
6309 // FIXME: We should look into making enable_if late-parsed.
6310 Expr *DiscardedThis;
6311 if (!convertArgsForAvailabilityChecks(
6312 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6313 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
Michael Kruse41dd6ce2018-06-25 20:06:13 +00006314 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006315
George Burgess IV2a6150d2015-10-16 01:17:38 +00006316 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006317 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006318 // FIXME: This doesn't consider value-dependent cases, because doing so is
6319 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006320 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006321 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006322 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006323
6324 if (!Result.isInt() || !Result.getInt().getBoolValue())
6325 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006326 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006327 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006328}
6329
George Burgess IV177399e2017-01-09 04:12:14 +00006330template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006331static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006332 bool ArgDependent, SourceLocation Loc,
6333 CheckFn &&IsSuccessful) {
6334 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006335 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006336 if (ArgDependent == DIA->getArgDependent())
6337 Attrs.push_back(DIA);
6338 }
6339
6340 // Common case: No diagnose_if attributes, so we can quit early.
6341 if (Attrs.empty())
6342 return false;
6343
6344 auto WarningBegin = std::stable_partition(
6345 Attrs.begin(), Attrs.end(),
6346 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6347
George Burgess IV177399e2017-01-09 04:12:14 +00006348 // Note that diagnose_if attributes are late-parsed, so they appear in the
6349 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006350 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6351 IsSuccessful);
6352 if (ErrAttr != WarningBegin) {
6353 const DiagnoseIfAttr *DIA = *ErrAttr;
6354 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6355 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6356 << DIA->getParent() << DIA->getCond()->getSourceRange();
6357 return true;
6358 }
George Burgess IV177399e2017-01-09 04:12:14 +00006359
George Burgess IVce6284b2017-01-28 02:19:40 +00006360 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6361 if (IsSuccessful(DIA)) {
6362 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6363 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6364 << DIA->getParent() << DIA->getCond()->getSourceRange();
6365 }
6366
6367 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006368}
6369
George Burgess IVce6284b2017-01-28 02:19:40 +00006370bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6371 const Expr *ThisArg,
6372 ArrayRef<const Expr *> Args,
6373 SourceLocation Loc) {
6374 return diagnoseDiagnoseIfAttrsWith(
6375 *this, Function, /*ArgDependent=*/true, Loc,
6376 [&](const DiagnoseIfAttr *DIA) {
6377 APValue Result;
6378 // It's sane to use the same Args for any redecl of this function, since
6379 // EvaluateWithSubstitution only cares about the position of each
6380 // argument in the arg list, not the ParmVarDecl* it maps to.
6381 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006382 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006383 return false;
6384 return Result.isInt() && Result.getInt().getBoolValue();
6385 });
George Burgess IV177399e2017-01-09 04:12:14 +00006386}
6387
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006388bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006389 SourceLocation Loc) {
6390 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006391 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006392 [&](const DiagnoseIfAttr *DIA) {
6393 bool Result;
6394 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6395 Result;
6396 });
George Burgess IV177399e2017-01-09 04:12:14 +00006397}
6398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006399/// Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006400/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006401void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006402 ArrayRef<Expr *> Args,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006403 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006404 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006405 bool SuppressUserConversions,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006406 bool PartialOverloading,
6407 bool FirstArgumentIsBase) {
John McCall4c4c1df2010-01-26 03:27:55 +00006408 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006409 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006410 ArrayRef<Expr *> FunctionArgs = Args;
6411
6412 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6413 FunctionDecl *FD =
6414 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6415
6416 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6417 QualType ObjectType;
6418 Expr::Classification ObjectClassification;
6419 if (Args.size() > 0) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006420 if (Expr *E = Args[0]) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006421 // Use the explicit base to restrict the lookup:
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006422 ObjectType = E->getType();
6423 ObjectClassification = E->Classify(Context);
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006424 } // .. else there is an implicit base.
6425 FunctionArgs = Args.slice(1);
6426 }
6427 if (FunTmpl) {
George Burgess IV177399e2017-01-09 04:12:14 +00006428 AddMethodTemplateCandidate(
6429 FunTmpl, F.getPair(),
6430 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006431 ExplicitTemplateArgs, ObjectType, ObjectClassification,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006432 FunctionArgs, CandidateSet, SuppressUserConversions,
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006433 PartialOverloading);
6434 } else {
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006435 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6436 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6437 ObjectClassification, FunctionArgs, CandidateSet,
6438 SuppressUserConversions, PartialOverloading);
6439 }
6440 } else {
6441 // This branch handles both standalone functions and static methods.
6442
6443 // Slice the first argument (which is the base) when we access
6444 // static method as non-static.
6445 if (Args.size() > 0 &&
6446 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6447 !isa<CXXConstructorDecl>(FD)))) {
6448 assert(cast<CXXMethodDecl>(FD)->isStatic());
6449 FunctionArgs = Args.slice(1);
6450 }
6451 if (FunTmpl) {
6452 AddTemplateOverloadCandidate(
6453 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6454 CandidateSet, SuppressUserConversions, PartialOverloading);
6455 } else {
6456 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6457 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006458 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006459 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006460 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006461}
6462
John McCallf0f1cf02009-11-17 07:50:12 +00006463/// AddMethodCandidate - Adds a named decl (which is some kind of
6464/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006465void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006466 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006467 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006468 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006469 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006470 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006471 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006472 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006473
6474 if (isa<UsingShadowDecl>(Decl))
6475 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476
John McCallf0f1cf02009-11-17 07:50:12 +00006477 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6478 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6479 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006480 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006481 /*ExplicitArgs*/ nullptr, ObjectType,
6482 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006483 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006484 } else {
John McCalla0296f72010-03-19 07:35:19 +00006485 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006486 ObjectType, ObjectClassification, Args, CandidateSet,
6487 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006488 }
6489}
6490
Douglas Gregor436424c2008-11-18 23:14:02 +00006491/// AddMethodCandidate - Adds the given C++ member function to the set
6492/// of candidate functions, using the given function call arguments
6493/// and the object argument (@c Object). For example, in a call
6494/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6495/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6496/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006497/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006498void
John McCalla0296f72010-03-19 07:35:19 +00006499Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006500 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006501 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006502 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006503 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006504 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006505 bool PartialOverloading,
6506 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006507 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006508 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006509 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006510 assert(!isa<CXXConstructorDecl>(Method) &&
6511 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006512
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006513 if (!CandidateSet.isNewCandidate(Method))
6514 return;
6515
Richard Smith8b86f2d2013-11-04 01:48:18 +00006516 // C++11 [class.copy]p23: [DR1402]
6517 // A defaulted move assignment operator that is defined as deleted is
6518 // ignored by overload resolution.
6519 if (Method->isDefaulted() && Method->isDeleted() &&
6520 Method->isMoveAssignmentOperator())
6521 return;
6522
Douglas Gregor27381f32009-11-23 12:27:39 +00006523 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006524 EnterExpressionEvaluationContext Unevaluated(
6525 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006526
Douglas Gregor436424c2008-11-18 23:14:02 +00006527 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006528 OverloadCandidate &Candidate =
6529 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006530 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006531 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006532 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006533 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006534 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006535
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006536 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006537
6538 // (C++ 13.3.2p2): A candidate function having fewer than m
6539 // parameters is viable only if it has an ellipsis in its parameter
6540 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006541 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6542 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006543 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006544 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006545 return;
6546 }
6547
6548 // (C++ 13.3.2p2): A candidate function having more than m parameters
6549 // is viable only if the (m+1)st parameter has a default argument
6550 // (8.3.6). For the purposes of overload resolution, the
6551 // parameter list is truncated on the right, so that there are
6552 // exactly m parameters.
6553 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006554 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006555 // Not enough arguments.
6556 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006557 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006558 return;
6559 }
6560
6561 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006562
John McCall6e9f8f62009-12-03 04:06:58 +00006563 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006564 // The implicit object argument is ignored.
6565 Candidate.IgnoreObjectArgument = true;
6566 else {
6567 // Determine the implicit conversion sequence for the object
6568 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006569 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6570 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6571 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006572 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006573 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006574 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006575 return;
6576 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006577 }
6578
Eli Bendersky291a57e2014-09-25 23:59:08 +00006579 // (CUDA B.1): Check for invalid calls between targets.
6580 if (getLangOpts().CUDA)
6581 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006582 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006583 Candidate.Viable = false;
6584 Candidate.FailureKind = ovl_fail_bad_target;
6585 return;
6586 }
6587
Douglas Gregor436424c2008-11-18 23:14:02 +00006588 // Determine the implicit conversion sequences for each of the
6589 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006590 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006591 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6592 // We already formed a conversion sequence for this parameter during
6593 // template argument deduction.
6594 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006595 // (C++ 13.3.2p3): for F to be a viable function, there shall
6596 // exist for each argument an implicit conversion sequence
6597 // (13.3.3.1) that converts that argument to the corresponding
6598 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006599 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006600 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006601 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006603 /*InOverloadResolution=*/true,
6604 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006605 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006606 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006607 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006608 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006609 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006610 }
6611 } else {
6612 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6613 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006614 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006615 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006616 }
6617 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006618
6619 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6620 Candidate.Viable = false;
6621 Candidate.FailureKind = ovl_fail_enable_if;
6622 Candidate.DeductionFailure.Data = FailedAttr;
6623 return;
6624 }
Erich Keane281d20b2018-01-08 21:34:17 +00006625
Erich Keane3efe0022018-07-20 14:13:28 +00006626 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00006627 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6628 Candidate.Viable = false;
6629 Candidate.FailureKind = ovl_non_default_multiversion_function;
6630 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006633/// Add a C++ member function template as a candidate to the candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006634/// set, using template argument deduction to produce an appropriate member
6635/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006636void
Douglas Gregor97628d62009-08-21 00:16:32 +00006637Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006638 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006639 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006640 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006641 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006642 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006643 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006644 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006645 bool SuppressUserConversions,
6646 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006647 if (!CandidateSet.isNewCandidate(MethodTmpl))
6648 return;
6649
Douglas Gregor97628d62009-08-21 00:16:32 +00006650 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006651 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006652 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006653 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006654 // candidate functions in the usual way.113) A given name can refer to one
6655 // or more function templates and also to a set of overloaded non-template
6656 // functions. In such a case, the candidate functions generated from each
6657 // function template are combined with the set of non-template candidate
6658 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006659 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006660 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006661 ConversionSequenceList Conversions;
6662 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6663 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6664 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6665 return CheckNonDependentConversions(
6666 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6667 SuppressUserConversions, ActingContext, ObjectType,
6668 ObjectClassification);
6669 })) {
6670 OverloadCandidate &Candidate =
6671 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006672 Candidate.FoundDecl = FoundDecl;
6673 Candidate.Function = MethodTmpl->getTemplatedDecl();
6674 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006675 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006676 Candidate.IgnoreObjectArgument =
6677 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6678 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006679 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006680 if (Result == TDK_NonDependentConversionFailure)
6681 Candidate.FailureKind = ovl_fail_bad_conversion;
6682 else {
6683 Candidate.FailureKind = ovl_fail_bad_deduction;
6684 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6685 Info);
6686 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006687 return;
6688 }
Mike Stump11289f42009-09-09 15:08:12 +00006689
Douglas Gregor97628d62009-08-21 00:16:32 +00006690 // Add the function template specialization produced by template argument
6691 // deduction as a candidate.
6692 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006693 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006694 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006695 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006696 ActingContext, ObjectType, ObjectClassification, Args,
6697 CandidateSet, SuppressUserConversions, PartialOverloading,
6698 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006699}
6700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006701/// Add a C++ function template specialization as a candidate
Douglas Gregor05155d82009-08-21 23:19:43 +00006702/// in the candidate set, using template argument deduction to produce
6703/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006704void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006705Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006706 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006707 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006708 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006709 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006710 bool SuppressUserConversions,
6711 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006712 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6713 return;
6714
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006715 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006716 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006717 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006718 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006719 // candidate functions in the usual way.113) A given name can refer to one
6720 // or more function templates and also to a set of overloaded non-template
6721 // functions. In such a case, the candidate functions generated from each
6722 // function template are combined with the set of non-template candidate
6723 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006724 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006725 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006726 ConversionSequenceList Conversions;
6727 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6728 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6729 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6730 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6731 Args, CandidateSet, Conversions,
6732 SuppressUserConversions);
6733 })) {
6734 OverloadCandidate &Candidate =
6735 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006736 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006737 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6738 Candidate.Viable = false;
6739 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006740 // Ignore the object argument if there is one, since we don't have an object
6741 // type.
6742 Candidate.IgnoreObjectArgument =
6743 isa<CXXMethodDecl>(Candidate.Function) &&
6744 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006745 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006746 if (Result == TDK_NonDependentConversionFailure)
6747 Candidate.FailureKind = ovl_fail_bad_conversion;
6748 else {
6749 Candidate.FailureKind = ovl_fail_bad_deduction;
6750 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6751 Info);
6752 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006753 return;
6754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006756 // Add the function template specialization produced by template argument
6757 // deduction as a candidate.
6758 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006759 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006760 SuppressUserConversions, PartialOverloading,
6761 /*AllowExplicit*/false, Conversions);
6762}
6763
6764/// Check that implicit conversion sequences can be formed for each argument
6765/// whose corresponding parameter has a non-dependent type, per DR1391's
6766/// [temp.deduct.call]p10.
6767bool Sema::CheckNonDependentConversions(
6768 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6769 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6770 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6771 CXXRecordDecl *ActingContext, QualType ObjectType,
6772 Expr::Classification ObjectClassification) {
6773 // FIXME: The cases in which we allow explicit conversions for constructor
6774 // arguments never consider calling a constructor template. It's not clear
6775 // that is correct.
6776 const bool AllowExplicit = false;
6777
6778 auto *FD = FunctionTemplate->getTemplatedDecl();
6779 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6780 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6781 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6782
6783 Conversions =
6784 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6785
6786 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006787 EnterExpressionEvaluationContext Unevaluated(
6788 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006789
6790 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6791 // require that, but this check should never result in a hard error, and
6792 // overload resolution is permitted to sidestep instantiations.
6793 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6794 !ObjectType.isNull()) {
6795 Conversions[0] = TryObjectArgumentInitialization(
6796 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6797 Method, ActingContext);
6798 if (Conversions[0].isBad())
6799 return true;
6800 }
6801
6802 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6803 ++I) {
6804 QualType ParamType = ParamTypes[I];
6805 if (!ParamType->isDependentType()) {
6806 Conversions[ThisConversions + I]
6807 = TryCopyInitialization(*this, Args[I], ParamType,
6808 SuppressUserConversions,
6809 /*InOverloadResolution=*/true,
6810 /*AllowObjCWritebackConversion=*/
6811 getLangOpts().ObjCAutoRefCount,
6812 AllowExplicit);
6813 if (Conversions[ThisConversions + I].isBad())
6814 return true;
6815 }
6816 }
6817
6818 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006819}
Mike Stump11289f42009-09-09 15:08:12 +00006820
Douglas Gregor4b60a152013-11-07 22:34:54 +00006821/// Determine whether this is an allowable conversion from the result
6822/// of an explicit conversion operator to the expected type, per C++
6823/// [over.match.conv]p1 and [over.match.ref]p1.
6824///
6825/// \param ConvType The return type of the conversion function.
6826///
6827/// \param ToType The type we are converting to.
6828///
6829/// \param AllowObjCPointerConversion Allow a conversion from one
6830/// Objective-C pointer to another.
6831///
6832/// \returns true if the conversion is allowable, false otherwise.
6833static bool isAllowableExplicitConversion(Sema &S,
6834 QualType ConvType, QualType ToType,
6835 bool AllowObjCPointerConversion) {
6836 QualType ToNonRefType = ToType.getNonReferenceType();
6837
6838 // Easy case: the types are the same.
6839 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6840 return true;
6841
6842 // Allow qualification conversions.
6843 bool ObjCLifetimeConversion;
6844 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6845 ObjCLifetimeConversion))
6846 return true;
6847
6848 // If we're not allowed to consider Objective-C pointer conversions,
6849 // we're done.
6850 if (!AllowObjCPointerConversion)
6851 return false;
6852
6853 // Is this an Objective-C pointer conversion?
6854 bool IncompatibleObjC = false;
6855 QualType ConvertedType;
6856 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6857 IncompatibleObjC);
6858}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006859
Douglas Gregora1f013e2008-11-07 22:36:19 +00006860/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006861/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006862/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006863/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006864/// (which may or may not be the same type as the type that the
6865/// conversion function produces).
6866void
6867Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006868 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006869 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006870 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006871 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006872 bool AllowObjCConversionOnExplicit,
6873 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006874 assert(!Conversion->getDescribedFunctionTemplate() &&
6875 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006876 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006877 if (!CandidateSet.isNewCandidate(Conversion))
6878 return;
6879
Richard Smith2a7d4812013-05-04 07:00:32 +00006880 // If the conversion function has an undeduced return type, trigger its
6881 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006882 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006883 if (DeduceReturnType(Conversion, From->getExprLoc()))
6884 return;
6885 ConvType = Conversion->getConversionType().getNonReferenceType();
6886 }
6887
Richard Smith67ef14f2017-09-26 18:37:55 +00006888 // If we don't allow any conversion of the result type, ignore conversion
6889 // functions that don't convert to exactly (possibly cv-qualified) T.
6890 if (!AllowResultConversion &&
6891 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6892 return;
6893
Richard Smith089c3162013-09-21 21:55:46 +00006894 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6895 // operator is only a candidate if its return type is the target type or
6896 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006897 if (Conversion->isExplicit() &&
6898 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006899 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006900 return;
6901
Douglas Gregor27381f32009-11-23 12:27:39 +00006902 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006903 EnterExpressionEvaluationContext Unevaluated(
6904 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006905
Douglas Gregora1f013e2008-11-07 22:36:19 +00006906 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006907 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006908 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006909 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006910 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006911 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006912 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006913 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006914 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006915 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006916 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006917
Douglas Gregor6affc782010-08-19 15:37:02 +00006918 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919 // For conversion functions, the function is considered to be a member of
6920 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006921 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006922 //
6923 // Determine the implicit conversion sequence for the implicit
6924 // object parameter.
6925 QualType ImplicitParamType = From->getType();
6926 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6927 ImplicitParamType = FromPtrType->getPointeeType();
6928 CXXRecordDecl *ConversionContext
6929 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930
Richard Smith0f59cb32015-12-18 21:45:41 +00006931 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6932 *this, CandidateSet.getLocation(), From->getType(),
6933 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
John McCall0d1da222010-01-12 00:44:57 +00006935 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006936 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006937 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006938 return;
6939 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006940
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006941 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006942 // derived to base as such conversions are given Conversion Rank. They only
6943 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6944 QualType FromCanon
6945 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6946 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006947 if (FromCanon == ToCanon ||
6948 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006949 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006950 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006951 return;
6952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
Douglas Gregora1f013e2008-11-07 22:36:19 +00006954 // To determine what the conversion from the result of calling the
6955 // conversion function to the type we're eventually trying to
6956 // convert to (ToType), we need to synthesize a call to the
6957 // conversion function and attempt copy initialization from it. This
6958 // makes sure that we get the right semantics with respect to
6959 // lvalues/rvalues and the type. Fortunately, we can allocate this
6960 // call on the stack and we don't need its arguments to be
6961 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006962 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006963 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006964 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6965 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006966 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006967 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006968
Richard Smith48d24642011-07-13 22:53:21 +00006969 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006970 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006971 Candidate.Viable = false;
6972 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6973 return;
6974 }
6975
Richard Smith48d24642011-07-13 22:53:21 +00006976 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006977
Mike Stump11289f42009-09-09 15:08:12 +00006978 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006979 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6980 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006981 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006982 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006983 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006984 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006985 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006986 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006987 /*InOverloadResolution=*/false,
6988 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006989
John McCall0d1da222010-01-12 00:44:57 +00006990 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006991 case ImplicitConversionSequence::StandardConversion:
6992 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006994 // C++ [over.ics.user]p3:
6995 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006997 // shall have exact match rank.
6998 if (Conversion->getPrimaryTemplate() &&
6999 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7000 Candidate.Viable = false;
7001 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007002 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007004
Douglas Gregorcba72b12011-01-21 05:18:22 +00007005 // C++0x [dcl.init.ref]p5:
7006 // In the second case, if the reference is an rvalue reference and
7007 // the second standard conversion sequence of the user-defined
7008 // conversion sequence includes an lvalue-to-rvalue conversion, the
7009 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00007011 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7012 Candidate.Viable = false;
7013 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007014 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00007015 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007016 break;
7017
7018 case ImplicitConversionSequence::BadConversion:
7019 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00007020 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007021 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00007022
7023 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007024 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00007025 "Can only end up with a standard conversion sequence or failure");
7026 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007027
Craig Topper5fc8fc22014-08-27 06:28:36 +00007028 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007029 Candidate.Viable = false;
7030 Candidate.FailureKind = ovl_fail_enable_if;
7031 Candidate.DeductionFailure.Data = FailedAttr;
7032 return;
7033 }
Erich Keane281d20b2018-01-08 21:34:17 +00007034
Erich Keane3efe0022018-07-20 14:13:28 +00007035 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00007036 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7037 Candidate.Viable = false;
7038 Candidate.FailureKind = ovl_non_default_multiversion_function;
7039 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007040}
7041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007042/// Adds a conversion function template specialization
Douglas Gregor05155d82009-08-21 23:19:43 +00007043/// candidate to the overload set, using template argument deduction
7044/// to deduce the template arguments of the conversion function
7045/// template from the type that we are converting to (C++
7046/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00007047void
Douglas Gregor05155d82009-08-21 23:19:43 +00007048Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00007049 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007050 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00007051 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00007052 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00007053 bool AllowObjCConversionOnExplicit,
7054 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007055 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7056 "Only conversion function templates permitted here");
7057
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007058 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7059 return;
7060
Craig Toppere6706e42012-09-19 02:26:47 +00007061 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007062 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00007063 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00007064 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00007065 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00007066 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007067 Candidate.FoundDecl = FoundDecl;
7068 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7069 Candidate.Viable = false;
7070 Candidate.FailureKind = ovl_fail_bad_deduction;
7071 Candidate.IsSurrogate = false;
7072 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00007073 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007074 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007075 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00007076 return;
7077 }
Mike Stump11289f42009-09-09 15:08:12 +00007078
Douglas Gregor05155d82009-08-21 23:19:43 +00007079 // Add the conversion function template specialization produced by
7080 // template argument deduction as a candidate.
7081 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007082 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007083 CandidateSet, AllowObjCConversionOnExplicit,
7084 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007085}
7086
Douglas Gregorab7897a2008-11-19 22:57:39 +00007087/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7088/// converts the given @c Object to a function pointer via the
7089/// conversion function @c Conversion, and then attempts to call it
7090/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7091/// the type of function that we'll eventually be calling.
7092void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007093 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007094 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007095 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007096 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007097 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007098 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007099 if (!CandidateSet.isNewCandidate(Conversion))
7100 return;
7101
Douglas Gregor27381f32009-11-23 12:27:39 +00007102 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007103 EnterExpressionEvaluationContext Unevaluated(
7104 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007105
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007106 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007107 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007108 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007109 Candidate.Surrogate = Conversion;
7110 Candidate.Viable = true;
7111 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007112 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007113 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007114
7115 // Determine the implicit conversion sequence for the implicit
7116 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007117 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7118 *this, CandidateSet.getLocation(), Object->getType(),
7119 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007120 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007121 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007122 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007123 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007124 return;
7125 }
7126
7127 // The first conversion is actually a user-defined conversion whose
7128 // first conversion is ObjectInit's standard conversion (which is
7129 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007130 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007131 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007132 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007133 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007134 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007135 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007136 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007137 = Candidate.Conversions[0].UserDefined.Before;
7138 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7139
Mike Stump11289f42009-09-09 15:08:12 +00007140 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007141 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007142
7143 // (C++ 13.3.2p2): A candidate function having fewer than m
7144 // parameters is viable only if it has an ellipsis in its parameter
7145 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007146 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007147 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007148 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007149 return;
7150 }
7151
7152 // Function types don't have any default arguments, so just check if
7153 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007154 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007155 // Not enough arguments.
7156 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007157 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007158 return;
7159 }
7160
7161 // Determine the implicit conversion sequences for each of the
7162 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007163 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007164 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007165 // (C++ 13.3.2p3): for F to be a viable function, there shall
7166 // exist for each argument an implicit conversion sequence
7167 // (13.3.3.1) that converts that argument to the corresponding
7168 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007169 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007170 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007171 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007172 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007173 /*InOverloadResolution=*/false,
7174 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007175 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007176 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007177 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007178 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007179 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007180 }
7181 } else {
7182 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7183 // argument for which there is no corresponding parameter is
7184 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007185 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007186 }
7187 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007188
Craig Topper5fc8fc22014-08-27 06:28:36 +00007189 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007190 Candidate.Viable = false;
7191 Candidate.FailureKind = ovl_fail_enable_if;
7192 Candidate.DeductionFailure.Data = FailedAttr;
7193 return;
7194 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007195}
7196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007197/// Add overload candidates for overloaded operators that are
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007198/// member functions.
7199///
7200/// Add the overloaded operator candidates that are member functions
7201/// for the operator Op that was used in an operator expression such
7202/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7203/// CandidateSet will store the added overload candidates. (C++
7204/// [over.match.oper]).
7205void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7206 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007207 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007208 OverloadCandidateSet& CandidateSet,
7209 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007210 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7211
7212 // C++ [over.match.oper]p3:
7213 // For a unary operator @ with an operand of a type whose
7214 // cv-unqualified version is T1, and for a binary operator @ with
7215 // a left operand of a type whose cv-unqualified version is T1 and
7216 // a right operand of a type whose cv-unqualified version is T2,
7217 // three sets of candidate functions, designated member
7218 // candidates, non-member candidates and built-in candidates, are
7219 // constructed as follows:
7220 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007221
Richard Smith0feaf0c2013-04-20 12:41:22 +00007222 // -- If T1 is a complete class type or a class currently being
7223 // defined, the set of member candidates is the result of the
7224 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7225 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007226 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007227 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007228 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007229 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007230 // If the type is neither complete nor being defined, bail out now.
7231 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007232 return;
Mike Stump11289f42009-09-09 15:08:12 +00007233
John McCall27b18f82009-11-17 02:14:36 +00007234 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7235 LookupQualifiedName(Operators, T1Rec->getDecl());
7236 Operators.suppressDiagnostics();
7237
Mike Stump11289f42009-09-09 15:08:12 +00007238 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007239 OperEnd = Operators.end();
7240 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007241 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007242 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007243 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007244 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007245 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007246}
7247
Douglas Gregora11693b2008-11-12 17:17:38 +00007248/// AddBuiltinCandidate - Add a candidate for a built-in
7249/// operator. ResultTy and ParamTys are the result and parameter types
7250/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007251/// arguments being passed to the candidate. IsAssignmentOperator
7252/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007253/// operator. NumContextualBoolArguments is the number of arguments
7254/// (at the beginning of the argument list) that will be contextually
7255/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007256void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007257 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007258 bool IsAssignmentOperator,
7259 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007260 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007261 EnterExpressionEvaluationContext Unevaluated(
7262 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007263
Douglas Gregora11693b2008-11-12 17:17:38 +00007264 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007265 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007266 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7267 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007268 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007269 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007270 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007271
7272 // Determine the implicit conversion sequences for each of the
7273 // arguments.
7274 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007275 Candidate.ExplicitCallArguments = Args.size();
7276 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007277 // C++ [over.match.oper]p4:
7278 // For the built-in assignment operators, conversions of the
7279 // left operand are restricted as follows:
7280 // -- no temporaries are introduced to hold the left operand, and
7281 // -- no user-defined conversions are applied to the left
7282 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007283 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007284 //
7285 // We block these conversions by turning off user-defined
7286 // conversions, since that is the only way that initialization of
7287 // a reference to a non-class type can occur from something that
7288 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007289 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007290 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007291 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007292 Candidate.Conversions[ArgIdx]
7293 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007294 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007295 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007296 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007297 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007298 /*InOverloadResolution=*/false,
7299 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007300 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007301 }
John McCall0d1da222010-01-12 00:44:57 +00007302 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007303 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007304 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007305 break;
7306 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007307 }
7308}
7309
Craig Toppercd7b0332013-07-01 06:29:40 +00007310namespace {
7311
Douglas Gregora11693b2008-11-12 17:17:38 +00007312/// BuiltinCandidateTypeSet - A set of types that will be used for the
7313/// candidate operator functions for built-in operators (C++
7314/// [over.built]). The types are separated into pointer types and
7315/// enumeration types.
7316class BuiltinCandidateTypeSet {
7317 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007318 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7319 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007320
7321 /// PointerTypes - The set of pointer types that will be used in the
7322 /// built-in candidates.
7323 TypeSet PointerTypes;
7324
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007325 /// MemberPointerTypes - The set of member pointer types that will be
7326 /// used in the built-in candidates.
7327 TypeSet MemberPointerTypes;
7328
Douglas Gregora11693b2008-11-12 17:17:38 +00007329 /// EnumerationTypes - The set of enumeration types that will be
7330 /// used in the built-in candidates.
7331 TypeSet EnumerationTypes;
7332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007333 /// The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007334 /// candidates.
7335 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007337 /// A flag indicating non-record types are viable candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007338 bool HasNonRecordTypes;
7339
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007340 /// A flag indicating whether either arithmetic or enumeration types
Chandler Carruth00a38332010-12-13 01:44:01 +00007341 /// were present in the candidate set.
7342 bool HasArithmeticOrEnumeralTypes;
7343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007344 /// A flag indicating whether the nullptr type was present in the
Douglas Gregor80af3132011-05-21 23:15:46 +00007345 /// candidate set.
7346 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007347
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007348 /// Sema - The semantic analysis instance where we are building the
7349 /// candidate type set.
7350 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007351
Douglas Gregora11693b2008-11-12 17:17:38 +00007352 /// Context - The AST context in which we will build the type sets.
7353 ASTContext &Context;
7354
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007355 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7356 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007357 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007358
7359public:
7360 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007361 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007362
Mike Stump11289f42009-09-09 15:08:12 +00007363 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007364 : HasNonRecordTypes(false),
7365 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007366 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007367 SemaRef(SemaRef),
7368 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007369
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007371 SourceLocation Loc,
7372 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007373 bool AllowExplicitConversions,
7374 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007375
7376 /// pointer_begin - First pointer type found;
7377 iterator pointer_begin() { return PointerTypes.begin(); }
7378
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007379 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007380 iterator pointer_end() { return PointerTypes.end(); }
7381
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007382 /// member_pointer_begin - First member pointer type found;
7383 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7384
7385 /// member_pointer_end - Past the last member pointer type found;
7386 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7387
Douglas Gregora11693b2008-11-12 17:17:38 +00007388 /// enumeration_begin - First enumeration type found;
7389 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7390
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007391 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007392 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007394 iterator vector_begin() { return VectorTypes.begin(); }
7395 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007396
7397 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7398 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007399 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007400};
7401
Craig Toppercd7b0332013-07-01 06:29:40 +00007402} // end anonymous namespace
7403
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007404/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007405/// the set of pointer types along with any more-qualified variants of
7406/// that type. For example, if @p Ty is "int const *", this routine
7407/// will add "int const *", "int const volatile *", "int const
7408/// restrict *", and "int const volatile restrict *" to the set of
7409/// pointer types. Returns true if the add of @p Ty itself succeeded,
7410/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007411///
7412/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007413bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007414BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7415 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007416
Douglas Gregora11693b2008-11-12 17:17:38 +00007417 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007418 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007419 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007420
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007421 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007422 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007423 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007424 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007425 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7426 PointeeTy = PTy->getPointeeType();
7427 buildObjCPtr = true;
7428 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007429 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007430 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007431
Sebastian Redl4990a632009-11-18 20:39:26 +00007432 // Don't add qualified variants of arrays. For one, they're not allowed
7433 // (the qualifier would sink to the element type), and for another, the
7434 // only overload situation where it matters is subscript or pointer +- int,
7435 // and those shouldn't have qualifier variants anyway.
7436 if (PointeeTy->isArrayType())
7437 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007438
John McCall8ccfcb52009-09-24 19:53:00 +00007439 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007440 bool hasVolatile = VisibleQuals.hasVolatile();
7441 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442
John McCall8ccfcb52009-09-24 19:53:00 +00007443 // Iterate through all strict supersets of BaseCVR.
7444 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7445 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007446 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007447 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007448
Douglas Gregor5bee2582012-06-04 00:15:09 +00007449 // Skip over restrict if no restrict found anywhere in the types, or if
7450 // the type cannot be restrict-qualified.
7451 if ((CVR & Qualifiers::Restrict) &&
7452 (!hasRestrict ||
7453 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7454 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007455
Douglas Gregor5bee2582012-06-04 00:15:09 +00007456 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007457 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007458
Douglas Gregor5bee2582012-06-04 00:15:09 +00007459 // Build qualified pointer type.
7460 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007461 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007462 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007463 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007464 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007465
Douglas Gregor5bee2582012-06-04 00:15:09 +00007466 // Insert qualified pointer type.
7467 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007468 }
7469
7470 return true;
7471}
7472
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007473/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7474/// to the set of pointer types along with any more-qualified variants of
7475/// that type. For example, if @p Ty is "int const *", this routine
7476/// will add "int const *", "int const volatile *", "int const
7477/// restrict *", and "int const volatile restrict *" to the set of
7478/// pointer types. Returns true if the add of @p Ty itself succeeded,
7479/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007480///
7481/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007482bool
7483BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7484 QualType Ty) {
7485 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007486 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007487 return false;
7488
John McCall8ccfcb52009-09-24 19:53:00 +00007489 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7490 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007491
John McCall8ccfcb52009-09-24 19:53:00 +00007492 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007493 // Don't add qualified variants of arrays. For one, they're not allowed
7494 // (the qualifier would sink to the element type), and for another, the
7495 // only overload situation where it matters is subscript or pointer +- int,
7496 // and those shouldn't have qualifier variants anyway.
7497 if (PointeeTy->isArrayType())
7498 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007499 const Type *ClassTy = PointerTy->getClass();
7500
7501 // Iterate through all strict supersets of the pointee type's CVR
7502 // qualifiers.
7503 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7504 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7505 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506
John McCall8ccfcb52009-09-24 19:53:00 +00007507 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007508 MemberPointerTypes.insert(
7509 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007510 }
7511
7512 return true;
7513}
7514
Douglas Gregora11693b2008-11-12 17:17:38 +00007515/// AddTypesConvertedFrom - Add each of the types to which the type @p
7516/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007517/// primarily interested in pointer types and enumeration types. We also
7518/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007519/// AllowUserConversions is true if we should look at the conversion
7520/// functions of a class type, and AllowExplicitConversions if we
7521/// should also include the explicit conversion functions of a class
7522/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007523void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007524BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007525 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007526 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007527 bool AllowExplicitConversions,
7528 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007529 // Only deal with canonical types.
7530 Ty = Context.getCanonicalType(Ty);
7531
7532 // Look through reference types; they aren't part of the type of an
7533 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007534 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007535 Ty = RefTy->getPointeeType();
7536
John McCall33ddac02011-01-19 10:06:00 +00007537 // If we're dealing with an array type, decay to the pointer.
7538 if (Ty->isArrayType())
7539 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7540
7541 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007542 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007543
Chandler Carruth00a38332010-12-13 01:44:01 +00007544 // Flag if we ever add a non-record type.
7545 const RecordType *TyRec = Ty->getAs<RecordType>();
7546 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7547
Chandler Carruth00a38332010-12-13 01:44:01 +00007548 // Flag if we encounter an arithmetic type.
7549 HasArithmeticOrEnumeralTypes =
7550 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7551
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007552 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7553 PointerTypes.insert(Ty);
7554 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007555 // Insert our type, and its more-qualified variants, into the set
7556 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007557 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007558 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007559 } else if (Ty->isMemberPointerType()) {
7560 // Member pointers are far easier, since the pointee can't be converted.
7561 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7562 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007563 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007564 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007565 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007566 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007567 // We treat vector types as arithmetic types in many contexts as an
7568 // extension.
7569 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007570 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007571 } else if (Ty->isNullPtrType()) {
7572 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007573 } else if (AllowUserConversions && TyRec) {
7574 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007575 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007576 return;
Mike Stump11289f42009-09-09 15:08:12 +00007577
Chandler Carruth00a38332010-12-13 01:44:01 +00007578 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007579 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007580 if (isa<UsingShadowDecl>(D))
7581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007582
Chandler Carruth00a38332010-12-13 01:44:01 +00007583 // Skip conversion function templates; they don't tell us anything
7584 // about which builtin types we can convert to.
7585 if (isa<FunctionTemplateDecl>(D))
7586 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007587
Chandler Carruth00a38332010-12-13 01:44:01 +00007588 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7589 if (AllowExplicitConversions || !Conv->isExplicit()) {
7590 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7591 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007592 }
7593 }
7594 }
7595}
7596
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007597/// Helper function for AddBuiltinOperatorCandidates() that adds
Douglas Gregor84605ae2009-08-24 13:43:27 +00007598/// the volatile- and non-volatile-qualified assignment operators for the
7599/// given type to the candidate set.
7600static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7601 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007602 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007603 OverloadCandidateSet &CandidateSet) {
7604 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007605
Douglas Gregor84605ae2009-08-24 13:43:27 +00007606 // T& operator=(T&, T)
7607 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7608 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007609 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007610 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007611
Douglas Gregor84605ae2009-08-24 13:43:27 +00007612 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7613 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007614 ParamTypes[0]
7615 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007616 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007617 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007618 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007619 }
7620}
Mike Stump11289f42009-09-09 15:08:12 +00007621
Sebastian Redl1054fae2009-10-25 17:03:50 +00007622/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7623/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007624static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7625 Qualifiers VRQuals;
7626 const RecordType *TyRec;
7627 if (const MemberPointerType *RHSMPType =
7628 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007629 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007630 else
7631 TyRec = ArgExpr->getType()->getAs<RecordType>();
7632 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007633 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007634 VRQuals.addVolatile();
7635 VRQuals.addRestrict();
7636 return VRQuals;
7637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007638
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007639 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007640 if (!ClassDecl->hasDefinition())
7641 return VRQuals;
7642
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007643 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007644 if (isa<UsingShadowDecl>(D))
7645 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7646 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007647 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7648 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7649 CanTy = ResTypeRef->getPointeeType();
7650 // Need to go down the pointer/mempointer chain and add qualifiers
7651 // as see them.
7652 bool done = false;
7653 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007654 if (CanTy.isRestrictQualified())
7655 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007656 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7657 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007658 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007659 CanTy->getAs<MemberPointerType>())
7660 CanTy = ResTypeMPtr->getPointeeType();
7661 else
7662 done = true;
7663 if (CanTy.isVolatileQualified())
7664 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007665 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7666 return VRQuals;
7667 }
7668 }
7669 }
7670 return VRQuals;
7671}
John McCall52872982010-11-13 05:51:15 +00007672
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007673namespace {
John McCall52872982010-11-13 05:51:15 +00007674
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007675/// Helper class to manage the addition of builtin operator overload
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007676/// candidates. It provides shared state and utility methods used throughout
7677/// the process, as well as a helper method to add each group of builtin
7678/// operator overloads from the standard to a candidate set.
7679class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007680 // Common instance state available to all overload candidate addition methods.
7681 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007682 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007683 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007684 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007685 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007686 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687
Hans Wennborg82371412017-11-15 17:11:53 +00007688 static constexpr int ArithmeticTypesCap = 24;
7689 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7690
7691 // Define some indices used to iterate over the arithemetic types in
7692 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
John McCall52872982010-11-13 05:51:15 +00007693 // types are that preserved by promotion (C++ [over.built]p2).
Hans Wennborg82371412017-11-15 17:11:53 +00007694 unsigned FirstIntegralType,
7695 LastIntegralType;
7696 unsigned FirstPromotedIntegralType,
7697 LastPromotedIntegralType;
7698 unsigned FirstPromotedArithmeticType,
7699 LastPromotedArithmeticType;
7700 unsigned NumArithmeticTypes;
John McCall52872982010-11-13 05:51:15 +00007701
Hans Wennborg82371412017-11-15 17:11:53 +00007702 void InitArithmeticTypes() {
7703 // Start of promoted types.
7704 FirstPromotedArithmeticType = 0;
7705 ArithmeticTypes.push_back(S.Context.FloatTy);
7706 ArithmeticTypes.push_back(S.Context.DoubleTy);
7707 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7708 if (S.Context.getTargetInfo().hasFloat128Type())
7709 ArithmeticTypes.push_back(S.Context.Float128Ty);
John McCall52872982010-11-13 05:51:15 +00007710
Hans Wennborg82371412017-11-15 17:11:53 +00007711 // Start of integral types.
7712 FirstIntegralType = ArithmeticTypes.size();
7713 FirstPromotedIntegralType = ArithmeticTypes.size();
7714 ArithmeticTypes.push_back(S.Context.IntTy);
7715 ArithmeticTypes.push_back(S.Context.LongTy);
7716 ArithmeticTypes.push_back(S.Context.LongLongTy);
7717 if (S.Context.getTargetInfo().hasInt128Type())
7718 ArithmeticTypes.push_back(S.Context.Int128Ty);
7719 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7720 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7721 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7722 if (S.Context.getTargetInfo().hasInt128Type())
7723 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7724 LastPromotedIntegralType = ArithmeticTypes.size();
7725 LastPromotedArithmeticType = ArithmeticTypes.size();
7726 // End of promoted types.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007727
Hans Wennborg82371412017-11-15 17:11:53 +00007728 ArithmeticTypes.push_back(S.Context.BoolTy);
7729 ArithmeticTypes.push_back(S.Context.CharTy);
7730 ArithmeticTypes.push_back(S.Context.WCharTy);
Richard Smith3a8244d2018-05-01 05:02:45 +00007731 if (S.Context.getLangOpts().Char8)
7732 ArithmeticTypes.push_back(S.Context.Char8Ty);
Hans Wennborg82371412017-11-15 17:11:53 +00007733 ArithmeticTypes.push_back(S.Context.Char16Ty);
7734 ArithmeticTypes.push_back(S.Context.Char32Ty);
7735 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7736 ArithmeticTypes.push_back(S.Context.ShortTy);
7737 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7738 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7739 LastIntegralType = ArithmeticTypes.size();
7740 NumArithmeticTypes = ArithmeticTypes.size();
7741 // End of integral types.
7742 // FIXME: What about complex? What about half?
7743
7744 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7745 "Enough inline storage for all arithmetic types.");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007746 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007748 /// Helper method to factor out the common pattern of adding overloads
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007749 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007751 bool HasVolatile,
7752 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 QualType ParamTypes[2] = {
7754 S.Context.getLValueReferenceType(CandidateTy),
7755 S.Context.IntTy
7756 };
7757
7758 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007759 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007760
7761 // Use a heuristic to reduce number of builtin candidates in the set:
7762 // add volatile version only if there are conversions to a volatile type.
7763 if (HasVolatile) {
7764 ParamTypes[0] =
7765 S.Context.getLValueReferenceType(
7766 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007767 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007768 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007769
Douglas Gregor5bee2582012-06-04 00:15:09 +00007770 // Add restrict version only if there are conversions to a restrict type
7771 // and our candidate type is a non-restrict-qualified pointer.
7772 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7773 !CandidateTy.isRestrictQualified()) {
7774 ParamTypes[0]
7775 = S.Context.getLValueReferenceType(
7776 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007777 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007778
Douglas Gregor5bee2582012-06-04 00:15:09 +00007779 if (HasVolatile) {
7780 ParamTypes[0]
7781 = S.Context.getLValueReferenceType(
7782 S.Context.getCVRQualifiedType(CandidateTy,
7783 (Qualifiers::Volatile |
7784 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007785 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007786 }
7787 }
7788
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007789 }
7790
7791public:
7792 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007793 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007794 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007795 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007796 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007798 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007800 HasArithmeticOrEnumeralCandidateType(
7801 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007802 CandidateTypes(CandidateTypes),
7803 CandidateSet(CandidateSet) {
Hans Wennborg82371412017-11-15 17:11:53 +00007804
7805 InitArithmeticTypes();
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007806 }
7807
Jan Korous536d2e32018-04-18 13:38:39 +00007808 // Increment is deprecated for bool since C++17.
7809 //
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 // C++ [over.built]p3:
7811 //
Jan Korous536d2e32018-04-18 13:38:39 +00007812 // For every pair (T, VQ), where T is an arithmetic type other
7813 // than bool, and VQ is either volatile or empty, there exist
7814 // candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 //
7816 // VQ T& operator++(VQ T&);
7817 // T operator++(VQ T&, int);
7818 //
7819 // C++ [over.built]p4:
7820 //
7821 // 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
7824 //
7825 // VQ T& operator--(VQ T&);
7826 // T operator--(VQ T&, int);
7827 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007828 if (!HasArithmeticOrEnumeralCandidateType)
7829 return;
7830
Jan Korousd74ebe22018-04-11 13:36:29 +00007831 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7832 const auto TypeOfT = ArithmeticTypes[Arith];
Jan Korous536d2e32018-04-18 13:38:39 +00007833 if (TypeOfT == S.Context.BoolTy) {
7834 if (Op == OO_MinusMinus)
7835 continue;
7836 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7837 continue;
7838 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007839 addPlusPlusMinusMinusStyleOverloads(
Jan Korousd74ebe22018-04-11 13:36:29 +00007840 TypeOfT,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007841 VisibleTypeConversionsQuals.hasVolatile(),
7842 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007843 }
7844 }
7845
7846 // C++ [over.built]p5:
7847 //
7848 // For every pair (T, VQ), where T is a cv-qualified or
7849 // cv-unqualified object type, and VQ is either volatile or
7850 // empty, there exist candidate operator functions of the form
7851 //
7852 // T*VQ& operator++(T*VQ&);
7853 // T*VQ& operator--(T*VQ&);
7854 // T* operator++(T*VQ&, int);
7855 // T* operator--(T*VQ&, int);
7856 void addPlusPlusMinusMinusPointerOverloads() {
7857 for (BuiltinCandidateTypeSet::iterator
7858 Ptr = CandidateTypes[0].pointer_begin(),
7859 PtrEnd = CandidateTypes[0].pointer_end();
7860 Ptr != PtrEnd; ++Ptr) {
7861 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007862 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007863 continue;
7864
7865 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007866 (!(*Ptr).isVolatileQualified() &&
7867 VisibleTypeConversionsQuals.hasVolatile()),
7868 (!(*Ptr).isRestrictQualified() &&
7869 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007870 }
7871 }
7872
7873 // C++ [over.built]p6:
7874 // For every cv-qualified or cv-unqualified object type T, there
7875 // exist candidate operator functions of the form
7876 //
7877 // T& operator*(T*);
7878 //
7879 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007881 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 // T& operator*(T*);
7883 void addUnaryStarPointerOverloads() {
7884 for (BuiltinCandidateTypeSet::iterator
7885 Ptr = CandidateTypes[0].pointer_begin(),
7886 PtrEnd = CandidateTypes[0].pointer_end();
7887 Ptr != PtrEnd; ++Ptr) {
7888 QualType ParamTy = *Ptr;
7889 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007890 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7891 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Douglas Gregor02824322011-01-26 19:30:28 +00007893 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7894 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7895 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007896
George Burgess IVc07c3892017-06-08 18:19:25 +00007897 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007898 }
7899 }
7900
7901 // C++ [over.built]p9:
7902 // For every promoted arithmetic type T, there exist candidate
7903 // operator functions of the form
7904 //
7905 // T operator+(T);
7906 // T operator-(T);
7907 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007908 if (!HasArithmeticOrEnumeralCandidateType)
7909 return;
7910
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007911 for (unsigned Arith = FirstPromotedArithmeticType;
7912 Arith < LastPromotedArithmeticType; ++Arith) {
Hans Wennborg82371412017-11-15 17:11:53 +00007913 QualType ArithTy = ArithmeticTypes[Arith];
George Burgess IVc07c3892017-06-08 18:19:25 +00007914 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007915 }
7916
7917 // Extension: We also add these operators for vector types.
7918 for (BuiltinCandidateTypeSet::iterator
7919 Vec = CandidateTypes[0].vector_begin(),
7920 VecEnd = CandidateTypes[0].vector_end();
7921 Vec != VecEnd; ++Vec) {
7922 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007923 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 }
7925 }
7926
7927 // C++ [over.built]p8:
7928 // For every type T, there exist candidate operator functions of
7929 // the form
7930 //
7931 // T* operator+(T*);
7932 void addUnaryPlusPointerOverloads() {
7933 for (BuiltinCandidateTypeSet::iterator
7934 Ptr = CandidateTypes[0].pointer_begin(),
7935 PtrEnd = CandidateTypes[0].pointer_end();
7936 Ptr != PtrEnd; ++Ptr) {
7937 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007938 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 }
7940 }
7941
7942 // C++ [over.built]p10:
7943 // For every promoted integral type T, there exist candidate
7944 // operator functions of the form
7945 //
7946 // T operator~(T);
7947 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007948 if (!HasArithmeticOrEnumeralCandidateType)
7949 return;
7950
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 for (unsigned Int = FirstPromotedIntegralType;
7952 Int < LastPromotedIntegralType; ++Int) {
Hans Wennborg82371412017-11-15 17:11:53 +00007953 QualType IntTy = ArithmeticTypes[Int];
George Burgess IVc07c3892017-06-08 18:19:25 +00007954 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007955 }
7956
7957 // Extension: We also add this operator for vector types.
7958 for (BuiltinCandidateTypeSet::iterator
7959 Vec = CandidateTypes[0].vector_begin(),
7960 VecEnd = CandidateTypes[0].vector_end();
7961 Vec != VecEnd; ++Vec) {
7962 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007963 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007964 }
7965 }
7966
7967 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007968 // For every pointer to member type T or type std::nullptr_t, there
7969 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007970 //
7971 // bool operator==(T,T);
7972 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007973 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007974 /// Set of (canonical) types that we've already handled.
7975 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7976
Richard Smithe54c3072013-05-05 15:51:06 +00007977 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007978 for (BuiltinCandidateTypeSet::iterator
7979 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7980 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7981 MemPtr != MemPtrEnd;
7982 ++MemPtr) {
7983 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007984 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007985 continue;
7986
7987 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007988 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007990
7991 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7992 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7993 if (AddedTypes.insert(NullPtrTy).second) {
7994 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007995 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007996 }
7997 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007998 }
7999 }
8000
8001 // C++ [over.built]p15:
8002 //
Richard Smith5e9746f2016-10-21 22:00:42 +00008003 // For every T, where T is an enumeration type or a pointer type,
8004 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008005 //
8006 // bool operator<(T, T);
8007 // bool operator>(T, T);
8008 // bool operator<=(T, T);
8009 // bool operator>=(T, T);
8010 // bool operator==(T, T);
8011 // bool operator!=(T, T);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008012 // R operator<=>(T, T)
8013 void addGenericBinaryPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00008014 // C++ [over.match.oper]p3:
8015 // [...]the built-in candidates include all of the candidate operator
8016 // functions defined in 13.6 that, compared to the given operator, [...]
8017 // do not have the same parameter-type-list as any non-template non-member
8018 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008019 //
Eli Friedman14f082b2012-09-18 21:52:24 +00008020 // Note that in practice, this only affects enumeration types because there
8021 // aren't any built-in candidates of record type, and a user-defined operator
8022 // must have an operand of record or enumeration type. Also, the only other
8023 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008024 // cannot be overloaded for enumeration types, so this is the only place
8025 // where we must suppress candidates like this.
8026 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8027 UserDefinedBinaryOperators;
8028
Richard Smithe54c3072013-05-05 15:51:06 +00008029 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008030 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8031 CandidateTypes[ArgIdx].enumeration_end()) {
8032 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8033 CEnd = CandidateSet.end();
8034 C != CEnd; ++C) {
8035 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8036 continue;
8037
Eli Friedman14f082b2012-09-18 21:52:24 +00008038 if (C->Function->isFunctionTemplateSpecialization())
8039 continue;
8040
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008041 QualType FirstParamType =
8042 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8043 QualType SecondParamType =
8044 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8045
8046 // Skip if either parameter isn't of enumeral type.
8047 if (!FirstParamType->isEnumeralType() ||
8048 !SecondParamType->isEnumeralType())
8049 continue;
8050
8051 // Add this operator to the set of known user-defined operators.
8052 UserDefinedBinaryOperators.insert(
8053 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8054 S.Context.getCanonicalType(SecondParamType)));
8055 }
8056 }
8057 }
8058
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 /// Set of (canonical) types that we've already handled.
8060 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8061
Richard Smithe54c3072013-05-05 15:51:06 +00008062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008063 for (BuiltinCandidateTypeSet::iterator
8064 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8065 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8066 Ptr != PtrEnd; ++Ptr) {
8067 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008068 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 continue;
8070
8071 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008073 }
8074 for (BuiltinCandidateTypeSet::iterator
8075 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8076 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8077 Enum != EnumEnd; ++Enum) {
8078 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8079
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008080 // Don't add the same builtin candidate twice, or if a user defined
8081 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008082 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008083 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8084 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008085 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008087 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008088 }
8089 }
8090 }
8091
8092 // C++ [over.built]p13:
8093 //
8094 // For every cv-qualified or cv-unqualified object type T
8095 // there exist candidate operator functions of the form
8096 //
8097 // T* operator+(T*, ptrdiff_t);
8098 // T& operator[](T*, ptrdiff_t); [BELOW]
8099 // T* operator-(T*, ptrdiff_t);
8100 // T* operator+(ptrdiff_t, T*);
8101 // T& operator[](ptrdiff_t, T*); [BELOW]
8102 //
8103 // C++ [over.built]p14:
8104 //
8105 // For every T, where T is a pointer to object type, there
8106 // exist candidate operator functions of the form
8107 //
8108 // ptrdiff_t operator-(T, T);
8109 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8110 /// Set of (canonical) types that we've already handled.
8111 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8112
8113 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008114 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008115 S.Context.getPointerDiffType(),
8116 S.Context.getPointerDiffType(),
8117 };
8118 for (BuiltinCandidateTypeSet::iterator
8119 Ptr = CandidateTypes[Arg].pointer_begin(),
8120 PtrEnd = CandidateTypes[Arg].pointer_end();
8121 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008122 QualType PointeeTy = (*Ptr)->getPointeeType();
8123 if (!PointeeTy->isObjectType())
8124 continue;
8125
Eric Christopher9207a522015-08-21 16:24:01 +00008126 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008127 if (Arg == 0 || Op == OO_Plus) {
8128 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8129 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008130 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008131 }
8132 if (Op == OO_Minus) {
8133 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008134 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008135 continue;
8136
8137 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 }
8140 }
8141 }
8142 }
8143
8144 // C++ [over.built]p12:
8145 //
8146 // For every pair of promoted arithmetic types L and R, there
8147 // exist candidate operator functions of the form
8148 //
8149 // LR operator*(L, R);
8150 // LR operator/(L, R);
8151 // LR operator+(L, R);
8152 // LR operator-(L, R);
8153 // bool operator<(L, R);
8154 // bool operator>(L, R);
8155 // bool operator<=(L, R);
8156 // bool operator>=(L, R);
8157 // bool operator==(L, R);
8158 // bool operator!=(L, R);
8159 //
8160 // where LR is the result of the usual arithmetic conversions
8161 // between types L and R.
8162 //
8163 // C++ [over.built]p24:
8164 //
8165 // For every pair of promoted arithmetic types L and R, there exist
8166 // candidate operator functions of the form
8167 //
8168 // LR operator?(bool, L, R);
8169 //
8170 // where LR is the result of the usual arithmetic conversions
8171 // between types L and R.
8172 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008173 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008174 if (!HasArithmeticOrEnumeralCandidateType)
8175 return;
8176
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008177 for (unsigned Left = FirstPromotedArithmeticType;
8178 Left < LastPromotedArithmeticType; ++Left) {
8179 for (unsigned Right = FirstPromotedArithmeticType;
8180 Right < LastPromotedArithmeticType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008181 QualType LandR[2] = { ArithmeticTypes[Left],
8182 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008183 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008184 }
8185 }
8186
8187 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8188 // conditional operator for vector types.
8189 for (BuiltinCandidateTypeSet::iterator
8190 Vec1 = CandidateTypes[0].vector_begin(),
8191 Vec1End = CandidateTypes[0].vector_end();
8192 Vec1 != Vec1End; ++Vec1) {
8193 for (BuiltinCandidateTypeSet::iterator
8194 Vec2 = CandidateTypes[1].vector_begin(),
8195 Vec2End = CandidateTypes[1].vector_end();
8196 Vec2 != Vec2End; ++Vec2) {
8197 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008198 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008199 }
8200 }
8201 }
8202
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008203 // C++2a [over.built]p14:
8204 //
8205 // For every integral type T there exists a candidate operator function
8206 // of the form
8207 //
8208 // std::strong_ordering operator<=>(T, T)
8209 //
8210 // C++2a [over.built]p15:
8211 //
8212 // For every pair of floating-point types L and R, there exists a candidate
8213 // operator function of the form
8214 //
8215 // std::partial_ordering operator<=>(L, R);
8216 //
8217 // FIXME: The current specification for integral types doesn't play nice with
8218 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8219 // comparisons. Under the current spec this can lead to ambiguity during
8220 // overload resolution. For example:
8221 //
8222 // enum A : int {a};
8223 // auto x = (a <=> (long)42);
8224 //
8225 // error: call is ambiguous for arguments 'A' and 'long'.
8226 // note: candidate operator<=>(int, int)
8227 // note: candidate operator<=>(long, long)
8228 //
8229 // To avoid this error, this function deviates from the specification and adds
8230 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8231 // arithmetic types (the same as the generic relational overloads).
8232 //
8233 // For now this function acts as a placeholder.
8234 void addThreeWayArithmeticOverloads() {
8235 addGenericBinaryArithmeticOverloads();
8236 }
8237
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008238 // C++ [over.built]p17:
8239 //
8240 // For every pair of promoted integral types L and R, there
8241 // exist candidate operator functions of the form
8242 //
8243 // LR operator%(L, R);
8244 // LR operator&(L, R);
8245 // LR operator^(L, R);
8246 // LR operator|(L, R);
8247 // L operator<<(L, R);
8248 // L operator>>(L, R);
8249 //
8250 // where LR is the result of the usual arithmetic conversions
8251 // between types L and R.
8252 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008253 if (!HasArithmeticOrEnumeralCandidateType)
8254 return;
8255
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008256 for (unsigned Left = FirstPromotedIntegralType;
8257 Left < LastPromotedIntegralType; ++Left) {
8258 for (unsigned Right = FirstPromotedIntegralType;
8259 Right < LastPromotedIntegralType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008260 QualType LandR[2] = { ArithmeticTypes[Left],
8261 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008262 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263 }
8264 }
8265 }
8266
8267 // C++ [over.built]p20:
8268 //
8269 // For every pair (T, VQ), where T is an enumeration or
8270 // pointer to member type and VQ is either volatile or
8271 // empty, there exist candidate operator functions of the form
8272 //
8273 // VQ T& operator=(VQ T&, T);
8274 void addAssignmentMemberPointerOrEnumeralOverloads() {
8275 /// Set of (canonical) types that we've already handled.
8276 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8277
8278 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8279 for (BuiltinCandidateTypeSet::iterator
8280 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8281 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8282 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008283 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284 continue;
8285
Richard Smithe54c3072013-05-05 15:51:06 +00008286 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008287 }
8288
8289 for (BuiltinCandidateTypeSet::iterator
8290 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8291 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8292 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008293 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008294 continue;
8295
Richard Smithe54c3072013-05-05 15:51:06 +00008296 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008297 }
8298 }
8299 }
8300
8301 // C++ [over.built]p19:
8302 //
8303 // For every pair (T, VQ), where T is any type and VQ is either
8304 // volatile or empty, there exist candidate operator functions
8305 // of the form
8306 //
8307 // T*VQ& operator=(T*VQ&, T*);
8308 //
8309 // C++ [over.built]p21:
8310 //
8311 // For every pair (T, VQ), where T is a cv-qualified or
8312 // cv-unqualified object type and VQ is either volatile or
8313 // empty, there exist candidate operator functions of the form
8314 //
8315 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8316 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8317 void addAssignmentPointerOverloads(bool isEqualOp) {
8318 /// Set of (canonical) types that we've already handled.
8319 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8320
8321 for (BuiltinCandidateTypeSet::iterator
8322 Ptr = CandidateTypes[0].pointer_begin(),
8323 PtrEnd = CandidateTypes[0].pointer_end();
8324 Ptr != PtrEnd; ++Ptr) {
8325 // If this is operator=, keep track of the builtin candidates we added.
8326 if (isEqualOp)
8327 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008328 else if (!(*Ptr)->getPointeeType()->isObjectType())
8329 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008330
8331 // non-volatile version
8332 QualType ParamTypes[2] = {
8333 S.Context.getLValueReferenceType(*Ptr),
8334 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8335 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008336 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337 /*IsAssigmentOperator=*/ isEqualOp);
8338
Douglas Gregor5bee2582012-06-04 00:15:09 +00008339 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8340 VisibleTypeConversionsQuals.hasVolatile();
8341 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 // volatile version
8343 ParamTypes[0] =
8344 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
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 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008348
Douglas Gregor5bee2582012-06-04 00:15:09 +00008349 if (!(*Ptr).isRestrictQualified() &&
8350 VisibleTypeConversionsQuals.hasRestrict()) {
8351 // restrict version
8352 ParamTypes[0]
8353 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008355 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008356
Douglas Gregor5bee2582012-06-04 00:15:09 +00008357 if (NeedVolatile) {
8358 // volatile restrict version
8359 ParamTypes[0]
8360 = S.Context.getLValueReferenceType(
8361 S.Context.getCVRQualifiedType(*Ptr,
8362 (Qualifiers::Volatile |
8363 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008364 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008365 /*IsAssigmentOperator=*/isEqualOp);
8366 }
8367 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 }
8369
8370 if (isEqualOp) {
8371 for (BuiltinCandidateTypeSet::iterator
8372 Ptr = CandidateTypes[1].pointer_begin(),
8373 PtrEnd = CandidateTypes[1].pointer_end();
8374 Ptr != PtrEnd; ++Ptr) {
8375 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008376 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008377 continue;
8378
Chandler Carruth8e543b32010-12-12 08:17:55 +00008379 QualType ParamTypes[2] = {
8380 S.Context.getLValueReferenceType(*Ptr),
8381 *Ptr,
8382 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008383
8384 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008385 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008386 /*IsAssigmentOperator=*/true);
8387
Douglas Gregor5bee2582012-06-04 00:15:09 +00008388 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8389 VisibleTypeConversionsQuals.hasVolatile();
8390 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008391 // volatile version
8392 ParamTypes[0] =
8393 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008394 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008395 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008396 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008397
Douglas Gregor5bee2582012-06-04 00:15:09 +00008398 if (!(*Ptr).isRestrictQualified() &&
8399 VisibleTypeConversionsQuals.hasRestrict()) {
8400 // restrict version
8401 ParamTypes[0]
8402 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*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);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008405
Douglas Gregor5bee2582012-06-04 00:15:09 +00008406 if (NeedVolatile) {
8407 // volatile restrict version
8408 ParamTypes[0]
8409 = S.Context.getLValueReferenceType(
8410 S.Context.getCVRQualifiedType(*Ptr,
8411 (Qualifiers::Volatile |
8412 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008414 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008415 }
8416 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008417 }
8418 }
8419 }
8420
8421 // C++ [over.built]p18:
8422 //
8423 // For every triple (L, VQ, R), where L is an arithmetic type,
8424 // VQ is either volatile or empty, and R is a promoted
8425 // arithmetic type, there exist candidate operator functions of
8426 // the form
8427 //
8428 // VQ L& operator=(VQ L&, R);
8429 // VQ L& operator*=(VQ L&, R);
8430 // VQ L& operator/=(VQ L&, R);
8431 // VQ L& operator+=(VQ L&, R);
8432 // VQ L& operator-=(VQ L&, R);
8433 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008434 if (!HasArithmeticOrEnumeralCandidateType)
8435 return;
8436
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8438 for (unsigned Right = FirstPromotedArithmeticType;
8439 Right < LastPromotedArithmeticType; ++Right) {
8440 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008441 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008442
8443 // Add this built-in operator as a candidate (VQ is empty).
8444 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008445 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008446 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008447 /*IsAssigmentOperator=*/isEqualOp);
8448
8449 // Add this built-in operator as a candidate (VQ is 'volatile').
8450 if (VisibleTypeConversionsQuals.hasVolatile()) {
8451 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008452 S.Context.getVolatileType(ArithmeticTypes[Left]);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008453 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008454 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008455 /*IsAssigmentOperator=*/isEqualOp);
8456 }
8457 }
8458 }
8459
8460 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8461 for (BuiltinCandidateTypeSet::iterator
8462 Vec1 = CandidateTypes[0].vector_begin(),
8463 Vec1End = CandidateTypes[0].vector_end();
8464 Vec1 != Vec1End; ++Vec1) {
8465 for (BuiltinCandidateTypeSet::iterator
8466 Vec2 = CandidateTypes[1].vector_begin(),
8467 Vec2End = CandidateTypes[1].vector_end();
8468 Vec2 != Vec2End; ++Vec2) {
8469 QualType ParamTypes[2];
8470 ParamTypes[1] = *Vec2;
8471 // Add this built-in operator as a candidate (VQ is empty).
8472 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008473 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008474 /*IsAssigmentOperator=*/isEqualOp);
8475
8476 // Add this built-in operator as a candidate (VQ is 'volatile').
8477 if (VisibleTypeConversionsQuals.hasVolatile()) {
8478 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8479 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008480 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008481 /*IsAssigmentOperator=*/isEqualOp);
8482 }
8483 }
8484 }
8485 }
8486
8487 // C++ [over.built]p22:
8488 //
8489 // For every triple (L, VQ, R), where L is an integral type, VQ
8490 // is either volatile or empty, and R is a promoted integral
8491 // type, there exist candidate operator functions of the form
8492 //
8493 // VQ L& operator%=(VQ L&, R);
8494 // VQ L& operator<<=(VQ L&, R);
8495 // VQ L& operator>>=(VQ L&, R);
8496 // VQ L& operator&=(VQ L&, R);
8497 // VQ L& operator^=(VQ L&, R);
8498 // VQ L& operator|=(VQ L&, R);
8499 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008500 if (!HasArithmeticOrEnumeralCandidateType)
8501 return;
8502
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008503 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8504 for (unsigned Right = FirstPromotedIntegralType;
8505 Right < LastPromotedIntegralType; ++Right) {
8506 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008507 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008508
8509 // Add this built-in operator as a candidate (VQ is empty).
8510 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008511 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008512 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008513 if (VisibleTypeConversionsQuals.hasVolatile()) {
8514 // Add this built-in operator as a candidate (VQ is 'volatile').
Hans Wennborg82371412017-11-15 17:11:53 +00008515 ParamTypes[0] = ArithmeticTypes[Left];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008516 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8517 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008518 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008519 }
8520 }
8521 }
8522 }
8523
8524 // C++ [over.operator]p23:
8525 //
8526 // There also exist candidate operator functions of the form
8527 //
8528 // bool operator!(bool);
8529 // bool operator&&(bool, bool);
8530 // bool operator||(bool, bool);
8531 void addExclaimOverload() {
8532 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008533 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008534 /*IsAssignmentOperator=*/false,
8535 /*NumContextualBoolArguments=*/1);
8536 }
8537 void addAmpAmpOrPipePipeOverload() {
8538 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008539 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008540 /*IsAssignmentOperator=*/false,
8541 /*NumContextualBoolArguments=*/2);
8542 }
8543
8544 // C++ [over.built]p13:
8545 //
8546 // For every cv-qualified or cv-unqualified object type T there
8547 // exist candidate operator functions of the form
8548 //
8549 // T* operator+(T*, ptrdiff_t); [ABOVE]
8550 // T& operator[](T*, ptrdiff_t);
8551 // T* operator-(T*, ptrdiff_t); [ABOVE]
8552 // T* operator+(ptrdiff_t, T*); [ABOVE]
8553 // T& operator[](ptrdiff_t, T*);
8554 void addSubscriptOverloads() {
8555 for (BuiltinCandidateTypeSet::iterator
8556 Ptr = CandidateTypes[0].pointer_begin(),
8557 PtrEnd = CandidateTypes[0].pointer_end();
8558 Ptr != PtrEnd; ++Ptr) {
8559 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8560 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008561 if (!PointeeType->isObjectType())
8562 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008563
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008564 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008565 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008566 }
8567
8568 for (BuiltinCandidateTypeSet::iterator
8569 Ptr = CandidateTypes[1].pointer_begin(),
8570 PtrEnd = CandidateTypes[1].pointer_end();
8571 Ptr != PtrEnd; ++Ptr) {
8572 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8573 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008574 if (!PointeeType->isObjectType())
8575 continue;
8576
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008577 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008578 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008579 }
8580 }
8581
8582 // C++ [over.built]p11:
8583 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8584 // C1 is the same type as C2 or is a derived class of C2, T is an object
8585 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8586 // there exist candidate operator functions of the form
8587 //
8588 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8589 //
8590 // where CV12 is the union of CV1 and CV2.
8591 void addArrowStarOverloads() {
8592 for (BuiltinCandidateTypeSet::iterator
8593 Ptr = CandidateTypes[0].pointer_begin(),
8594 PtrEnd = CandidateTypes[0].pointer_end();
8595 Ptr != PtrEnd; ++Ptr) {
8596 QualType C1Ty = (*Ptr);
8597 QualType C1;
8598 QualifierCollector Q1;
8599 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8600 if (!isa<RecordType>(C1))
8601 continue;
8602 // heuristic to reduce number of builtin candidates in the set.
8603 // Add volatile/restrict version only if there are conversions to a
8604 // volatile/restrict type.
8605 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8606 continue;
8607 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8608 continue;
8609 for (BuiltinCandidateTypeSet::iterator
8610 MemPtr = CandidateTypes[1].member_pointer_begin(),
8611 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8612 MemPtr != MemPtrEnd; ++MemPtr) {
8613 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8614 QualType C2 = QualType(mptr->getClass(), 0);
8615 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008616 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008617 break;
8618 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8619 // build CV12 T&
8620 QualType T = mptr->getPointeeType();
8621 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8622 T.isVolatileQualified())
8623 continue;
8624 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8625 T.isRestrictQualified())
8626 continue;
8627 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008628 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008629 }
8630 }
8631 }
8632
8633 // Note that we don't consider the first argument, since it has been
8634 // contextually converted to bool long ago. The candidates below are
8635 // therefore added as binary.
8636 //
8637 // C++ [over.built]p25:
8638 // For every type T, where T is a pointer, pointer-to-member, or scoped
8639 // enumeration type, there exist candidate operator functions of the form
8640 //
8641 // T operator?(bool, T, T);
8642 //
8643 void addConditionalOperatorOverloads() {
8644 /// Set of (canonical) types that we've already handled.
8645 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8646
8647 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8648 for (BuiltinCandidateTypeSet::iterator
8649 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8650 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8651 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008652 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008653 continue;
8654
8655 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008656 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008657 }
8658
8659 for (BuiltinCandidateTypeSet::iterator
8660 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8661 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8662 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008663 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008664 continue;
8665
8666 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008667 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008668 }
8669
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008670 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008671 for (BuiltinCandidateTypeSet::iterator
8672 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8673 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8674 Enum != EnumEnd; ++Enum) {
8675 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8676 continue;
8677
David Blaikie82e95a32014-11-19 07:49:47 +00008678 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008679 continue;
8680
8681 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008682 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008683 }
8684 }
8685 }
8686 }
8687};
8688
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008689} // end anonymous namespace
8690
8691/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8692/// operator overloads to the candidate set (C++ [over.built]), based
8693/// on the operator @p Op and the arguments given. For example, if the
8694/// operator is a binary '+', this routine might add "int
8695/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008696void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8697 SourceLocation OpLoc,
8698 ArrayRef<Expr *> Args,
8699 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008700 // Find all of the types that the arguments can convert to, but only
8701 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008702 // that make use of these types. Also record whether we encounter non-record
8703 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008704 Qualifiers VisibleTypeConversionsQuals;
8705 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008706 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008707 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008708
8709 bool HasNonRecordCandidateType = false;
8710 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008711 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008712 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008713 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008714 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8715 OpLoc,
8716 true,
8717 (Op == OO_Exclaim ||
8718 Op == OO_AmpAmp ||
8719 Op == OO_PipePipe),
8720 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008721 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8722 CandidateTypes[ArgIdx].hasNonRecordTypes();
8723 HasArithmeticOrEnumeralCandidateType =
8724 HasArithmeticOrEnumeralCandidateType ||
8725 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008726 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008727
Chandler Carruth00a38332010-12-13 01:44:01 +00008728 // Exit early when no non-record types have been added to the candidate set
8729 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008730 //
8731 // We can't exit early for !, ||, or &&, since there we have always have
8732 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008733 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008734 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008735 return;
8736
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008737 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008738 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008739 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008740 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008741 CandidateTypes, CandidateSet);
8742
8743 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008744 switch (Op) {
8745 case OO_None:
8746 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008747 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008748
Chandler Carruth5184de02010-12-12 08:51:33 +00008749 case OO_New:
8750 case OO_Delete:
8751 case OO_Array_New:
8752 case OO_Array_Delete:
8753 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008754 llvm_unreachable(
8755 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008756
8757 case OO_Comma:
8758 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008759 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008760 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008761 // -- For the operator ',', the unary operator '&', the
8762 // operator '->', or the operator 'co_await', the
8763 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008764 break;
8765
8766 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008767 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008768 OpBuilder.addUnaryPlusPointerOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008769 LLVM_FALLTHROUGH;
Douglas Gregord08452f2008-11-19 15:42:04 +00008770
8771 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008772 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008773 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008774 } else {
8775 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008776 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008777 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008778 break;
8779
Chandler Carruth5184de02010-12-12 08:51:33 +00008780 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008781 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008782 OpBuilder.addUnaryStarPointerOverloads();
8783 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008784 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008785 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008786
Chandler Carruth5184de02010-12-12 08:51:33 +00008787 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008788 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008789 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008790
8791 case OO_PlusPlus:
8792 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008793 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8794 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008795 break;
8796
Douglas Gregor84605ae2009-08-24 13:43:27 +00008797 case OO_EqualEqual:
8798 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008799 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008800 LLVM_FALLTHROUGH;
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008801
Douglas Gregora11693b2008-11-12 17:17:38 +00008802 case OO_Less:
8803 case OO_Greater:
8804 case OO_LessEqual:
8805 case OO_GreaterEqual:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008806 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008807 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008808 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008809
Richard Smithd30b23d2017-12-01 02:13:10 +00008810 case OO_Spaceship:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008811 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8812 OpBuilder.addThreeWayArithmeticOverloads();
8813 break;
Richard Smithd30b23d2017-12-01 02:13:10 +00008814
Douglas Gregora11693b2008-11-12 17:17:38 +00008815 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008816 case OO_Caret:
8817 case OO_Pipe:
8818 case OO_LessLess:
8819 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008820 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008821 break;
8822
Chandler Carruth5184de02010-12-12 08:51:33 +00008823 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008824 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008825 // C++ [over.match.oper]p3:
8826 // -- For the operator ',', the unary operator '&', or the
8827 // operator '->', the built-in candidates set is empty.
8828 break;
8829
8830 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8831 break;
8832
8833 case OO_Tilde:
8834 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8835 break;
8836
Douglas Gregora11693b2008-11-12 17:17:38 +00008837 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008838 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008839 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008840
8841 case OO_PlusEqual:
8842 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008843 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008844 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008845
8846 case OO_StarEqual:
8847 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008848 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008849 break;
8850
8851 case OO_PercentEqual:
8852 case OO_LessLessEqual:
8853 case OO_GreaterGreaterEqual:
8854 case OO_AmpEqual:
8855 case OO_CaretEqual:
8856 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008857 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008858 break;
8859
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008860 case OO_Exclaim:
8861 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008862 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008863
Douglas Gregora11693b2008-11-12 17:17:38 +00008864 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008865 case OO_PipePipe:
8866 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008867 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008868
8869 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008870 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008871 break;
8872
8873 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008874 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008875 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008876
8877 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008878 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008879 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008880 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008881 }
8882}
8883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008884/// Add function candidates found via argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00008885/// to the set of overloading candidates.
8886///
8887/// This routine performs argument-dependent name lookup based on the
8888/// given function name (which may also be an operator name) and adds
8889/// all of the overload candidates found by ADL to the overload
8890/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008891void
Douglas Gregore254f902009-02-04 00:32:51 +00008892Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008893 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008894 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008895 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008896 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008897 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008898 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008899
John McCall91f61fc2010-01-26 06:04:06 +00008900 // FIXME: This approach for uniquing ADL results (and removing
8901 // redundant candidates from the set) relies on pointer-equality,
8902 // which means we need to key off the canonical decl. However,
8903 // always going back to the canonical decl might not get us the
8904 // right set of default arguments. What default arguments are
8905 // we supposed to consider on ADL candidates, anyway?
8906
Douglas Gregorcabea402009-09-22 15:41:20 +00008907 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008908 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008909
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008910 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008911 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8912 CandEnd = CandidateSet.end();
8913 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008914 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008915 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008916 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008917 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008918 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008919
8920 // For each of the ADL candidates we found, add it to the overload
8921 // set.
John McCall8fe68082010-01-26 07:16:45 +00008922 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008923 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008924 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008925 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008926 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008927
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008928 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8929 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008930 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008931 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008932 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008933 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008934 }
Douglas Gregore254f902009-02-04 00:32:51 +00008935}
8936
George Burgess IV3dc166912016-05-10 01:59:34 +00008937namespace {
8938enum class Comparison { Equal, Better, Worse };
8939}
8940
8941/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8942/// overload resolution.
8943///
8944/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8945/// Cand1's first N enable_if attributes have precisely the same conditions as
8946/// Cand2's first N enable_if attributes (where N = the number of enable_if
8947/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8948///
8949/// Note that you can have a pair of candidates such that Cand1's enable_if
8950/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8951/// worse than Cand1's.
8952static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8953 const FunctionDecl *Cand2) {
8954 // Common case: One (or both) decls don't have enable_if attrs.
8955 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8956 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8957 if (!Cand1Attr || !Cand2Attr) {
8958 if (Cand1Attr == Cand2Attr)
8959 return Comparison::Equal;
8960 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8961 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008962
Michael Kruse41dd6ce2018-06-25 20:06:13 +00008963 // FIXME: The next several lines are just
8964 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8965 // instead of reverse order which is how they're stored in the AST.
8966 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8967 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8968
8969 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8970 // has fewer enable_if attributes than Cand2.
8971 if (Cand1Attrs.size() < Cand2Attrs.size())
8972 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008973
8974 auto Cand1I = Cand1Attrs.begin();
8975 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Michael Kruse41dd6ce2018-06-25 20:06:13 +00008976 for (auto &Cand2A : Cand2Attrs) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00008977 Cand1ID.clear();
8978 Cand2ID.clear();
8979
Michael Kruse41dd6ce2018-06-25 20:06:13 +00008980 auto &Cand1A = *Cand1I++;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008981 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8982 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8983 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008984 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008985 }
8986
George Burgess IV3dc166912016-05-10 01:59:34 +00008987 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008988}
8989
Erich Keane3efe0022018-07-20 14:13:28 +00008990static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8991 const OverloadCandidate &Cand2) {
8992 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
8993 !Cand2.Function->isMultiVersion())
8994 return false;
8995
8996 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
8997 // cpu_dispatch, else arbitrarily based on the identifiers.
8998 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
8999 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9000 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9001 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9002
9003 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9004 return false;
9005
9006 if (Cand1CPUDisp && !Cand2CPUDisp)
9007 return true;
9008 if (Cand2CPUDisp && !Cand1CPUDisp)
9009 return false;
9010
9011 if (Cand1CPUSpec && Cand2CPUSpec) {
9012 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9013 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9014
9015 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9016 FirstDiff = std::mismatch(
9017 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9018 Cand2CPUSpec->cpus_begin(),
9019 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9020 return LHS->getName() == RHS->getName();
9021 });
9022
9023 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9024 "Two different cpu-specific versions should not have the same "
9025 "identifier list, otherwise they'd be the same decl!");
9026 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9027 }
9028 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9029}
9030
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009031/// isBetterOverloadCandidate - Determines whether the first overload
9032/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00009033bool clang::isBetterOverloadCandidate(
9034 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9035 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009036 // Define viable functions to be better candidates than non-viable
9037 // functions.
9038 if (!Cand2.Viable)
9039 return Cand1.Viable;
9040 else if (!Cand1.Viable)
9041 return false;
9042
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009043 // C++ [over.match.best]p1:
9044 //
9045 // -- if F is a static member function, ICS1(F) is defined such
9046 // that ICS1(F) is neither better nor worse than ICS1(G) for
9047 // any function G, and, symmetrically, ICS1(G) is neither
9048 // better nor worse than ICS1(F).
9049 unsigned StartArg = 0;
9050 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9051 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009052
George Burgess IVfbad5b22016-09-07 20:03:19 +00009053 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9054 // We don't allow incompatible pointer conversions in C++.
9055 if (!S.getLangOpts().CPlusPlus)
9056 return ICS.isStandard() &&
9057 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9058
9059 // The only ill-formed conversion we allow in C++ is the string literal to
9060 // char* conversion, which is only considered ill-formed after C++11.
9061 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9062 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9063 };
9064
9065 // Define functions that don't require ill-formed conversions for a given
9066 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00009067 unsigned NumArgs = Cand1.Conversions.size();
9068 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00009069 bool HasBetterConversion = false;
9070 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9071 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9072 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9073 if (Cand1Bad != Cand2Bad) {
9074 if (Cand1Bad)
9075 return false;
9076 HasBetterConversion = true;
9077 }
9078 }
9079
9080 if (HasBetterConversion)
9081 return true;
9082
Douglas Gregord3cb3562009-07-07 23:38:56 +00009083 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00009084 // A viable function F1 is defined to be a better function than another
9085 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00009086 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009087 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009088 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009089 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009090 Cand2.Conversions[ArgIdx])) {
9091 case ImplicitConversionSequence::Better:
9092 // Cand1 has a better conversion sequence.
9093 HasBetterConversion = true;
9094 break;
9095
9096 case ImplicitConversionSequence::Worse:
9097 // Cand1 can't be better than Cand2.
9098 return false;
9099
9100 case ImplicitConversionSequence::Indistinguishable:
9101 // Do nothing.
9102 break;
9103 }
9104 }
9105
Mike Stump11289f42009-09-09 15:08:12 +00009106 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00009107 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009108 if (HasBetterConversion)
9109 return true;
9110
Douglas Gregora1f013e2008-11-07 22:36:19 +00009111 // -- the context is an initialization by user-defined conversion
9112 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9113 // from the return type of F1 to the destination type (i.e.,
9114 // the type of the entity being initialized) is a better
9115 // conversion sequence than the standard conversion sequence
9116 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00009117 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9118 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009119 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009120 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009121 // First check whether we prefer one of the conversion functions over the
9122 // other. This only distinguishes the results in non-standard, extension
9123 // cases such as the conversion from a lambda closure type to a function
9124 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009125 ImplicitConversionSequence::CompareKind Result =
9126 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9127 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009128 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009129 Cand1.FinalConversion,
9130 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009131
Richard Smithec2748a2014-05-17 04:36:39 +00009132 if (Result != ImplicitConversionSequence::Indistinguishable)
9133 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009134
9135 // FIXME: Compare kind of reference binding if conversion functions
9136 // convert to a reference type used in direct reference binding, per
9137 // C++14 [over.match.best]p1 section 2 bullet 3.
9138 }
9139
Richard Smith51731362017-11-01 01:37:11 +00009140 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9141 // as combined with the resolution to CWG issue 243.
9142 //
9143 // When the context is initialization by constructor ([over.match.ctor] or
9144 // either phase of [over.match.list]), a constructor is preferred over
9145 // a conversion function.
9146 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9147 Cand1.Function && Cand2.Function &&
9148 isa<CXXConstructorDecl>(Cand1.Function) !=
9149 isa<CXXConstructorDecl>(Cand2.Function))
9150 return isa<CXXConstructorDecl>(Cand1.Function);
9151
Richard Smith6fdeaab2014-05-17 01:58:45 +00009152 // -- F1 is a non-template function and F2 is a function template
9153 // specialization, or, if not that,
9154 bool Cand1IsSpecialization = Cand1.Function &&
9155 Cand1.Function->getPrimaryTemplate();
9156 bool Cand2IsSpecialization = Cand2.Function &&
9157 Cand2.Function->getPrimaryTemplate();
9158 if (Cand1IsSpecialization != Cand2IsSpecialization)
9159 return Cand2IsSpecialization;
9160
9161 // -- F1 and F2 are function template specializations, and the function
9162 // template for F1 is more specialized than the template for F2
9163 // according to the partial ordering rules described in 14.5.5.2, or,
9164 // if not that,
9165 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9166 if (FunctionTemplateDecl *BetterTemplate
9167 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9168 Cand2.Function->getPrimaryTemplate(),
9169 Loc,
9170 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9171 : TPOC_Call,
9172 Cand1.ExplicitCallArguments,
9173 Cand2.ExplicitCallArguments))
9174 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009175 }
9176
Richard Smith5179eb72016-06-28 19:03:57 +00009177 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9178 // A derived-class constructor beats an (inherited) base class constructor.
9179 bool Cand1IsInherited =
9180 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9181 bool Cand2IsInherited =
9182 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9183 if (Cand1IsInherited != Cand2IsInherited)
9184 return Cand2IsInherited;
9185 else if (Cand1IsInherited) {
9186 assert(Cand2IsInherited);
9187 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9188 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9189 if (Cand1Class->isDerivedFrom(Cand2Class))
9190 return true;
9191 if (Cand2Class->isDerivedFrom(Cand1Class))
9192 return false;
9193 // Inherited from sibling base classes: still ambiguous.
9194 }
9195
Faisal Vali81b756e2017-10-22 14:45:08 +00009196 // Check C++17 tie-breakers for deduction guides.
9197 {
9198 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9199 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9200 if (Guide1 && Guide2) {
9201 // -- F1 is generated from a deduction-guide and F2 is not
9202 if (Guide1->isImplicit() != Guide2->isImplicit())
9203 return Guide2->isImplicit();
9204
9205 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9206 if (Guide1->isCopyDeductionCandidate())
9207 return true;
9208 }
9209 }
Richard Smith67ef14f2017-09-26 18:37:55 +00009210
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009211 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009212 if (Cand1.Function && Cand2.Function) {
9213 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9214 if (Cmp != Comparison::Equal)
9215 return Cmp == Comparison::Better;
9216 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009217
Justin Lebar25c4a812016-03-29 16:24:16 +00009218 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009219 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9220 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9221 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9222 }
9223
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009224 bool HasPS1 = Cand1.Function != nullptr &&
9225 functionHasPassObjectSizeParams(Cand1.Function);
9226 bool HasPS2 = Cand2.Function != nullptr &&
9227 functionHasPassObjectSizeParams(Cand2.Function);
Erich Keane3efe0022018-07-20 14:13:28 +00009228 if (HasPS1 != HasPS2 && HasPS1)
9229 return true;
9230
9231 return isBetterMultiversionCandidate(Cand1, Cand2);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009232}
9233
Richard Smith2dbe4042015-11-04 19:26:32 +00009234/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009235/// name lookup and overload resolution. This applies when the same internal/no
9236/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009237/// the same header). In such a case, we don't consider the declarations to
9238/// declare the same entity, but we also don't want lookups with both
9239/// declarations visible to be ambiguous in some cases (this happens when using
9240/// a modularized libstdc++).
9241bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9242 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009243 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9244 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9245 if (!VA || !VB)
9246 return false;
9247
9248 // The declarations must be declaring the same name as an internal linkage
9249 // entity in different modules.
9250 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9251 VB->getDeclContext()->getRedeclContext()) ||
9252 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9253 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9254 VA->isExternallyVisible() || VB->isExternallyVisible())
9255 return false;
9256
9257 // Check that the declarations appear to be equivalent.
9258 //
9259 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9260 // For constants and functions, we should check the initializer or body is
9261 // the same. For non-constant variables, we shouldn't allow it at all.
9262 if (Context.hasSameType(VA->getType(), VB->getType()))
9263 return true;
9264
9265 // Enum constants within unnamed enumerations will have different types, but
9266 // may still be similar enough to be interchangeable for our purposes.
9267 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9268 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9269 // Only handle anonymous enums. If the enumerations were named and
9270 // equivalent, they would have been merged to the same type.
9271 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9272 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9273 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9274 !Context.hasSameType(EnumA->getIntegerType(),
9275 EnumB->getIntegerType()))
9276 return false;
9277 // Allow this only if the value is the same for both enumerators.
9278 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9279 }
9280 }
9281
9282 // Nothing else is sufficiently similar.
9283 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009284}
9285
9286void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9287 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9288 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9289
9290 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9291 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9292 << !M << (M ? M->getFullModuleName() : "");
9293
9294 for (auto *E : Equiv) {
9295 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9296 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9297 << !M << (M ? M->getFullModuleName() : "");
9298 }
Richard Smith896c66e2015-10-21 07:13:52 +00009299}
9300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009301/// Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009302/// within an overload candidate set.
9303///
James Dennettffad8b72012-06-22 08:10:18 +00009304/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009305/// which overload resolution occurs.
9306///
James Dennettffad8b72012-06-22 08:10:18 +00009307/// \param Best If overload resolution was successful or found a deleted
9308/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009309///
9310/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009311OverloadingResult
9312OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009313 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009314 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9315 std::transform(begin(), end(), std::back_inserter(Candidates),
9316 [](OverloadCandidate &Cand) { return &Cand; });
9317
Justin Lebar66a2ab92016-08-10 00:40:43 +00009318 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9319 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009320 // compilation mode only one call variant is viable. We need to
9321 // exclude non-viable overload candidates from consideration based
9322 // only on their host/device attributes. Specifically, if one
9323 // candidate call is WrongSide and the other is SameSide, we ignore
9324 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009325 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009326 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9327 bool ContainsSameSideCandidate =
9328 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9329 return Cand->Function &&
9330 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9331 Sema::CFP_SameSide;
9332 });
9333 if (ContainsSameSideCandidate) {
9334 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9335 return Cand->Function &&
9336 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9337 Sema::CFP_WrongSide;
9338 };
George Burgess IV8684b032017-01-04 19:16:29 +00009339 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009340 }
9341 }
9342
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009343 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009344 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009345 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009346 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009347 if (Best == end() ||
9348 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009349 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009350
9351 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009352 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009353 return OR_No_Viable_Function;
9354
Richard Smith2dbe4042015-11-04 19:26:32 +00009355 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009356
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009357 // Make sure that this function is better than every other viable
9358 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009359 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009360 if (Cand->Viable && Cand != Best &&
9361 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009362 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9363 Cand->Function)) {
9364 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009365 continue;
9366 }
9367
John McCall5c32be02010-08-24 20:38:10 +00009368 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009369 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009370 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009371 }
Mike Stump11289f42009-09-09 15:08:12 +00009372
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009373 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009374 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009375 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009376 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009377 return OR_Deleted;
9378
Richard Smith2dbe4042015-11-04 19:26:32 +00009379 if (!EquivalentCands.empty())
9380 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9381 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009382
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009383 return OR_Success;
9384}
9385
John McCall53262c92010-01-12 02:15:36 +00009386namespace {
9387
9388enum OverloadCandidateKind {
9389 oc_function,
9390 oc_method,
9391 oc_constructor,
9392 oc_implicit_default_constructor,
9393 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009394 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009395 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009396 oc_implicit_move_assignment,
Eric Fiselier92e523b2018-05-30 01:00:41 +00009397 oc_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00009398};
9399
Eric Fiselier92e523b2018-05-30 01:00:41 +00009400enum OverloadCandidateSelect {
9401 ocs_non_template,
9402 ocs_template,
9403 ocs_described_template,
9404};
9405
9406static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
George Burgess IVd66d37c2016-10-28 21:42:06 +00009407ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9408 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009409
Eric Fiselier92e523b2018-05-30 01:00:41 +00009410 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
John McCalle1ac8d12010-01-13 00:25:19 +00009411 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9412 isTemplate = true;
9413 Description = S.getTemplateArgumentBindingsText(
Eric Fiselier92e523b2018-05-30 01:00:41 +00009414 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
John McCalle1ac8d12010-01-13 00:25:19 +00009415 }
John McCallfd0b2f82010-01-06 09:43:14 +00009416
Eric Fiselier92e523b2018-05-30 01:00:41 +00009417 OverloadCandidateSelect Select = [&]() {
9418 if (!Description.empty())
9419 return ocs_described_template;
9420 return isTemplate ? ocs_template : ocs_non_template;
9421 }();
9422
9423 OverloadCandidateKind Kind = [&]() {
9424 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9425 if (!Ctor->isImplicit()) {
9426 if (isa<ConstructorUsingShadowDecl>(Found))
9427 return oc_inherited_constructor;
9428 else
9429 return oc_constructor;
9430 }
9431
9432 if (Ctor->isDefaultConstructor())
9433 return oc_implicit_default_constructor;
9434
9435 if (Ctor->isMoveConstructor())
9436 return oc_implicit_move_constructor;
9437
9438 assert(Ctor->isCopyConstructor() &&
9439 "unexpected sort of implicit constructor");
9440 return oc_implicit_copy_constructor;
Richard Smith5179eb72016-06-28 19:03:57 +00009441 }
Sebastian Redl08905022011-02-05 19:23:19 +00009442
Eric Fiselier92e523b2018-05-30 01:00:41 +00009443 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9444 // This actually gets spelled 'candidate function' for now, but
9445 // it doesn't hurt to split it out.
9446 if (!Meth->isImplicit())
9447 return oc_method;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009448
Eric Fiselier92e523b2018-05-30 01:00:41 +00009449 if (Meth->isMoveAssignmentOperator())
9450 return oc_implicit_move_assignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009451
Eric Fiselier92e523b2018-05-30 01:00:41 +00009452 if (Meth->isCopyAssignmentOperator())
9453 return oc_implicit_copy_assignment;
John McCallfd0b2f82010-01-06 09:43:14 +00009454
Eric Fiselier92e523b2018-05-30 01:00:41 +00009455 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9456 return oc_method;
9457 }
John McCallfd0b2f82010-01-06 09:43:14 +00009458
Eric Fiselier92e523b2018-05-30 01:00:41 +00009459 return oc_function;
9460 }();
Alexis Hunt119c10e2011-05-25 23:16:36 +00009461
Eric Fiselier92e523b2018-05-30 01:00:41 +00009462 return std::make_pair(Kind, Select);
John McCall53262c92010-01-12 02:15:36 +00009463}
9464
Richard Smith5179eb72016-06-28 19:03:57 +00009465void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9466 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9467 // set.
9468 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9469 S.Diag(FoundDecl->getLocation(),
9470 diag::note_ovl_candidate_inherited_constructor)
9471 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009472}
9473
John McCall53262c92010-01-12 02:15:36 +00009474} // end anonymous namespace
9475
George Burgess IV5f21c712015-10-12 19:57:04 +00009476static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9477 const FunctionDecl *FD) {
9478 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9479 bool AlwaysTrue;
9480 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9481 return false;
9482 if (!AlwaysTrue)
9483 return false;
9484 }
9485 return true;
9486}
9487
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009488/// Returns true if we can take the address of the function.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009489///
9490/// \param Complain - If true, we'll emit a diagnostic
9491/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9492/// we in overload resolution?
9493/// \param Loc - The location of the statement we're complaining about. Ignored
9494/// if we're not complaining, or if we're in overload resolution.
9495static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9496 bool Complain,
9497 bool InOverloadResolution,
9498 SourceLocation Loc) {
9499 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9500 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009501 if (InOverloadResolution)
9502 S.Diag(FD->getLocStart(),
9503 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9504 else
9505 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9506 }
9507 return false;
9508 }
9509
George Burgess IV21081362016-07-24 23:12:40 +00009510 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9511 return P->hasAttr<PassObjectSizeAttr>();
9512 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009513 if (I == FD->param_end())
9514 return true;
9515
9516 if (Complain) {
9517 // Add one to ParamNo because it's user-facing
9518 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9519 if (InOverloadResolution)
9520 S.Diag(FD->getLocation(),
9521 diag::note_ovl_candidate_has_pass_object_size_params)
9522 << ParamNo;
9523 else
9524 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9525 << FD << ParamNo;
9526 }
9527 return false;
9528}
9529
9530static bool checkAddressOfCandidateIsAvailable(Sema &S,
9531 const FunctionDecl *FD) {
9532 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9533 /*InOverloadResolution=*/true,
9534 /*Loc=*/SourceLocation());
9535}
9536
9537bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9538 bool Complain,
9539 SourceLocation Loc) {
9540 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9541 /*InOverloadResolution=*/false,
9542 Loc);
9543}
9544
John McCall53262c92010-01-12 02:15:36 +00009545// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009546void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9547 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009548 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9549 return;
Erich Keane3efe0022018-07-20 14:13:28 +00009550 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9551 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +00009552 return;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009553
John McCalle1ac8d12010-01-13 00:25:19 +00009554 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009555 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9556 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009557 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009558 << (unsigned)KSPair.first << (unsigned)KSPair.second
9559 << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009560
9561 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009562 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009563 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009564}
9565
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009566// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009567// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009568void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9569 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009570 assert(OverloadedExpr->getType() == Context.OverloadTy);
9571
9572 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9573 OverloadExpr *OvlExpr = Ovl.Expression;
9574
9575 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009576 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009577 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009578 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009579 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009580 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009581 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009582 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009583 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009584 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009585 }
9586 }
9587}
9588
John McCall0d1da222010-01-12 00:44:57 +00009589/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9590/// "lead" diagnostic; it will be given two arguments, the source and
9591/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009592void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9593 Sema &S,
9594 SourceLocation CaretLoc,
9595 const PartialDiagnostic &PDiag) const {
9596 S.Diag(CaretLoc, PDiag)
9597 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009598 // FIXME: The note limiting machinery is borrowed from
9599 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9600 // refactoring here.
9601 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9602 unsigned CandsShown = 0;
9603 AmbiguousConversionSequence::const_iterator I, E;
9604 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9605 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9606 break;
9607 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009608 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009609 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009610 if (I != E)
9611 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009612}
9613
Richard Smith17c00b42014-11-12 01:24:00 +00009614static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009615 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009616 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9617 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009618 assert(Cand->Function && "for now, candidate must be a function");
9619 FunctionDecl *Fn = Cand->Function;
9620
9621 // There's a conversion slot for the object argument if this is a
9622 // non-constructor method. Note that 'I' corresponds the
9623 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009624 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009625 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009626 if (I == 0)
9627 isObjectArgument = true;
9628 else
9629 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009630 }
9631
John McCalle1ac8d12010-01-13 00:25:19 +00009632 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009633 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009634 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009635
John McCall6a61b522010-01-13 09:16:55 +00009636 Expr *FromExpr = Conv.Bad.FromExpr;
9637 QualType FromTy = Conv.Bad.getFromType();
9638 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009639
John McCallfb7ad0f2010-02-02 02:42:52 +00009640 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009641 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009642 Expr *E = FromExpr->IgnoreParens();
9643 if (isa<UnaryOperator>(E))
9644 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009645 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009646
9647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009648 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9649 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9650 << Name << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009651 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009652 return;
9653 }
9654
John McCall6d174642010-01-23 08:10:49 +00009655 // Do some hand-waving analysis to see if the non-viability is due
9656 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009657 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9658 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9659 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9660 CToTy = RT->getPointeeType();
9661 else {
9662 // TODO: detect and diagnose the full richness of const mismatches.
9663 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009664 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9665 CFromTy = FromPT->getPointeeType();
9666 CToTy = ToPT->getPointeeType();
9667 }
John McCall47000992010-01-14 03:28:57 +00009668 }
9669
9670 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9671 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009672 Qualifiers FromQs = CFromTy.getQualifiers();
9673 Qualifiers ToQs = CToTy.getQualifiers();
9674
9675 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9676 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009677 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
Anastasia Stulovabf549bf2018-06-22 15:45:08 +00009679 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009681 return;
9682 }
9683
John McCall31168b02011-06-15 23:02:42 +00009684 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009685 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009686 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9687 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9688 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9689 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009690 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009691 return;
9692 }
9693
Douglas Gregoraec25842011-04-26 23:16:46 +00009694 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9695 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009696 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9697 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9698 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9699 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009700 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009701 return;
9702 }
9703
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009704 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009706 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9707 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9708 << FromQs.hasUnaligned() << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009709 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009710 return;
9711 }
9712
John McCall47000992010-01-14 03:28:57 +00009713 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9714 assert(CVR && "unexpected qualifiers mismatch");
9715
9716 if (isObjectArgument) {
9717 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009718 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9719 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9720 << (CVR - 1);
John McCall47000992010-01-14 03:28:57 +00009721 } else {
9722 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009723 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9724 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9725 << (CVR - 1) << I + 1;
John McCall47000992010-01-14 03:28:57 +00009726 }
Richard Smith5179eb72016-06-28 19:03:57 +00009727 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009728 return;
9729 }
9730
Sebastian Redla72462c2011-09-24 17:48:32 +00009731 // Special diagnostic for failure to convert an initializer list, since
9732 // telling the user that it has type void is not useful.
9733 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009735 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9736 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9737 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009738 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009739 return;
9740 }
9741
John McCall6d174642010-01-23 08:10:49 +00009742 // Diagnose references or pointers to incomplete types differently,
9743 // since it's far from impossible that the incompleteness triggered
9744 // the failure.
9745 QualType TempFromTy = FromTy.getNonReferenceType();
9746 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9747 TempFromTy = PTy->getPointeeType();
9748 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009749 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009750 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009751 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9752 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9753 << ToTy << (unsigned)isObjectArgument << I + 1
9754 << (unsigned)(Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009755
Richard Smith5179eb72016-06-28 19:03:57 +00009756 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009757 return;
9758 }
9759
Douglas Gregor56f2e342010-06-30 23:01:39 +00009760 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009761 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009762 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9763 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9764 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9765 FromPtrTy->getPointeeType()) &&
9766 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9767 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009768 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009769 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009770 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009771 }
9772 } else if (const ObjCObjectPointerType *FromPtrTy
9773 = FromTy->getAs<ObjCObjectPointerType>()) {
9774 if (const ObjCObjectPointerType *ToPtrTy
9775 = ToTy->getAs<ObjCObjectPointerType>())
9776 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9777 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9778 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9779 FromPtrTy->getPointeeType()) &&
9780 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009781 BaseToDerivedConversion = 2;
9782 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009783 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9784 !FromTy->isIncompleteType() &&
9785 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009786 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009787 BaseToDerivedConversion = 3;
9788 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9789 ToTy.getNonReferenceType().getCanonicalType() ==
9790 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009792 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9793 << (unsigned)isObjectArgument << I + 1
9794 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
Richard Smith5179eb72016-06-28 19:03:57 +00009795 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009796 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009797 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009799
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009800 if (BaseToDerivedConversion) {
Eric Fiselier92e523b2018-05-30 01:00:41 +00009801 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9802 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9804 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009805 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009806 return;
9807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009808
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009809 if (isa<ObjCObjectPointerType>(CFromTy) &&
9810 isa<PointerType>(CToTy)) {
9811 Qualifiers FromQs = CFromTy.getQualifiers();
9812 Qualifiers ToQs = CToTy.getQualifiers();
9813 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009815 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9816 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9817 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009818 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009819 return;
9820 }
9821 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009822
9823 if (TakingCandidateAddress &&
9824 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9825 return;
9826
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009827 // Emit the generic diagnostic and, optionally, add the hints to it.
9828 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
Eric Fiselier92e523b2018-05-30 01:00:41 +00009829 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9830 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9831 << ToTy << (unsigned)isObjectArgument << I + 1
9832 << (unsigned)(Cand->Fix.Kind);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009833
9834 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009835 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9836 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009837 FDiag << *HI;
9838 S.Diag(Fn->getLocation(), FDiag);
9839
Richard Smith5179eb72016-06-28 19:03:57 +00009840 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009841}
9842
Larisse Voufo98b20f12013-07-19 23:00:19 +00009843/// Additional arity mismatch diagnosis specific to a function overload
9844/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9845/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009846static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9847 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009848 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009849 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009850
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009851 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009852 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009853 // right number of arguments, because only overloaded operators have
9854 // the weird behavior of overloading member and non-member functions.
9855 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009856 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009857 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009858 return true;
9859
9860 if (NumArgs < MinParams) {
9861 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9862 (Cand->FailureKind == ovl_fail_bad_deduction &&
9863 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9864 } else {
9865 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9866 (Cand->FailureKind == ovl_fail_bad_deduction &&
9867 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9868 }
9869
9870 return false;
9871}
9872
9873/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009874static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9875 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009876 assert(isa<FunctionDecl>(D) &&
9877 "The templated declaration should at least be a function"
9878 " when diagnosing bad template argument deduction due to too many"
9879 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009880
Larisse Voufo98b20f12013-07-19 23:00:19 +00009881 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009882
Larisse Voufo98b20f12013-07-19 23:00:19 +00009883 // TODO: treat calls to a missing default constructor as a special case
9884 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9885 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009886
John McCall6a61b522010-01-13 09:16:55 +00009887 // at least / at most / exactly
9888 unsigned mode, modeCount;
9889 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009890 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9891 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009892 mode = 0; // "at least"
9893 else
9894 mode = 2; // "exactly"
9895 modeCount = MinParams;
9896 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009897 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009898 mode = 1; // "at most"
9899 else
9900 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009901 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009902 }
9903
9904 std::string Description;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009905 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009906 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009907
Richard Smith10ff50d2012-05-11 05:16:41 +00009908 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9911 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009912 else
9913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009914 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9915 << Description << mode << modeCount << NumFormalArgs;
9916
Richard Smith5179eb72016-06-28 19:03:57 +00009917 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009918}
9919
Larisse Voufo98b20f12013-07-19 23:00:19 +00009920/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009921static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9922 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009923 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009924 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009925}
Larisse Voufo47c08452013-07-19 22:53:23 +00009926
Richard Smith17c00b42014-11-12 01:24:00 +00009927static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009928 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9929 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009930 llvm_unreachable("Unsupported: Getting the described template declaration"
9931 " for bad deduction diagnosis");
9932}
9933
9934/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009935static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009936 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009937 unsigned NumArgs,
9938 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009939 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009940 NamedDecl *ParamD;
9941 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9942 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9943 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009944 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009945 case Sema::TDK_Success:
9946 llvm_unreachable("TDK_success while diagnosing bad deduction");
9947
9948 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009949 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009950 S.Diag(Templated->getLocation(),
9951 diag::note_ovl_candidate_incomplete_deduction)
9952 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009953 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009954 return;
9955 }
9956
Richard Smith4a8f3512018-07-19 19:00:37 +00009957 case Sema::TDK_IncompletePack: {
9958 assert(ParamD && "no parameter found for incomplete deduction result");
9959 S.Diag(Templated->getLocation(),
9960 diag::note_ovl_candidate_incomplete_deduction_pack)
9961 << ParamD->getDeclName()
9962 << (DeductionFailure.getFirstArg()->pack_size() + 1)
9963 << *DeductionFailure.getFirstArg();
9964 MaybeEmitInheritedConstructorNote(S, Found);
9965 return;
9966 }
9967
John McCall42d7d192010-08-05 09:05:08 +00009968 case Sema::TDK_Underqualified: {
9969 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9970 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9971
Larisse Voufo98b20f12013-07-19 23:00:19 +00009972 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009973
9974 // Param will have been canonicalized, but it should just be a
9975 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009976 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009977 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009978 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009979 assert(S.Context.hasSameType(Param, NonCanonParam));
9980
9981 // Arg has also been canonicalized, but there's nothing we can do
9982 // about that. It also doesn't matter as much, because it won't
9983 // have any template parameters in it (because deduction isn't
9984 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009985 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009986
Larisse Voufo98b20f12013-07-19 23:00:19 +00009987 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9988 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009989 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009990 return;
9991 }
9992
9993 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009994 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009995 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009996 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009997 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009998 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9999 // Deduction might have failed because we deduced arguments of two
10000 // different types for a non-type template parameter.
10001 // FIXME: Use a different TDK value for this.
10002 QualType T1 =
10003 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10004 QualType T2 =
10005 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10006 if (!S.Context.hasSameType(T1, T2)) {
10007 S.Diag(Templated->getLocation(),
10008 diag::note_ovl_candidate_inconsistent_deduction_types)
10009 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10010 << *DeductionFailure.getSecondArg() << T2;
10011 MaybeEmitInheritedConstructorNote(S, Found);
10012 return;
10013 }
10014
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010015 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +000010016 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010017 which = 2;
10018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010019
Larisse Voufo98b20f12013-07-19 23:00:19 +000010020 S.Diag(Templated->getLocation(),
10021 diag::note_ovl_candidate_inconsistent_deduction)
10022 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10023 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +000010024 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010025 return;
10026 }
Douglas Gregor02eb4832010-05-08 18:13:28 +000010027
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010028 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010029 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010030 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +000010031 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010032 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010033 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010034 else {
10035 int index = 0;
10036 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10037 index = TTP->getIndex();
10038 else if (NonTypeTemplateParmDecl *NTTP
10039 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10040 index = NTTP->getIndex();
10041 else
10042 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +000010043 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010044 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010045 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010046 }
Richard Smith5179eb72016-06-28 19:03:57 +000010047 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010048 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010049
Douglas Gregor02eb4832010-05-08 18:13:28 +000010050 case Sema::TDK_TooManyArguments:
10051 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +000010052 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +000010053 return;
Douglas Gregord09efd42010-05-08 20:07:26 +000010054
10055 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010056 S.Diag(Templated->getLocation(),
10057 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +000010058 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010059 return;
10060
10061 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +000010062 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010063 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010064 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +000010065 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +000010066 TemplateArgString = " ";
10067 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +000010068 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +000010069 }
10070
Richard Smith6f8d2c62012-05-09 05:17:00 +000010071 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010072 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +000010073 if (PDiag && PDiag->second.getDiagID() ==
10074 diag::err_typename_nested_not_found_enable_if) {
10075 // FIXME: Use the source range of the condition, and the fully-qualified
10076 // name of the enable_if template. These are both present in PDiag.
10077 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10078 << "'enable_if'" << TemplateArgString;
10079 return;
10080 }
10081
Douglas Gregor00fa10b2017-07-05 20:20:14 +000010082 // We found a specific requirement that disabled the enable_if.
10083 if (PDiag && PDiag->second.getDiagID() ==
10084 diag::err_typename_nested_not_found_requirement) {
10085 S.Diag(Templated->getLocation(),
10086 diag::note_ovl_candidate_disabled_by_requirement)
10087 << PDiag->second.getStringArg(0) << TemplateArgString;
10088 return;
10089 }
10090
Richard Smith9ca64612012-05-07 09:03:25 +000010091 // Format the SFINAE diagnostic into the argument string.
10092 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10093 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010094 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010095 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +000010096 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +000010097 SFINAEArgString = ": ";
10098 R = SourceRange(PDiag->first, PDiag->first);
10099 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10100 }
10101
Larisse Voufo98b20f12013-07-19 23:00:19 +000010102 S.Diag(Templated->getLocation(),
10103 diag::note_ovl_candidate_substitution_failure)
10104 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +000010105 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010106 return;
10107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010108
Richard Smithc92d2062017-01-05 23:02:44 +000010109 case Sema::TDK_DeducedMismatch:
10110 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +000010111 // Format the template argument list into the argument string.
10112 SmallString<128> TemplateArgString;
10113 if (TemplateArgumentList *Args =
10114 DeductionFailure.getTemplateArgumentList()) {
10115 TemplateArgString = " ";
10116 TemplateArgString += S.getTemplateArgumentBindingsText(
10117 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10118 }
10119
10120 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10121 << (*DeductionFailure.getCallArgIndex() + 1)
10122 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +000010123 << TemplateArgString
10124 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +000010125 break;
10126 }
10127
Richard Trieue3732352013-04-08 21:11:40 +000010128 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +000010129 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010130 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10131 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +000010132 if (FirstTA.getKind() == TemplateArgument::Template &&
10133 SecondTA.getKind() == TemplateArgument::Template) {
10134 TemplateName FirstTN = FirstTA.getAsTemplate();
10135 TemplateName SecondTN = SecondTA.getAsTemplate();
10136 if (FirstTN.getKind() == TemplateName::Template &&
10137 SecondTN.getKind() == TemplateName::Template) {
10138 if (FirstTN.getAsTemplateDecl()->getName() ==
10139 SecondTN.getAsTemplateDecl()->getName()) {
10140 // FIXME: This fixes a bad diagnostic where both templates are named
10141 // the same. This particular case is a bit difficult since:
10142 // 1) It is passed as a string to the diagnostic printer.
10143 // 2) The diagnostic printer only attempts to find a better
10144 // name for types, not decls.
10145 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010146 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010147 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10148 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10149 return;
10150 }
10151 }
10152 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010153
10154 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10155 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10156 return;
10157
Faisal Vali2b391ab2013-09-26 19:54:12 +000010158 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010159 // call operator, and if so, emit a prettier and more informative
10160 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +000010161 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010162 S.Diag(Templated->getLocation(),
10163 diag::note_ovl_candidate_non_deduced_mismatch)
10164 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010165 return;
Richard Trieue3732352013-04-08 21:11:40 +000010166 }
John McCall8b9ed552010-02-01 18:53:26 +000010167 // TODO: diagnose these individually, then kill off
10168 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010169 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010170 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010171 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010172 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010173 case Sema::TDK_CUDATargetMismatch:
10174 S.Diag(Templated->getLocation(),
10175 diag::note_cuda_ovl_candidate_target_mismatch);
10176 return;
John McCall8b9ed552010-02-01 18:53:26 +000010177 }
10178}
10179
Larisse Voufo98b20f12013-07-19 23:00:19 +000010180/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010181static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010182 unsigned NumArgs,
10183 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010184 unsigned TDK = Cand->DeductionFailure.Result;
10185 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10186 if (CheckArityMismatch(S, Cand, NumArgs))
10187 return;
10188 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010189 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010190 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010191}
10192
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010193/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010194static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010195 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10196 FunctionDecl *Callee = Cand->Function;
10197
10198 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10199 CalleeTarget = S.IdentifyCUDATarget(Callee);
10200
10201 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010202 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +000010203 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010204
10205 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010206 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10207 << FnDesc /* Ignored */
10208 << CalleeTarget << CallerTarget;
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010209
10210 // This could be an implicit constructor for which we could not infer the
10211 // target due to a collsion. Diagnose that case.
10212 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10213 if (Meth != nullptr && Meth->isImplicit()) {
10214 CXXRecordDecl *ParentClass = Meth->getParent();
10215 Sema::CXXSpecialMember CSM;
10216
Eric Fiselier92e523b2018-05-30 01:00:41 +000010217 switch (FnKindPair.first) {
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010218 default:
10219 return;
10220 case oc_implicit_default_constructor:
10221 CSM = Sema::CXXDefaultConstructor;
10222 break;
10223 case oc_implicit_copy_constructor:
10224 CSM = Sema::CXXCopyConstructor;
10225 break;
10226 case oc_implicit_move_constructor:
10227 CSM = Sema::CXXMoveConstructor;
10228 break;
10229 case oc_implicit_copy_assignment:
10230 CSM = Sema::CXXCopyAssignment;
10231 break;
10232 case oc_implicit_move_assignment:
10233 CSM = Sema::CXXMoveAssignment;
10234 break;
10235 };
10236
10237 bool ConstRHS = false;
10238 if (Meth->getNumParams()) {
10239 if (const ReferenceType *RT =
10240 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10241 ConstRHS = RT->getPointeeType().isConstQualified();
10242 }
10243 }
10244
10245 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10246 /* ConstRHS */ ConstRHS,
10247 /* Diagnose */ true);
10248 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010249}
10250
Richard Smith17c00b42014-11-12 01:24:00 +000010251static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010252 FunctionDecl *Callee = Cand->Function;
10253 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10254
10255 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010256 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010257 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10258}
10259
Yaxun Liu5b746652016-12-18 05:18:55 +000010260static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10261 FunctionDecl *Callee = Cand->Function;
10262
10263 S.Diag(Callee->getLocation(),
10264 diag::note_ovl_candidate_disabled_by_extension);
10265}
10266
John McCall8b9ed552010-02-01 18:53:26 +000010267/// Generates a 'note' diagnostic for an overload candidate. We've
10268/// already generated a primary error at the call site.
10269///
10270/// It really does need to be a single diagnostic with its caret
10271/// pointed at the candidate declaration. Yes, this creates some
10272/// major challenges of technical writing. Yes, this makes pointing
10273/// out problems with specific arguments quite awkward. It's still
10274/// better than generating twenty screens of text for every failed
10275/// overload.
10276///
10277/// It would be great to be able to express per-candidate problems
10278/// more richly for those diagnostic clients that cared, but we'd
10279/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010280static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010281 unsigned NumArgs,
10282 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010283 FunctionDecl *Fn = Cand->Function;
10284
John McCall12f97bc2010-01-08 04:41:39 +000010285 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010286 if (Cand->Viable) {
10287 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10288 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010289 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10290 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010291
George Burgess IV177399e2017-01-09 04:12:14 +000010292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010293 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10294 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
George Burgess IV177399e2017-01-09 04:12:14 +000010295 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10296 return;
10297 }
John McCall12f97bc2010-01-08 04:41:39 +000010298
George Burgess IV177399e2017-01-09 04:12:14 +000010299 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010300 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010301 return;
10302 }
John McCall0d1da222010-01-12 00:44:57 +000010303
John McCall6a61b522010-01-13 09:16:55 +000010304 switch (Cand->FailureKind) {
10305 case ovl_fail_too_many_arguments:
10306 case ovl_fail_too_few_arguments:
10307 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010308
John McCall6a61b522010-01-13 09:16:55 +000010309 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010310 return DiagnoseBadDeduction(S, Cand, NumArgs,
10311 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010312
John McCall578a1f82014-12-14 01:46:53 +000010313 case ovl_fail_illegal_constructor: {
10314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10315 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010316 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010317 return;
10318 }
10319
John McCallfe796dd2010-01-23 05:17:32 +000010320 case ovl_fail_trivial_conversion:
10321 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010322 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010323 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010324
John McCall65eb8792010-02-25 01:37:24 +000010325 case ovl_fail_bad_conversion: {
10326 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010327 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010328 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010329 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010330
John McCall6a61b522010-01-13 09:16:55 +000010331 // FIXME: this currently happens when we're called from SemaInit
10332 // when user-conversion overload fails. Figure out how to handle
10333 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010334 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010335 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010336
10337 case ovl_fail_bad_target:
10338 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010339
10340 case ovl_fail_enable_if:
10341 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010342
Yaxun Liu5b746652016-12-18 05:18:55 +000010343 case ovl_fail_ext_disabled:
10344 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10345
Richard Smithf9c59b72017-01-08 21:45:44 +000010346 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010347 // It's generally not interesting to note copy/move constructors here.
10348 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10349 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010350 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010351 diag::note_ovl_candidate_inherited_constructor_slice)
10352 << (Fn->getPrimaryTemplate() ? 1 : 0)
10353 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10355 return;
10356
George Burgess IV7204ed92016-01-07 02:26:57 +000010357 case ovl_fail_addr_not_available: {
10358 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10359 (void)Available;
10360 assert(!Available);
10361 break;
10362 }
Erich Keane281d20b2018-01-08 21:34:17 +000010363 case ovl_non_default_multiversion_function:
10364 // Do nothing, these should simply be ignored.
10365 break;
John McCall65eb8792010-02-25 01:37:24 +000010366 }
John McCalld3224162010-01-08 00:58:21 +000010367}
10368
Richard Smith17c00b42014-11-12 01:24:00 +000010369static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010370 // Desugar the type of the surrogate down to a function type,
10371 // retaining as many typedefs as possible while still showing
10372 // the function type (and, therefore, its parameter types).
10373 QualType FnType = Cand->Surrogate->getConversionType();
10374 bool isLValueReference = false;
10375 bool isRValueReference = false;
10376 bool isPointer = false;
10377 if (const LValueReferenceType *FnTypeRef =
10378 FnType->getAs<LValueReferenceType>()) {
10379 FnType = FnTypeRef->getPointeeType();
10380 isLValueReference = true;
10381 } else if (const RValueReferenceType *FnTypeRef =
10382 FnType->getAs<RValueReferenceType>()) {
10383 FnType = FnTypeRef->getPointeeType();
10384 isRValueReference = true;
10385 }
10386 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10387 FnType = FnTypePtr->getPointeeType();
10388 isPointer = true;
10389 }
10390 // Desugar down to a function type.
10391 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10392 // Reconstruct the pointer/reference as appropriate.
10393 if (isPointer) FnType = S.Context.getPointerType(FnType);
10394 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10395 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10396
10397 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10398 << FnType;
10399}
10400
Richard Smith17c00b42014-11-12 01:24:00 +000010401static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10402 SourceLocation OpLoc,
10403 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010404 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010405 std::string TypeStr("operator");
10406 TypeStr += Opc;
10407 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010408 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010409 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010410 TypeStr += ")";
10411 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10412 } else {
10413 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010414 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010415 TypeStr += ")";
10416 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10417 }
10418}
10419
Richard Smith17c00b42014-11-12 01:24:00 +000010420static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10421 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010422 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010423 if (ICS.isBad()) break; // all meaningless after first invalid
10424 if (!ICS.isAmbiguous()) continue;
10425
Richard Smithc2bebe92016-05-11 20:37:46 +000010426 ICS.DiagnoseAmbiguousConversion(
10427 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010428 }
10429}
10430
Larisse Voufo98b20f12013-07-19 23:00:19 +000010431static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010432 if (Cand->Function)
10433 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010434 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010435 return Cand->Surrogate->getLocation();
10436 return SourceLocation();
10437}
10438
Larisse Voufo98b20f12013-07-19 23:00:19 +000010439static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010440 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010441 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010442 case Sema::TDK_NonDependentConversionFailure:
10443 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010444
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010445 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010446 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +000010447 case Sema::TDK_IncompletePack:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010448 return 1;
10449
10450 case Sema::TDK_Underqualified:
10451 case Sema::TDK_Inconsistent:
10452 return 2;
10453
10454 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010455 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010456 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010457 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010458 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010459 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010460 return 3;
10461
10462 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010463 return 4;
10464
10465 case Sema::TDK_InvalidExplicitArguments:
10466 return 5;
10467
10468 case Sema::TDK_TooManyArguments:
10469 case Sema::TDK_TooFewArguments:
10470 return 6;
10471 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010472 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010473}
10474
Richard Smith17c00b42014-11-12 01:24:00 +000010475namespace {
John McCallad2587a2010-01-12 00:48:53 +000010476struct CompareOverloadCandidatesForDisplay {
10477 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010478 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010479 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010480 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010481
Richard Smith67ef14f2017-09-26 18:37:55 +000010482 CompareOverloadCandidatesForDisplay(
10483 Sema &S, SourceLocation Loc, size_t NArgs,
10484 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010485 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010486
10487 bool operator()(const OverloadCandidate *L,
10488 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010489 // Fast-path this check.
10490 if (L == R) return false;
10491
John McCall12f97bc2010-01-08 04:41:39 +000010492 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010493 if (L->Viable) {
10494 if (!R->Viable) return true;
10495
10496 // TODO: introduce a tri-valued comparison for overload
10497 // candidates. Would be more worthwhile if we had a sort
10498 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010499 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10500 return true;
10501 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10502 return false;
John McCallad2587a2010-01-12 00:48:53 +000010503 } else if (R->Viable)
10504 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010505
John McCall3712d9e2010-01-15 23:32:50 +000010506 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010507
John McCall3712d9e2010-01-15 23:32:50 +000010508 // Criteria by which we can sort non-viable candidates:
10509 if (!L->Viable) {
10510 // 1. Arity mismatches come after other candidates.
10511 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010512 L->FailureKind == ovl_fail_too_few_arguments) {
10513 if (R->FailureKind == ovl_fail_too_many_arguments ||
10514 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010515 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10516 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10517 if (LDist == RDist) {
10518 if (L->FailureKind == R->FailureKind)
10519 // Sort non-surrogates before surrogates.
10520 return !L->IsSurrogate && R->IsSurrogate;
10521 // Sort candidates requiring fewer parameters than there were
10522 // arguments given after candidates requiring more parameters
10523 // than there were arguments given.
10524 return L->FailureKind == ovl_fail_too_many_arguments;
10525 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010526 return LDist < RDist;
10527 }
John McCall3712d9e2010-01-15 23:32:50 +000010528 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010529 }
John McCall3712d9e2010-01-15 23:32:50 +000010530 if (R->FailureKind == ovl_fail_too_many_arguments ||
10531 R->FailureKind == ovl_fail_too_few_arguments)
10532 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010533
John McCallfe796dd2010-01-23 05:17:32 +000010534 // 2. Bad conversions come first and are ordered by the number
10535 // of bad conversions and quality of good conversions.
10536 if (L->FailureKind == ovl_fail_bad_conversion) {
10537 if (R->FailureKind != ovl_fail_bad_conversion)
10538 return true;
10539
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010540 // The conversion that can be fixed with a smaller number of changes,
10541 // comes first.
10542 unsigned numLFixes = L->Fix.NumConversionsFixed;
10543 unsigned numRFixes = R->Fix.NumConversionsFixed;
10544 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10545 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010546 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010547 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010548 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010549
John McCallfe796dd2010-01-23 05:17:32 +000010550 // If there's any ordering between the defined conversions...
10551 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010552 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010553
10554 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010555 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010556 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010557 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010558 L->Conversions[I],
10559 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010560 case ImplicitConversionSequence::Better:
10561 leftBetter++;
10562 break;
10563
10564 case ImplicitConversionSequence::Worse:
10565 leftBetter--;
10566 break;
10567
10568 case ImplicitConversionSequence::Indistinguishable:
10569 break;
10570 }
10571 }
10572 if (leftBetter > 0) return true;
10573 if (leftBetter < 0) return false;
10574
10575 } else if (R->FailureKind == ovl_fail_bad_conversion)
10576 return false;
10577
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010578 if (L->FailureKind == ovl_fail_bad_deduction) {
10579 if (R->FailureKind != ovl_fail_bad_deduction)
10580 return true;
10581
10582 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10583 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010584 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010585 } else if (R->FailureKind == ovl_fail_bad_deduction)
10586 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010587
John McCall3712d9e2010-01-15 23:32:50 +000010588 // TODO: others?
10589 }
10590
10591 // Sort everything else by location.
10592 SourceLocation LLoc = GetLocationForCandidate(L);
10593 SourceLocation RLoc = GetLocationForCandidate(R);
10594
10595 // Put candidates without locations (e.g. builtins) at the end.
10596 if (LLoc.isInvalid()) return false;
10597 if (RLoc.isInvalid()) return true;
10598
10599 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010600 }
10601};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010602}
John McCall12f97bc2010-01-08 04:41:39 +000010603
John McCallfe796dd2010-01-23 05:17:32 +000010604/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010605/// computes up to the first bad conversion. Produces the FixIt set if
10606/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010607static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10608 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010609 assert(!Cand->Viable);
10610
10611 // Don't do anything on failures other than bad conversion.
10612 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10613
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010614 // We only want the FixIts if all the arguments can be corrected.
10615 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010616 // Use a implicit copy initialization to check conversion fixes.
10617 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010618
Richard Smith6eedfe72017-01-09 08:01:21 +000010619 // Attempt to fix the bad conversion.
10620 unsigned ConvCount = Cand->Conversions.size();
10621 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10622 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010623 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010624 if (Cand->Conversions[ConvIdx].isInitialized() &&
10625 Cand->Conversions[ConvIdx].isBad()) {
10626 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010627 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010628 }
John McCallfe796dd2010-01-23 05:17:32 +000010629 }
10630
Douglas Gregoradc7a702010-04-16 17:45:54 +000010631 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010632 // operation somehow.
10633 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010634
Richard Smith14ead302017-01-10 20:19:21 +000010635 unsigned ConvIdx = 0;
10636 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010637
10638 if (Cand->IsSurrogate) {
10639 QualType ConvType
10640 = Cand->Surrogate->getConversionType().getNonReferenceType();
10641 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10642 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010643 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10644 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10645 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010646 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010647 ParamTypes =
10648 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010649 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010650 !isa<CXXConstructorDecl>(Cand->Function)) {
10651 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10652 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010653 }
Richard Smith14ead302017-01-10 20:19:21 +000010654 } else {
10655 // Builtin operator.
10656 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010657 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010658 }
10659
10660 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010661 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010662 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010663 // We've already checked this conversion.
10664 } else if (ArgIdx < ParamTypes.size()) {
10665 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010666 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10667 Args[ArgIdx]->getType());
10668 else {
10669 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010670 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010671 SuppressUserConversions,
10672 /*InOverloadResolution=*/true,
10673 /*AllowObjCWritebackConversion=*/
10674 S.getLangOpts().ObjCAutoRefCount);
10675 // Store the FixIt in the candidate if it exists.
10676 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10677 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10678 }
10679 } else
John McCallfe796dd2010-01-23 05:17:32 +000010680 Cand->Conversions[ConvIdx].setEllipsis();
10681 }
10682}
10683
Erich Keanec18cce42018-01-29 19:33:20 +000010684/// When overload resolution fails, prints diagnostic messages containing the
10685/// candidates in the candidate set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010686void OverloadCandidateSet::NoteCandidates(
10687 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10688 StringRef Opc, SourceLocation OpLoc,
10689 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010690 // Sort the candidates by viability and position. Sorting directly would
10691 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010692 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010693 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10694 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010695 if (!Filter(*Cand))
10696 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010697 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010698 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010699 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010700 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010701 if (Cand->Function || Cand->IsSurrogate)
10702 Cands.push_back(Cand);
10703 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10704 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010705 }
10706 }
10707
Mandeep Singh Grange66d2322017-11-14 00:22:24 +000010708 std::stable_sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010709 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010710
John McCall0d1da222010-01-12 00:44:57 +000010711 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010712
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010713 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010714 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010715 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010716 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10717 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010718
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010719 // Set an arbitrary limit on the number of candidate functions we'll spam
10720 // the user with. FIXME: This limit should depend on details of the
10721 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010722 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010723 break;
10724 }
10725 ++CandsShown;
10726
John McCalld3224162010-01-08 00:58:21 +000010727 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010728 NoteFunctionCandidate(S, Cand, Args.size(),
10729 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010730 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010731 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010732 else {
10733 assert(Cand->Viable &&
10734 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010735 // Generally we only see ambiguities including viable builtin
10736 // operators if overload resolution got screwed up by an
10737 // ambiguous user-defined conversion.
10738 //
10739 // FIXME: It's quite possible for different conversions to see
10740 // different ambiguities, though.
10741 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010742 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010743 ReportedAmbiguousConversions = true;
10744 }
John McCalld3224162010-01-08 00:58:21 +000010745
John McCall0d1da222010-01-12 00:44:57 +000010746 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010747 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010749 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010750
10751 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010752 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010753}
10754
Larisse Voufo98b20f12013-07-19 23:00:19 +000010755static SourceLocation
10756GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10757 return Cand->Specialization ? Cand->Specialization->getLocation()
10758 : SourceLocation();
10759}
10760
Richard Smith17c00b42014-11-12 01:24:00 +000010761namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010762struct CompareTemplateSpecCandidatesForDisplay {
10763 Sema &S;
10764 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10765
10766 bool operator()(const TemplateSpecCandidate *L,
10767 const TemplateSpecCandidate *R) {
10768 // Fast-path this check.
10769 if (L == R)
10770 return false;
10771
10772 // Assuming that both candidates are not matches...
10773
10774 // Sort by the ranking of deduction failures.
10775 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10776 return RankDeductionFailure(L->DeductionFailure) <
10777 RankDeductionFailure(R->DeductionFailure);
10778
10779 // Sort everything else by location.
10780 SourceLocation LLoc = GetLocationForCandidate(L);
10781 SourceLocation RLoc = GetLocationForCandidate(R);
10782
10783 // Put candidates without locations (e.g. builtins) at the end.
10784 if (LLoc.isInvalid())
10785 return false;
10786 if (RLoc.isInvalid())
10787 return true;
10788
10789 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10790 }
10791};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010792}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010793
10794/// Diagnose a template argument deduction failure.
10795/// We are treating these failures as overload failures due to bad
10796/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010797void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10798 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010799 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010800 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010801}
10802
10803void TemplateSpecCandidateSet::destroyCandidates() {
10804 for (iterator i = begin(), e = end(); i != e; ++i) {
10805 i->DeductionFailure.Destroy();
10806 }
10807}
10808
10809void TemplateSpecCandidateSet::clear() {
10810 destroyCandidates();
10811 Candidates.clear();
10812}
10813
10814/// NoteCandidates - When no template specialization match is found, prints
10815/// diagnostic messages containing the non-matching specializations that form
10816/// the candidate set.
10817/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10818/// OCD == OCD_AllCandidates and Cand->Viable == false.
10819void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10820 // Sort the candidates by position (assuming no candidate is a match).
10821 // Sorting directly would be prohibitive, so we make a set of pointers
10822 // and sort those.
10823 SmallVector<TemplateSpecCandidate *, 32> Cands;
10824 Cands.reserve(size());
10825 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10826 if (Cand->Specialization)
10827 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010828 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010829 // in general, want to list every possible builtin candidate.
10830 }
10831
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +000010832 llvm::sort(Cands.begin(), Cands.end(),
10833 CompareTemplateSpecCandidatesForDisplay(S));
Larisse Voufo98b20f12013-07-19 23:00:19 +000010834
10835 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10836 // for generalization purposes (?).
10837 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10838
10839 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10840 unsigned CandsShown = 0;
10841 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10842 TemplateSpecCandidate *Cand = *I;
10843
10844 // Set an arbitrary limit on the number of candidates we'll spam
10845 // the user with. FIXME: This limit should depend on details of the
10846 // candidate list.
10847 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10848 break;
10849 ++CandsShown;
10850
10851 assert(Cand->Specialization &&
10852 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010853 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010854 }
10855
10856 if (I != E)
10857 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10858}
10859
Douglas Gregorb491ed32011-02-19 21:32:49 +000010860// [PossiblyAFunctionType] --> [Return]
10861// NonFunctionType --> NonFunctionType
10862// R (A) --> R(A)
10863// R (*)(A) --> R (A)
10864// R (&)(A) --> R (A)
10865// R (S::*)(A) --> R (A)
10866QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10867 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010868 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010869 PossiblyAFunctionType->getAs<PointerType>())
10870 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010871 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010872 PossiblyAFunctionType->getAs<ReferenceType>())
10873 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010874 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010875 PossiblyAFunctionType->getAs<MemberPointerType>())
10876 Ret = MemTypePtr->getPointeeType();
10877 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010878 Context.getCanonicalType(Ret).getUnqualifiedType();
10879 return Ret;
10880}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010881
Richard Smith9095e5b2016-11-01 01:31:23 +000010882static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10883 bool Complain = true) {
10884 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10885 S.DeduceReturnType(FD, Loc, Complain))
10886 return true;
10887
10888 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010889 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +000010890 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10891 !S.ResolveExceptionSpec(Loc, FPT))
10892 return true;
10893
10894 return false;
10895}
10896
Richard Smith17c00b42014-11-12 01:24:00 +000010897namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010898// A helper class to help with address of function resolution
10899// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010900class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010901 Sema& S;
10902 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010903 const QualType& TargetType;
10904 QualType TargetFunctionType; // Extracted function type from target type
10905
Douglas Gregorb491ed32011-02-19 21:32:49 +000010906 bool Complain;
10907 //DeclAccessPair& ResultFunctionAccessPair;
10908 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010909
Douglas Gregorb491ed32011-02-19 21:32:49 +000010910 bool TargetTypeIsNonStaticMemberFunction;
10911 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010912 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010913 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010914
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010915 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010916 OverloadExpr *OvlExpr;
10917 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010918 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010919 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010920
Douglas Gregorb491ed32011-02-19 21:32:49 +000010921public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010922 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10923 const QualType &TargetType, bool Complain)
10924 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10925 Complain(Complain), Context(S.getASTContext()),
10926 TargetTypeIsNonStaticMemberFunction(
10927 !!TargetType->getAs<MemberPointerType>()),
10928 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010929 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010930 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010931 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10932 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010933 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010934 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010935
David Majnemera4f7c7a2013-08-01 06:13:59 +000010936 if (TargetFunctionType->isFunctionType()) {
10937 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10938 if (!UME->isImplicitAccess() &&
10939 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10940 StaticMemberFunctionFromBoundPointer = true;
10941 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10942 DeclAccessPair dap;
10943 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10944 OvlExpr, false, &dap)) {
10945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10946 if (!Method->isStatic()) {
10947 // If the target type is a non-function type and the function found
10948 // is a non-static member function, pretend as if that was the
10949 // target, it's the only possible type to end up with.
10950 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010951
David Majnemera4f7c7a2013-08-01 06:13:59 +000010952 // And skip adding the function if its not in the proper form.
10953 // We'll diagnose this due to an empty set of functions.
10954 if (!OvlExprInfo.HasFormOfMemberPointer)
10955 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010956 }
10957
David Majnemera4f7c7a2013-08-01 06:13:59 +000010958 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010959 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010960 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010961 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010962
Douglas Gregorb491ed32011-02-19 21:32:49 +000010963 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010964 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010965
Douglas Gregorb491ed32011-02-19 21:32:49 +000010966 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10967 // C++ [over.over]p4:
10968 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010969 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010970 if (FoundNonTemplateFunction)
10971 EliminateAllTemplateMatches();
10972 else
10973 EliminateAllExceptMostSpecializedTemplate();
10974 }
10975 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010976
Justin Lebar25c4a812016-03-29 16:24:16 +000010977 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010978 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010979 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010980
10981 bool hasComplained() const { return HasComplained; }
10982
Douglas Gregorb491ed32011-02-19 21:32:49 +000010983private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010984 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10985 QualType Discard;
10986 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010987 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010988 }
10989
George Burgess IV6da4c202016-03-23 02:33:58 +000010990 /// \return true if A is considered a better overload candidate for the
10991 /// desired type than B.
10992 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10993 // If A doesn't have exactly the correct type, we don't want to classify it
10994 // as "better" than anything else. This way, the user is required to
10995 // disambiguate for us if there are multiple candidates and no exact match.
10996 return candidateHasExactlyCorrectType(A) &&
10997 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010998 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010999 }
11000
11001 /// \return true if we were able to eliminate all but one overload candidate,
11002 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000011003 bool eliminiateSuboptimalOverloadCandidates() {
11004 // Same algorithm as overload resolution -- one pass to pick the "best",
11005 // another pass to be sure that nothing is better than the best.
11006 auto Best = Matches.begin();
11007 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11008 if (isBetterCandidate(I->second, Best->second))
11009 Best = I;
11010
11011 const FunctionDecl *BestFn = Best->second;
11012 auto IsBestOrInferiorToBest = [this, BestFn](
11013 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11014 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11015 };
11016
11017 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11018 // option, so we can potentially give the user a better error
11019 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
11020 return false;
11021 Matches[0] = *Best;
11022 Matches.resize(1);
11023 return true;
11024 }
11025
Douglas Gregorb491ed32011-02-19 21:32:49 +000011026 bool isTargetTypeAFunction() const {
11027 return TargetFunctionType->isFunctionType();
11028 }
11029
11030 // [ToType] [Return]
11031
11032 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11033 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11034 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11035 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11036 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11037 }
11038
11039 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011040 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011041 const DeclAccessPair& CurAccessFunPair) {
11042 if (CXXMethodDecl *Method
11043 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11044 // Skip non-static function templates when converting to pointer, and
11045 // static when converting to member pointer.
11046 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11047 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011048 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011049 else if (TargetTypeIsNonStaticMemberFunction)
11050 return false;
11051
11052 // C++ [over.over]p2:
11053 // If the name is a function template, template argument deduction is
11054 // done (14.8.2.2), and if the argument deduction succeeds, the
11055 // resulting template argument list is used to generate a single
11056 // function template specialization, which is added to the set of
11057 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011058 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011059 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000011060 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011061 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011062 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011063 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000011064 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011065 // Make a note of the failed deduction for diagnostics.
11066 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011067 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011068 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000011069 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011070 }
11071
Douglas Gregor19a41f12013-04-17 08:45:07 +000011072 // Template argument deduction ensures that we have an exact match or
11073 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011074 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000011075 assert(S.isSameOrCompatibleFunctionType(
11076 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011077 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000011078
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011079 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000011080 return false;
11081
Douglas Gregorb491ed32011-02-19 21:32:49 +000011082 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11083 return true;
11084 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011085
11086 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011087 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011088 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000011089 // Skip non-static functions when converting to pointer, and static
11090 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011091 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11092 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011093 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011094 else if (TargetTypeIsNonStaticMemberFunction)
11095 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011096
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011097 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011098 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011099 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000011100 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011101 return false;
Erich Keane281d20b2018-01-08 21:34:17 +000011102 if (FunDecl->isMultiVersion()) {
11103 const auto *TA = FunDecl->getAttr<TargetAttr>();
Erich Keane3efe0022018-07-20 14:13:28 +000011104 if (TA && !TA->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +000011105 return false;
11106 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011107
Richard Smith2a7d4812013-05-04 07:00:32 +000011108 // If any candidate has a placeholder return type, trigger its deduction
11109 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000011110 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11111 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000011112 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000011113 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011114 }
Richard Smith2a7d4812013-05-04 07:00:32 +000011115
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011116 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000011117 return false;
11118
George Burgess IV6da4c202016-03-23 02:33:58 +000011119 // If we're in C, we need to support types that aren't exactly identical.
11120 if (!S.getLangOpts().CPlusPlus ||
11121 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000011122 Matches.push_back(std::make_pair(
11123 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011124 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011125 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011126 }
Mike Stump11289f42009-09-09 15:08:12 +000011127 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011128
Douglas Gregorb491ed32011-02-19 21:32:49 +000011129 return false;
11130 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011131
Douglas Gregorb491ed32011-02-19 21:32:49 +000011132 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11133 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011134
Douglas Gregorb491ed32011-02-19 21:32:49 +000011135 // If the overload expression doesn't have the form of a pointer to
11136 // member, don't try to convert it to a pointer-to-member type.
11137 if (IsInvalidFormOfPointerToMemberFunction())
11138 return false;
11139
11140 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011141 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011142 I != E; ++I) {
11143 // Look through any using declarations to find the underlying function.
11144 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11145
11146 // C++ [over.over]p3:
11147 // Non-member functions and static member functions match
11148 // targets of type "pointer-to-function" or "reference-to-function."
11149 // Nonstatic member functions match targets of
11150 // type "pointer-to-member-function."
11151 // Note that according to DR 247, the containing class does not matter.
11152 if (FunctionTemplateDecl *FunctionTemplate
11153 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11154 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11155 Ret = true;
11156 }
11157 // If we have explicit template arguments supplied, skip non-templates.
11158 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11159 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11160 Ret = true;
11161 }
11162 assert(Ret || Matches.empty());
11163 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011164 }
11165
Douglas Gregorb491ed32011-02-19 21:32:49 +000011166 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011167 // [...] and any given function template specialization F1 is
11168 // eliminated if the set contains a second function template
11169 // specialization whose function template is more specialized
11170 // than the function template of F1 according to the partial
11171 // ordering rules of 14.5.5.2.
11172
11173 // The algorithm specified above is quadratic. We instead use a
11174 // two-pass algorithm (similar to the one used to identify the
11175 // best viable function in an overload set) that identifies the
11176 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011177
11178 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11179 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11180 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011181
Larisse Voufo98b20f12013-07-19 23:00:19 +000011182 // TODO: It looks like FailedCandidates does not serve much purpose
11183 // here, since the no_viable diagnostic has index 0.
11184 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011185 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011186 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011187 S.PDiag(diag::err_addr_ovl_ambiguous)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011188 << Matches[0].second->getDeclName(),
Richard Smith5179eb72016-06-28 19:03:57 +000011189 S.PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011190 << (unsigned)oc_function << (unsigned)ocs_described_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011191 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011192
Douglas Gregorb491ed32011-02-19 21:32:49 +000011193 if (Result != MatchesCopy.end()) {
11194 // Make it the first and only element
11195 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11196 Matches[0].second = cast<FunctionDecl>(*Result);
11197 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011198 } else
11199 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011201
Douglas Gregorb491ed32011-02-19 21:32:49 +000011202 void EliminateAllTemplateMatches() {
11203 // [...] any function template specializations in the set are
11204 // eliminated if the set also contains a non-template function, [...]
11205 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011206 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011207 ++I;
11208 else {
11209 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011210 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011211 }
11212 }
11213 }
11214
Artem Belevich94a55e82015-09-22 17:22:59 +000011215 void EliminateSuboptimalCudaMatches() {
11216 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11217 }
11218
Douglas Gregorb491ed32011-02-19 21:32:49 +000011219public:
11220 void ComplainNoMatchesFound() const {
11221 assert(Matches.empty());
11222 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11223 << OvlExpr->getName() << TargetFunctionType
11224 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011225 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011226 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11227 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011228 else {
11229 // We have some deduction failure messages. Use them to diagnose
11230 // the function templates, and diagnose the non-template candidates
11231 // normally.
11232 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11233 IEnd = OvlExpr->decls_end();
11234 I != IEnd; ++I)
11235 if (FunctionDecl *Fun =
11236 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011237 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011238 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011239 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011240 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11241 }
11242 }
11243
Douglas Gregorb491ed32011-02-19 21:32:49 +000011244 bool IsInvalidFormOfPointerToMemberFunction() const {
11245 return TargetTypeIsNonStaticMemberFunction &&
11246 !OvlExprInfo.HasFormOfMemberPointer;
11247 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011248
Douglas Gregorb491ed32011-02-19 21:32:49 +000011249 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11250 // TODO: Should we condition this on whether any functions might
11251 // have matched, or is it more appropriate to do that in callers?
11252 // TODO: a fixit wouldn't hurt.
11253 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11254 << TargetType << OvlExpr->getSourceRange();
11255 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011256
11257 bool IsStaticMemberFunctionFromBoundPointer() const {
11258 return StaticMemberFunctionFromBoundPointer;
11259 }
11260
11261 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11262 S.Diag(OvlExpr->getLocStart(),
11263 diag::err_invalid_form_pointer_member_function)
11264 << OvlExpr->getSourceRange();
11265 }
11266
Douglas Gregorb491ed32011-02-19 21:32:49 +000011267 void ComplainOfInvalidConversion() const {
11268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11269 << OvlExpr->getName() << TargetType;
11270 }
11271
11272 void ComplainMultipleMatchesFound() const {
11273 assert(Matches.size() > 1);
11274 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11275 << OvlExpr->getName()
11276 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011277 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11278 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011279 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011280
11281 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11282
Douglas Gregorb491ed32011-02-19 21:32:49 +000011283 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011284
Douglas Gregorb491ed32011-02-19 21:32:49 +000011285 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011286 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011287 return Matches[0].second;
11288 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011289
Douglas Gregorb491ed32011-02-19 21:32:49 +000011290 const DeclAccessPair* getMatchingFunctionAccessPair() 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].first;
11293 }
11294};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011295}
Richard Smith17c00b42014-11-12 01:24:00 +000011296
Douglas Gregorb491ed32011-02-19 21:32:49 +000011297/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11298/// an overloaded function (C++ [over.over]), where @p From is an
11299/// expression with overloaded function type and @p ToType is the type
11300/// we're trying to resolve to. For example:
11301///
11302/// @code
11303/// int f(double);
11304/// int f(int);
11305///
11306/// int (*pfd)(double) = f; // selects f(double)
11307/// @endcode
11308///
11309/// This routine returns the resulting FunctionDecl if it could be
11310/// resolved, and NULL otherwise. When @p Complain is true, this
11311/// routine will emit diagnostics if there is an error.
11312FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011313Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11314 QualType TargetType,
11315 bool Complain,
11316 DeclAccessPair &FoundResult,
11317 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011318 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011319
11320 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11321 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011322 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011323 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011324 bool ShouldComplain = Complain && !Resolver.hasComplained();
11325 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011326 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11327 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11328 else
11329 Resolver.ComplainNoMatchesFound();
11330 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011331 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011332 Resolver.ComplainMultipleMatchesFound();
11333 else if (NumMatches == 1) {
11334 Fn = Resolver.getMatchingFunctionDecl();
11335 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011336 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11337 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011338 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011339 if (Complain) {
11340 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11341 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11342 else
11343 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11344 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011345 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011346
11347 if (pHadMultipleCandidates)
11348 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011349 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011350}
11351
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011352/// Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011353/// resolve that function to a single function that can have its address taken.
11354/// This will modify `Pair` iff it returns non-null.
11355///
11356/// This routine can only realistically succeed if all but one candidates in the
11357/// overload set for SrcExpr cannot have their addresses taken.
11358FunctionDecl *
11359Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11360 DeclAccessPair &Pair) {
11361 OverloadExpr::FindResult R = OverloadExpr::find(E);
11362 OverloadExpr *Ovl = R.Expression;
11363 FunctionDecl *Result = nullptr;
11364 DeclAccessPair DAP;
11365 // Don't use the AddressOfResolver because we're specifically looking for
11366 // cases where we have one overload candidate that lacks
11367 // enable_if/pass_object_size/...
11368 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11369 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11370 if (!FD)
11371 return nullptr;
11372
11373 if (!checkAddressOfFunctionIsAvailable(FD))
11374 continue;
11375
11376 // We have more than one result; quit.
11377 if (Result)
11378 return nullptr;
11379 DAP = I.getPair();
11380 Result = FD;
11381 }
11382
11383 if (Result)
11384 Pair = DAP;
11385 return Result;
11386}
11387
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011388/// Given an overloaded function, tries to turn it into a non-overloaded
George Burgess IVbeca4a32016-06-08 00:34:22 +000011389/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11390/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011391/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011392///
11393/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11394/// Otherwise, returns true. This may emit diagnostics and return true.
11395bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011396 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011397 Expr *E = SrcExpr.get();
11398 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11399
11400 DeclAccessPair DAP;
11401 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
Erich Keane3efe0022018-07-20 14:13:28 +000011402 if (!Found || Found->isCPUDispatchMultiVersion() ||
11403 Found->isCPUSpecificMultiVersion())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011404 return false;
11405
11406 // Emitting multiple diagnostics for a function that is both inaccessible and
11407 // unavailable is consistent with our behavior elsewhere. So, always check
11408 // for both.
11409 DiagnoseUseOfDecl(Found, E->getExprLoc());
11410 CheckAddressOfMemberAccess(E, DAP);
11411 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011412 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011413 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11414 else
11415 SrcExpr = Fixed;
11416 return true;
11417}
11418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011419/// Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011420/// resolve that overloaded function expression down to a single function.
11421///
11422/// This routine can only resolve template-ids that refer to a single function
11423/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011424/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011425/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011426///
11427/// If no template-ids are found, no diagnostics are emitted and NULL is
11428/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011429FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011430Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011431 bool Complain,
11432 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011433 // C++ [over.over]p1:
11434 // [...] [Note: any redundant set of parentheses surrounding the
11435 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011436 // C++ [over.over]p1:
11437 // [...] The overloaded function name can be preceded by the &
11438 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011439
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011440 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011441 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011442 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011443
11444 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011445 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011446 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011447
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011448 // Look through all of the overloaded functions, searching for one
11449 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011450 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011451 for (UnresolvedSetIterator I = ovl->decls_begin(),
11452 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011453 // C++0x [temp.arg.explicit]p3:
11454 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011455 // where deduction is not done, if a template argument list is
11456 // specified and it, along with any default template arguments,
11457 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011458 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011459 FunctionTemplateDecl *FunctionTemplate
11460 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011461
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011462 // C++ [over.over]p2:
11463 // If the name is a function template, template argument deduction is
11464 // done (14.8.2.2), and if the argument deduction succeeds, the
11465 // resulting template argument list is used to generate a single
11466 // function template specialization, which is added to the set of
11467 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011468 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011469 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011470 if (TemplateDeductionResult Result
11471 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011472 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011473 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011474 // Make a note of the failed deduction for diagnostics.
11475 // TODO: Actually use the failed-deduction info?
11476 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011477 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011478 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011479 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011480 }
11481
John McCall0009fcc2011-04-26 20:42:42 +000011482 assert(Specialization && "no specialization and no error?");
11483
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011484 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011485 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011486 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011487 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11488 << ovl->getName();
11489 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011490 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011491 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011492 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011493
John McCall0009fcc2011-04-26 20:42:42 +000011494 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011495 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011497
Richard Smith9095e5b2016-11-01 01:31:23 +000011498 if (Matched &&
11499 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011500 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011501
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011502 return Matched;
11503}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011504
John McCall50a2c2c2011-10-11 23:14:30 +000011505// Resolve and fix an overloaded expression that can be resolved
11506// because it identifies a single function template specialization.
11507//
Douglas Gregor1beec452011-03-12 01:48:56 +000011508// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011509//
11510// Return true if it was logically possible to so resolve the
11511// expression, regardless of whether or not it succeeded. Always
11512// returns true if 'complain' is set.
11513bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11514 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011515 bool complain, SourceRange OpRangeForComplaining,
11516 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011517 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011518 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011519
John McCall50a2c2c2011-10-11 23:14:30 +000011520 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011521
John McCall0009fcc2011-04-26 20:42:42 +000011522 DeclAccessPair found;
11523 ExprResult SingleFunctionExpression;
11524 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11525 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011526 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011527 SrcExpr = ExprError();
11528 return true;
11529 }
John McCall0009fcc2011-04-26 20:42:42 +000011530
11531 // It is only correct to resolve to an instance method if we're
11532 // resolving a form that's permitted to be a pointer to member.
11533 // Otherwise we'll end up making a bound member expression, which
11534 // is illegal in all the contexts we resolve like this.
11535 if (!ovl.HasFormOfMemberPointer &&
11536 isa<CXXMethodDecl>(fn) &&
11537 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011538 if (!complain) return false;
11539
11540 Diag(ovl.Expression->getExprLoc(),
11541 diag::err_bound_member_function)
11542 << 0 << ovl.Expression->getSourceRange();
11543
11544 // TODO: I believe we only end up here if there's a mix of
11545 // static and non-static candidates (otherwise the expression
11546 // would have 'bound member' type, not 'overload' type).
11547 // Ideally we would note which candidate was chosen and why
11548 // the static candidates were rejected.
11549 SrcExpr = ExprError();
11550 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011551 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011552
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011553 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011554 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011555 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011556
11557 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011558 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011559 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011560 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011561 if (SingleFunctionExpression.isInvalid()) {
11562 SrcExpr = ExprError();
11563 return true;
11564 }
11565 }
John McCall0009fcc2011-04-26 20:42:42 +000011566 }
11567
11568 if (!SingleFunctionExpression.isUsable()) {
11569 if (complain) {
11570 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11571 << ovl.Expression->getName()
11572 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011573 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011574 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011575 NoteAllOverloadCandidates(SrcExpr.get());
11576
11577 SrcExpr = ExprError();
11578 return true;
11579 }
11580
11581 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011582 }
11583
John McCall50a2c2c2011-10-11 23:14:30 +000011584 SrcExpr = SingleFunctionExpression;
11585 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011586}
11587
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011588/// Add a single candidate to the overload set.
Douglas Gregorcabea402009-09-22 15:41:20 +000011589static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011590 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011591 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011592 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011593 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011594 bool PartialOverloading,
11595 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011596 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011597 if (isa<UsingShadowDecl>(Callee))
11598 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11599
Douglas Gregorcabea402009-09-22 15:41:20 +000011600 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011601 if (ExplicitTemplateArgs) {
11602 assert(!KnownValid && "Explicit template arguments?");
11603 return;
11604 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011605 // Prevent ill-formed function decls to be added as overload candidates.
11606 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11607 return;
11608
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011609 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11610 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011611 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011612 return;
John McCalld14a8642009-11-21 08:51:07 +000011613 }
11614
11615 if (FunctionTemplateDecl *FuncTemplate
11616 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011617 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011618 ExplicitTemplateArgs, Args, CandidateSet,
11619 /*SuppressUsedConversions=*/false,
11620 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011621 return;
11622 }
11623
Richard Smith95ce4f62011-06-26 22:19:54 +000011624 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011625}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011627/// Add the overload candidates named by callee and/or found by argument
Douglas Gregorcabea402009-09-22 15:41:20 +000011628/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011629void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011630 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011631 OverloadCandidateSet &CandidateSet,
11632 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011633
11634#ifndef NDEBUG
11635 // Verify that ArgumentDependentLookup is consistent with the rules
11636 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011637 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011638 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11639 // and let Y be the lookup set produced by argument dependent
11640 // lookup (defined as follows). If X contains
11641 //
11642 // -- a declaration of a class member, or
11643 //
11644 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011645 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011646 //
11647 // -- a declaration that is neither a function or a function
11648 // template
11649 //
11650 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011651
John McCall57500772009-12-16 12:17:52 +000011652 if (ULE->requiresADL()) {
11653 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11654 E = ULE->decls_end(); I != E; ++I) {
11655 assert(!(*I)->getDeclContext()->isRecord());
11656 assert(isa<UsingShadowDecl>(*I) ||
11657 !(*I)->getDeclContext()->isFunctionOrMethod());
11658 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011659 }
11660 }
11661#endif
11662
John McCall57500772009-12-16 12:17:52 +000011663 // It would be nice to avoid this copy.
11664 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011665 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011666 if (ULE->hasExplicitTemplateArgs()) {
11667 ULE->copyTemplateArgumentsInto(TABuffer);
11668 ExplicitTemplateArgs = &TABuffer;
11669 }
11670
11671 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11672 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011673 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11674 CandidateSet, PartialOverloading,
11675 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011676
John McCall57500772009-12-16 12:17:52 +000011677 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011678 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011679 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011680 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011681}
John McCalld681c392009-12-16 08:11:27 +000011682
Richard Smith0603bbb2013-06-12 22:56:54 +000011683/// Determine whether a declaration with the specified name could be moved into
11684/// a different namespace.
11685static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11686 switch (Name.getCXXOverloadedOperator()) {
11687 case OO_New: case OO_Array_New:
11688 case OO_Delete: case OO_Array_Delete:
11689 return false;
11690
11691 default:
11692 return true;
11693 }
11694}
11695
Richard Smith998a5912011-06-05 22:42:48 +000011696/// Attempt to recover from an ill-formed use of a non-dependent name in a
11697/// template, where the non-dependent name was declared after the template
11698/// was defined. This is common in code written for a compilers which do not
11699/// correctly implement two-stage name lookup.
11700///
11701/// Returns true if a viable candidate was found and a diagnostic was issued.
11702static bool
11703DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11704 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011705 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011706 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011707 ArrayRef<Expr *> Args,
11708 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011709 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011710 return false;
11711
11712 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011713 if (DC->isTransparentContext())
11714 continue;
11715
Richard Smith998a5912011-06-05 22:42:48 +000011716 SemaRef.LookupQualifiedName(R, DC);
11717
11718 if (!R.empty()) {
11719 R.suppressDiagnostics();
11720
11721 if (isa<CXXRecordDecl>(DC)) {
11722 // Don't diagnose names we find in classes; we get much better
11723 // diagnostics for these from DiagnoseEmptyLookup.
11724 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011725 if (DoDiagnoseEmptyLookup)
11726 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011727 return false;
11728 }
11729
Richard Smith100b24a2014-04-17 01:52:14 +000011730 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011731 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11732 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011733 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011734 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011735
11736 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011737 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011738 // No viable functions. Don't bother the user with notes for functions
11739 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011740 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011741 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011742 }
Richard Smith998a5912011-06-05 22:42:48 +000011743
11744 // Find the namespaces where ADL would have looked, and suggest
11745 // declaring the function there instead.
11746 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11747 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011748 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011749 AssociatedNamespaces,
11750 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011751 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011752 if (canBeDeclaredInNamespace(R.getLookupName())) {
11753 DeclContext *Std = SemaRef.getStdNamespace();
11754 for (Sema::AssociatedNamespaceSet::iterator
11755 it = AssociatedNamespaces.begin(),
11756 end = AssociatedNamespaces.end(); it != end; ++it) {
11757 // Never suggest declaring a function within namespace 'std'.
11758 if (Std && Std->Encloses(*it))
11759 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011760
Richard Smith0603bbb2013-06-12 22:56:54 +000011761 // Never suggest declaring a function within a namespace with a
11762 // reserved name, like __gnu_cxx.
11763 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11764 if (NS &&
11765 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11766 continue;
11767
11768 SuggestedNamespaces.insert(*it);
11769 }
Richard Smith998a5912011-06-05 22:42:48 +000011770 }
11771
11772 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11773 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011774 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011775 SemaRef.Diag(Best->Function->getLocation(),
11776 diag::note_not_found_by_two_phase_lookup)
11777 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011778 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011779 SemaRef.Diag(Best->Function->getLocation(),
11780 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011781 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011782 } else {
11783 // FIXME: It would be useful to list the associated namespaces here,
11784 // but the diagnostics infrastructure doesn't provide a way to produce
11785 // a localized representation of a list of items.
11786 SemaRef.Diag(Best->Function->getLocation(),
11787 diag::note_not_found_by_two_phase_lookup)
11788 << R.getLookupName() << 2;
11789 }
11790
11791 // Try to recover by calling this function.
11792 return true;
11793 }
11794
11795 R.clear();
11796 }
11797
11798 return false;
11799}
11800
11801/// Attempt to recover from ill-formed use of a non-dependent operator in a
11802/// template, where the non-dependent operator was declared after the template
11803/// was defined.
11804///
11805/// Returns true if a viable candidate was found and a diagnostic was issued.
11806static bool
11807DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11808 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011809 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011810 DeclarationName OpName =
11811 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11812 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11813 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011814 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011815 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011816}
11817
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011818namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011819class BuildRecoveryCallExprRAII {
11820 Sema &SemaRef;
11821public:
11822 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11823 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11824 SemaRef.IsBuildingRecoveryCallExpr = true;
11825 }
11826
11827 ~BuildRecoveryCallExprRAII() {
11828 SemaRef.IsBuildingRecoveryCallExpr = false;
11829 }
11830};
11831
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011832}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011833
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011834static std::unique_ptr<CorrectionCandidateCallback>
11835MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11836 bool HasTemplateArgs, bool AllowTypoCorrection) {
11837 if (!AllowTypoCorrection)
11838 return llvm::make_unique<NoTypoCorrectionCCC>();
11839 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11840 HasTemplateArgs, ME);
11841}
11842
John McCalld681c392009-12-16 08:11:27 +000011843/// Attempts to recover from a call where no functions were found.
11844///
11845/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011846static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011847BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011848 UnresolvedLookupExpr *ULE,
11849 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011850 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011851 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011852 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011853 // Do not try to recover if it is already building a recovery call.
11854 // This stops infinite loops for template instantiations like
11855 //
11856 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11857 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11858 //
11859 if (SemaRef.IsBuildingRecoveryCallExpr)
11860 return ExprError();
11861 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011862
11863 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011864 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011865 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011866
John McCall57500772009-12-16 12:17:52 +000011867 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011868 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011869 if (ULE->hasExplicitTemplateArgs()) {
11870 ULE->copyTemplateArgumentsInto(TABuffer);
11871 ExplicitTemplateArgs = &TABuffer;
11872 }
11873
John McCalld681c392009-12-16 08:11:27 +000011874 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11875 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011876 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011877 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011878 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011879 ExplicitTemplateArgs, Args,
11880 &DoDiagnoseEmptyLookup) &&
11881 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11882 S, SS, R,
11883 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11884 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11885 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011886 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011887
John McCall57500772009-12-16 12:17:52 +000011888 assert(!R.empty() && "lookup results empty despite recovery");
11889
Richard Smith151c4562016-12-20 21:35:28 +000011890 // If recovery created an ambiguity, just bail out.
11891 if (R.isAmbiguous()) {
11892 R.suppressDiagnostics();
11893 return ExprError();
11894 }
11895
John McCall57500772009-12-16 12:17:52 +000011896 // Build an implicit member call if appropriate. Just drop the
11897 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011898 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011899 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011900 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11901 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011902 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011903 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011904 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011905 else
11906 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11907
11908 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011909 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011910
11911 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011912 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011913 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011914 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011915 MultiExprArg(Args.data(), Args.size()),
11916 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011917}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011919/// Constructs and populates an OverloadedCandidateSet from
Sam Panzer0f384432012-08-21 00:52:01 +000011920/// the given function.
11921/// \returns true when an the ExprResult output parameter has been set.
11922bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11923 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011924 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011925 SourceLocation RParenLoc,
11926 OverloadCandidateSet *CandidateSet,
11927 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011928#ifndef NDEBUG
11929 if (ULE->requiresADL()) {
11930 // To do ADL, we must have found an unqualified name.
11931 assert(!ULE->getQualifier() && "qualified name with ADL");
11932
11933 // We don't perform ADL for implicit declarations of builtins.
11934 // Verify that this was correctly set up.
11935 FunctionDecl *F;
11936 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11937 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11938 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011939 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011940
John McCall57500772009-12-16 12:17:52 +000011941 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011942 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011943 }
John McCall57500772009-12-16 12:17:52 +000011944#endif
11945
John McCall4124c492011-10-17 18:40:02 +000011946 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011947 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011948 *Result = ExprError();
11949 return true;
11950 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011951
John McCall57500772009-12-16 12:17:52 +000011952 // Add the functions denoted by the callee to the set of candidate
11953 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011954 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011955
Hans Wennborgb2747382015-06-12 21:23:23 +000011956 if (getLangOpts().MSVCCompat &&
11957 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011958 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11959
11960 OverloadCandidateSet::iterator Best;
11961 if (CandidateSet->empty() ||
11962 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11963 OR_No_Viable_Function) {
11964 // In Microsoft mode, if we are inside a template class member function then
11965 // create a type dependent CallExpr. The goal is to postpone name lookup
11966 // to instantiation time to be able to search into type dependent base
11967 // classes.
11968 CallExpr *CE = new (Context) CallExpr(
11969 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011970 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011971 CE->setValueDependent(true);
11972 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011973 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011974 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011975 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011976 }
John McCalld681c392009-12-16 08:11:27 +000011977
Hans Wennborg64937c62015-06-11 21:21:57 +000011978 if (CandidateSet->empty())
11979 return false;
11980
John McCall4124c492011-10-17 18:40:02 +000011981 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011982 return false;
11983}
John McCall4124c492011-10-17 18:40:02 +000011984
Sam Panzer0f384432012-08-21 00:52:01 +000011985/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11986/// the completed call expression. If overload resolution fails, emits
11987/// diagnostics and returns ExprError()
11988static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11989 UnresolvedLookupExpr *ULE,
11990 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011991 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011992 SourceLocation RParenLoc,
11993 Expr *ExecConfig,
11994 OverloadCandidateSet *CandidateSet,
11995 OverloadCandidateSet::iterator *Best,
11996 OverloadingResult OverloadResult,
11997 bool AllowTypoCorrection) {
11998 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011999 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012000 RParenLoc, /*EmptyLookup=*/true,
12001 AllowTypoCorrection);
12002
12003 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000012004 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000012005 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000012006 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012007 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12008 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012009 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012010 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12011 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000012012 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012013
Richard Smith998a5912011-06-05 22:42:48 +000012014 case OR_No_Viable_Function: {
12015 // Try to recover by looking for viable functions which the user might
12016 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000012017 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012018 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000012019 /*EmptyLookup=*/false,
12020 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000012021 if (!Recovery.isInvalid())
12022 return Recovery;
12023
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012024 // If the user passes in a function that we can't take the address of, we
12025 // generally end up emitting really bad error messages. Here, we attempt to
12026 // emit better ones.
12027 for (const Expr *Arg : Args) {
12028 if (!Arg->getType()->isFunctionType())
12029 continue;
12030 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12031 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12032 if (FD &&
12033 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12034 Arg->getExprLoc()))
12035 return ExprError();
12036 }
12037 }
12038
12039 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
12040 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012041 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012042 break;
Richard Smith998a5912011-06-05 22:42:48 +000012043 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012044
12045 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000012046 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000012047 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012048 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012049 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012050
Sam Panzer0f384432012-08-21 00:52:01 +000012051 case OR_Deleted: {
12052 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
12053 << (*Best)->Function->isDeleted()
12054 << ULE->getName()
12055 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12056 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012057 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000012058
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012059 // We emitted an error for the unavailable/deleted function call but keep
Sam Panzer0f384432012-08-21 00:52:01 +000012060 // the call in the AST.
12061 FunctionDecl *FDecl = (*Best)->Function;
12062 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012063 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12064 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000012065 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012066 }
12067
Douglas Gregorb412e172010-07-25 18:17:45 +000012068 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000012069 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012070}
12071
George Burgess IV7204ed92016-01-07 02:26:57 +000012072static void markUnaddressableCandidatesUnviable(Sema &S,
12073 OverloadCandidateSet &CS) {
12074 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12075 if (I->Viable &&
12076 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12077 I->Viable = false;
12078 I->FailureKind = ovl_fail_addr_not_available;
12079 }
12080 }
12081}
12082
Sam Panzer0f384432012-08-21 00:52:01 +000012083/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12084/// (which eventually refers to the declaration Func) and the call
12085/// arguments Args/NumArgs, attempt to resolve the function call down
12086/// to a specific function. If overload resolution succeeds, returns
12087/// the call expression produced by overload resolution.
12088/// Otherwise, emits diagnostics and returns ExprError.
12089ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12090 UnresolvedLookupExpr *ULE,
12091 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012092 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012093 SourceLocation RParenLoc,
12094 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000012095 bool AllowTypoCorrection,
12096 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000012097 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12098 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000012099 ExprResult result;
12100
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012101 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12102 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000012103 return result;
12104
George Burgess IV7204ed92016-01-07 02:26:57 +000012105 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12106 // functions that aren't addressible are considered unviable.
12107 if (CalleesAddressIsTaken)
12108 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12109
Sam Panzer0f384432012-08-21 00:52:01 +000012110 OverloadCandidateSet::iterator Best;
12111 OverloadingResult OverloadResult =
12112 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12113
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012114 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012115 RParenLoc, ExecConfig, &CandidateSet,
12116 &Best, OverloadResult,
12117 AllowTypoCorrection);
12118}
12119
John McCall4c4c1df2010-01-26 03:27:55 +000012120static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000012121 return Functions.size() > 1 ||
12122 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12123}
12124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012125/// Create a unary operation that may resolve to an overloaded
Douglas Gregor084d8552009-03-13 23:49:33 +000012126/// operator.
12127///
12128/// \param OpLoc The location of the operator itself (e.g., '*').
12129///
Craig Toppera92ffb02015-12-10 08:51:49 +000012130/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000012131///
James Dennett18348b62012-06-22 08:52:37 +000012132/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000012133/// considered by overload resolution. The caller needs to build this
12134/// set based on the context using, e.g.,
12135/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12136/// set should not contain any member functions; those will be added
12137/// by CreateOverloadedUnaryOp().
12138///
James Dennett91738ff2012-06-22 10:32:46 +000012139/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000012140ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000012141Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012142 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012143 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012144 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12145 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12146 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012147 // TODO: provide better source location info.
12148 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012149
John McCall4124c492011-10-17 18:40:02 +000012150 if (checkPlaceholderForOverload(*this, Input))
12151 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012152
Craig Topperc3ec1492014-05-26 06:22:03 +000012153 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012154 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012155
Douglas Gregor084d8552009-03-13 23:49:33 +000012156 // For post-increment and post-decrement, add the implicit '0' as
12157 // the second argument, so that we know this is a post-increment or
12158 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012159 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012160 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012161 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12162 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012163 NumArgs = 2;
12164 }
12165
Richard Smithe54c3072013-05-05 15:51:06 +000012166 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12167
Douglas Gregor084d8552009-03-13 23:49:33 +000012168 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012169 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012170 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
Aaron Ballmana5038552018-01-09 13:07:03 +000012171 VK_RValue, OK_Ordinary, OpLoc, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012172
Craig Topperc3ec1492014-05-26 06:22:03 +000012173 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012174 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012175 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012176 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012177 /*ADL*/ true, IsOverloaded(Fns),
12178 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012179 return new (Context)
12180 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012181 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012182 }
12183
12184 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012185 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012186
12187 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012188 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012189
12190 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012191 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012192
John McCall4c4c1df2010-01-26 03:27:55 +000012193 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000012194 if (PerformADL) {
12195 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12196 /*ExplicitTemplateArgs*/nullptr,
12197 CandidateSet);
12198 }
John McCall4c4c1df2010-01-26 03:27:55 +000012199
Douglas Gregor084d8552009-03-13 23:49:33 +000012200 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012201 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012202
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12204
Douglas Gregor084d8552009-03-13 23:49:33 +000012205 // Perform overload resolution.
12206 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012207 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012208 case OR_Success: {
12209 // We found a built-in operator or an overloaded operator.
12210 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012211
Douglas Gregor084d8552009-03-13 23:49:33 +000012212 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012213 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012214 // We matched an overloaded operator. Build a call to that
12215 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012216
Douglas Gregor084d8552009-03-13 23:49:33 +000012217 // Convert the arguments.
12218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012219 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012220
John Wiegley01296292011-04-08 18:41:53 +000012221 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012222 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012223 Best->FoundDecl, Method);
12224 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012225 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012226 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012227 } else {
12228 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012229 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012230 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012231 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012232 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012233 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012234 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012235 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012236 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012237 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012238 }
12239
Douglas Gregor084d8552009-03-13 23:49:33 +000012240 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012242 Base, HadMultipleCandidates,
12243 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012244 if (FnExpr.isInvalid())
12245 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012246
Richard Smithc1564702013-11-15 02:58:23 +000012247 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012248 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012249 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12250 ResultTy = ResultTy.getNonLValueExprType(Context);
12251
Eli Friedman030eee42009-11-18 03:58:17 +000012252 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012253 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012254 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012255 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012256
Alp Toker314cc812014-01-25 16:55:45 +000012257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012258 return ExprError();
12259
George Burgess IVce6284b2017-01-28 02:19:40 +000012260 if (CheckFunctionCall(FnDecl, TheCall,
12261 FnDecl->getType()->castAs<FunctionProtoType>()))
12262 return ExprError();
12263
John McCallb268a282010-08-23 23:25:46 +000012264 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012265 } else {
12266 // We matched a built-in operator. Convert the arguments, then
12267 // break out so that we will build the appropriate built-in
12268 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012269 ExprResult InputRes = PerformImplicitConversion(
Richard Smith1ef75542018-06-27 20:30:34 +000012270 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12271 CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012272 if (InputRes.isInvalid())
12273 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012274 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012275 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012276 }
John Wiegley01296292011-04-08 18:41:53 +000012277 }
12278
12279 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012280 // This is an erroneous use of an operator which can be overloaded by
12281 // a non-member function. Check for non-member operators which were
12282 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012283 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012284 // FIXME: Recover by calling the found function.
12285 return ExprError();
12286
John Wiegley01296292011-04-08 18:41:53 +000012287 // No viable function; fall through to handling this as a
12288 // built-in operator, which will produce an error message for us.
12289 break;
12290
12291 case OR_Ambiguous:
12292 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12293 << UnaryOperator::getOpcodeStr(Opc)
12294 << Input->getType()
12295 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012296 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012297 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12298 return ExprError();
12299
12300 case OR_Deleted:
12301 Diag(OpLoc, diag::err_ovl_deleted_oper)
12302 << Best->Function->isDeleted()
12303 << UnaryOperator::getOpcodeStr(Opc)
12304 << getDeletedOrUnavailableSuffix(Best->Function)
12305 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012307 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012308 return ExprError();
12309 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012310
12311 // Either we found no viable overloaded operator or we matched a
12312 // built-in operator. In either case, fall through to trying to
12313 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012314 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012315}
12316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012317/// Create a binary operation that may resolve to an overloaded
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012318/// operator.
12319///
12320/// \param OpLoc The location of the operator itself (e.g., '+').
12321///
Craig Toppera92ffb02015-12-10 08:51:49 +000012322/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012323///
James Dennett18348b62012-06-22 08:52:37 +000012324/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012325/// considered by overload resolution. The caller needs to build this
12326/// set based on the context using, e.g.,
12327/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12328/// set should not contain any member functions; those will be added
12329/// by CreateOverloadedBinOp().
12330///
12331/// \param LHS Left-hand argument.
12332/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012333ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012334Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012335 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012336 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012337 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012338 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012339 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012340
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012341 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12343
12344 // If either side is type-dependent, create an appropriate dependent
12345 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012346 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012347 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012348 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012349 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012350 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012351 return new (Context) BinaryOperator(
12352 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012353 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012354
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012355 return new (Context) CompoundAssignOperator(
12356 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12357 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012358 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012359 }
John McCall4c4c1df2010-01-26 03:27:55 +000012360
12361 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012362 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012363 // TODO: provide better source location info in DNLoc component.
12364 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012365 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012366 = UnresolvedLookupExpr::Create(Context, NamingClass,
12367 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012368 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012369 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012370 return new (Context)
12371 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012372 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012373 }
12374
John McCall4124c492011-10-17 18:40:02 +000012375 // Always do placeholder-like conversions on the RHS.
12376 if (checkPlaceholderForOverload(*this, Args[1]))
12377 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012378
John McCall526ab472011-10-25 17:37:35 +000012379 // Do placeholder-like conversion on the LHS; note that we should
12380 // not get here with a PseudoObject LHS.
12381 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012382 if (checkPlaceholderForOverload(*this, Args[0]))
12383 return ExprError();
12384
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012385 // If this is the assignment operator, we only perform overload resolution
12386 // if the left-hand side is a class or enumeration type. This is actually
12387 // a hack. The standard requires that we do overload resolution between the
12388 // various built-in candidates, but as DR507 points out, this can lead to
12389 // problems. So we do it this way, which pretty much follows what GCC does.
12390 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012391 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012392 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012393
John McCalle26a8722010-12-04 08:14:53 +000012394 // If this is the .* operator, which is not overloadable, just
12395 // create a built-in binary operator.
12396 if (Opc == BO_PtrMemD)
12397 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12398
Douglas Gregor084d8552009-03-13 23:49:33 +000012399 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012400 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012401
12402 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012403 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012404
12405 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012406 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012407
Richard Smith0daabd72014-09-23 20:31:39 +000012408 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12409 // performed for an assignment operator (nor for operator[] nor operator->,
12410 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012411 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012412 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12413 /*ExplicitTemplateArgs*/ nullptr,
12414 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012415
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012416 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012417 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012418
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12420
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012421 // Perform overload resolution.
12422 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012423 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012424 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012425 // We found a built-in operator or an overloaded operator.
12426 FunctionDecl *FnDecl = Best->Function;
12427
12428 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012429 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012430 // We matched an overloaded operator. Build a call to that
12431 // operator.
12432
12433 // Convert the arguments.
12434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012435 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012436 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012437
Chandler Carruth8e543b32010-12-12 08:17:55 +000012438 ExprResult Arg1 =
12439 PerformCopyInitialization(
12440 InitializedEntity::InitializeParameter(Context,
12441 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012442 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012443 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012444 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012445
John Wiegley01296292011-04-08 18:41:53 +000012446 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012447 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012448 Best->FoundDecl, Method);
12449 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012450 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012451 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012452 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012453 } else {
12454 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012455 ExprResult Arg0 = PerformCopyInitialization(
12456 InitializedEntity::InitializeParameter(Context,
12457 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012458 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012459 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012460 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012461
Chandler Carruth8e543b32010-12-12 08:17:55 +000012462 ExprResult Arg1 =
12463 PerformCopyInitialization(
12464 InitializedEntity::InitializeParameter(Context,
12465 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012466 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012467 if (Arg1.isInvalid())
12468 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012469 Args[0] = LHS = Arg0.getAs<Expr>();
12470 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012471 }
12472
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012473 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012474 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012475 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012476 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012477 if (FnExpr.isInvalid())
12478 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012479
Richard Smithc1564702013-11-15 02:58:23 +000012480 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012481 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012482 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12483 ResultTy = ResultTy.getNonLValueExprType(Context);
12484
John McCallb268a282010-08-23 23:25:46 +000012485 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012486 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012487 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012488 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012489
Alp Toker314cc812014-01-25 16:55:45 +000012490 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012491 FnDecl))
12492 return ExprError();
12493
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012494 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012495 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012496 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012497 if (isa<CXXMethodDecl>(FnDecl)) {
12498 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012499 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012500 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012501
12502 // Check for a self move.
12503 if (Op == OO_Equal)
12504 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12505
George Burgess IVce6284b2017-01-28 02:19:40 +000012506 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12507 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12508 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012509
John McCallb268a282010-08-23 23:25:46 +000012510 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012511 } else {
12512 // We matched a built-in operator. Convert the arguments, then
12513 // break out so that we will build the appropriate built-in
12514 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012515 ExprResult ArgsRes0 = PerformImplicitConversion(
12516 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12517 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012518 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012519 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012520 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012521
Richard Smith1ef75542018-06-27 20:30:34 +000012522 ExprResult ArgsRes1 = PerformImplicitConversion(
12523 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12524 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012525 if (ArgsRes1.isInvalid())
12526 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012527 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012528 break;
12529 }
12530 }
12531
Douglas Gregor66950a32009-09-30 21:46:01 +000012532 case OR_No_Viable_Function: {
12533 // C++ [over.match.oper]p9:
12534 // If the operator is the operator , [...] and there are no
12535 // viable functions, then the operator is assumed to be the
12536 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012537 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012538 break;
12539
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012540 // For class as left operand for assignment or compound assignment
Chandler Carruth8e543b32010-12-12 08:17:55 +000012541 // operator do not fall through to handling in built-in, but report that
12542 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012543 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012544 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012545 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012546 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12547 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012548 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012549 if (Args[0]->getType()->isIncompleteType()) {
12550 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12551 << Args[0]->getType()
12552 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12553 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012554 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012555 // This is an erroneous use of an operator which can be overloaded by
12556 // a non-member function. Check for non-member operators which were
12557 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012558 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012559 // FIXME: Recover by calling the found function.
12560 return ExprError();
12561
Douglas Gregor66950a32009-09-30 21:46:01 +000012562 // No viable function; try to create a built-in operation, which will
12563 // produce an error. Then, show the non-viable candidates.
12564 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012566 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012567 "C++ binary operator overloading is missing candidates!");
12568 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012569 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012570 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012571 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012572 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012573
12574 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012575 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012576 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012577 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012579 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012580 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012581 return ExprError();
12582
12583 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012584 if (isImplicitlyDeleted(Best->Function)) {
12585 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12586 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012587 << Context.getRecordType(Method->getParent())
12588 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012589
Richard Smithde1a4872012-12-28 12:23:24 +000012590 // The user probably meant to call this special member. Just
12591 // explain why it's deleted.
12592 NoteDeletedFunction(Method);
12593 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012594 } else {
12595 Diag(OpLoc, diag::err_ovl_deleted_oper)
12596 << Best->Function->isDeleted()
12597 << BinaryOperator::getOpcodeStr(Opc)
12598 << getDeletedOrUnavailableSuffix(Best->Function)
12599 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12600 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012601 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012602 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012603 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012604 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012605
Douglas Gregor66950a32009-09-30 21:46:01 +000012606 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012607 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012608}
12609
John McCalldadc5752010-08-24 06:29:42 +000012610ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012611Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12612 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012613 Expr *Base, Expr *Idx) {
12614 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012615 DeclarationName OpName =
12616 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12617
12618 // If either side is type-dependent, create an appropriate dependent
12619 // expression.
12620 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12621
Craig Topperc3ec1492014-05-26 06:22:03 +000012622 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012623 // CHECKME: no 'operator' keyword?
12624 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12625 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012626 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012627 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012628 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012629 /*ADL*/ true, /*Overloaded*/ false,
12630 UnresolvedSetIterator(),
12631 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012632 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012633
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012634 return new (Context)
12635 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012636 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012637 }
12638
John McCall4124c492011-10-17 18:40:02 +000012639 // Handle placeholders on both operands.
12640 if (checkPlaceholderForOverload(*this, Args[0]))
12641 return ExprError();
12642 if (checkPlaceholderForOverload(*this, Args[1]))
12643 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012644
Sebastian Redladba46e2009-10-29 20:17:01 +000012645 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012646 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012647
12648 // Subscript can only be overloaded as a member function.
12649
12650 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012651 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012652
12653 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012654 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012655
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012656 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12657
Sebastian Redladba46e2009-10-29 20:17:01 +000012658 // Perform overload resolution.
12659 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012660 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012661 case OR_Success: {
12662 // We found a built-in operator or an overloaded operator.
12663 FunctionDecl *FnDecl = Best->Function;
12664
12665 if (FnDecl) {
12666 // We matched an overloaded operator. Build a call to that
12667 // operator.
12668
John McCalla0296f72010-03-19 07:35:19 +000012669 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012670
Sebastian Redladba46e2009-10-29 20:17:01 +000012671 // Convert the arguments.
12672 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012673 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012674 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012675 Best->FoundDecl, Method);
12676 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012677 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012678 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012679
Anders Carlssona68e51e2010-01-29 18:37:50 +000012680 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012681 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012682 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012683 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012684 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012685 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012686 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012687 if (InputInit.isInvalid())
12688 return ExprError();
12689
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012690 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012691
Sebastian Redladba46e2009-10-29 20:17:01 +000012692 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012693 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12694 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012695 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012696 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012697 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012698 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012699 OpLocInfo.getLoc(),
12700 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012701 if (FnExpr.isInvalid())
12702 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012703
Richard Smithc1564702013-11-15 02:58:23 +000012704 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012705 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012706 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12707 ResultTy = ResultTy.getNonLValueExprType(Context);
12708
John McCallb268a282010-08-23 23:25:46 +000012709 CXXOperatorCallExpr *TheCall =
12710 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012711 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012712 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012713 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012714
Alp Toker314cc812014-01-25 16:55:45 +000012715 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012716 return ExprError();
12717
George Burgess IVce6284b2017-01-28 02:19:40 +000012718 if (CheckFunctionCall(Method, TheCall,
12719 Method->getType()->castAs<FunctionProtoType>()))
12720 return ExprError();
12721
John McCallb268a282010-08-23 23:25:46 +000012722 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012723 } else {
12724 // We matched a built-in operator. Convert the arguments, then
12725 // break out so that we will build the appropriate built-in
12726 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012727 ExprResult ArgsRes0 = PerformImplicitConversion(
12728 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12729 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012730 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012731 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012732 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012733
Richard Smith1ef75542018-06-27 20:30:34 +000012734 ExprResult ArgsRes1 = PerformImplicitConversion(
12735 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12736 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012737 if (ArgsRes1.isInvalid())
12738 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012739 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012740
12741 break;
12742 }
12743 }
12744
12745 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012746 if (CandidateSet.empty())
12747 Diag(LLoc, diag::err_ovl_no_oper)
12748 << Args[0]->getType() << /*subscript*/ 0
12749 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12750 else
12751 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12752 << Args[0]->getType()
12753 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012755 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012756 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012757 }
12758
12759 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012760 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012761 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012762 << Args[0]->getType() << Args[1]->getType()
12763 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012764 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012765 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012766 return ExprError();
12767
12768 case OR_Deleted:
12769 Diag(LLoc, diag::err_ovl_deleted_oper)
12770 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012771 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012772 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012774 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012775 return ExprError();
12776 }
12777
12778 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012779 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012780}
12781
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012782/// BuildCallToMemberFunction - Build a call to a member
12783/// function. MemExpr is the expression that refers to the member
12784/// function (and includes the object parameter), Args/NumArgs are the
12785/// arguments to the function call (not including the object
12786/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012787/// expression refers to a non-static member function or an overloaded
12788/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012789ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012790Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012791 SourceLocation LParenLoc,
12792 MultiExprArg Args,
12793 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012794 assert(MemExprE->getType() == Context.BoundMemberTy ||
12795 MemExprE->getType() == Context.OverloadTy);
12796
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012797 // Dig out the member expression. This holds both the object
12798 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012799 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012800
John McCall0009fcc2011-04-26 20:42:42 +000012801 // Determine whether this is a call to a pointer-to-member function.
12802 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12803 assert(op->getType() == Context.BoundMemberTy);
12804 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12805
12806 QualType fnType =
12807 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12808
12809 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12810 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012811 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012812
12813 // Check that the object type isn't more qualified than the
12814 // member function we're calling.
12815 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12816
12817 QualType objectType = op->getLHS()->getType();
12818 if (op->getOpcode() == BO_PtrMemI)
12819 objectType = objectType->castAs<PointerType>()->getPointeeType();
12820 Qualifiers objectQuals = objectType.getQualifiers();
12821
12822 Qualifiers difference = objectQuals - funcQuals;
12823 difference.removeObjCGCAttr();
12824 difference.removeAddressSpace();
12825 if (difference) {
12826 std::string qualsString = difference.getAsString();
12827 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12828 << fnType.getUnqualifiedType()
12829 << qualsString
12830 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12831 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012832
John McCall0009fcc2011-04-26 20:42:42 +000012833 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012834 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012835 resultType, valueKind, RParenLoc);
12836
Alp Toker314cc812014-01-25 16:55:45 +000012837 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012838 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012839 return ExprError();
12840
Craig Topperc3ec1492014-05-26 06:22:03 +000012841 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012842 return ExprError();
12843
Richard Trieu9be9c682013-06-22 02:30:38 +000012844 if (CheckOtherCall(call, proto))
12845 return ExprError();
12846
John McCall0009fcc2011-04-26 20:42:42 +000012847 return MaybeBindToTemporary(call);
12848 }
12849
David Majnemerced8bdf2015-02-25 17:36:15 +000012850 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12851 return new (Context)
12852 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12853
John McCall4124c492011-10-17 18:40:02 +000012854 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012855 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012856 return ExprError();
12857
John McCall10eae182009-11-30 22:42:35 +000012858 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012859 CXXMethodDecl *Method = nullptr;
12860 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12861 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012862 if (isa<MemberExpr>(NakedMemExpr)) {
12863 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012864 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012865 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012866 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012867 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012868 } else {
12869 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012870 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012871
John McCall6e9f8f62009-12-03 04:06:58 +000012872 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012873 Expr::Classification ObjectClassification
12874 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12875 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012876
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012877 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012878 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12879 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012880
John McCall2d74de92009-12-01 22:10:20 +000012881 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012882 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012883 if (UnresExpr->hasExplicitTemplateArgs()) {
12884 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12885 TemplateArgs = &TemplateArgsBuffer;
12886 }
12887
John McCall10eae182009-11-30 22:42:35 +000012888 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12889 E = UnresExpr->decls_end(); I != E; ++I) {
12890
John McCall6e9f8f62009-12-03 04:06:58 +000012891 NamedDecl *Func = *I;
12892 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12893 if (isa<UsingShadowDecl>(Func))
12894 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12895
Douglas Gregor02824322011-01-26 19:30:28 +000012896
Francois Pichet64225792011-01-18 05:04:39 +000012897 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012898 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012899 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012900 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012901 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012902 // If explicit template arguments were provided, we can't call a
12903 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012904 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012905 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012906
John McCalla0296f72010-03-19 07:35:19 +000012907 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012908 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012909 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012910 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012911 AddMethodTemplateCandidate(
12912 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012913 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012914 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012915 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012916 }
Mike Stump11289f42009-09-09 15:08:12 +000012917
John McCall10eae182009-11-30 22:42:35 +000012918 DeclarationName DeclName = UnresExpr->getMemberName();
12919
John McCall4124c492011-10-17 18:40:02 +000012920 UnbridgedCasts.restore();
12921
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012922 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012923 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012924 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012925 case OR_Success:
12926 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012927 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012928 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012929 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12930 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012931 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012932 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012933 // called on both.
12934 // FIXME: This would be more comprehensively addressed by modifying
12935 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12936 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012937 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012938 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12939 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012940 break;
12941
12942 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012943 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012944 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012945 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012946 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012947 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012948 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012949
12950 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012951 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012952 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012953 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012954 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012955 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012956
12957 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012958 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012959 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012960 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012961 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012962 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012964 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012965 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012966 }
12967
John McCall16df1e52010-03-30 21:47:33 +000012968 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012969
John McCall2d74de92009-12-01 22:10:20 +000012970 // If overload resolution picked a static member, build a
12971 // non-member call based on that function.
12972 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012973 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12974 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012975 }
12976
John McCall10eae182009-11-30 22:42:35 +000012977 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012978 }
12979
Alp Toker314cc812014-01-25 16:55:45 +000012980 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012981 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12982 ResultType = ResultType.getNonLValueExprType(Context);
12983
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012984 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012985 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012986 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012987 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012988
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012989 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012990 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012991 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012992 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012993
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012994 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012995 // We only need to do this if there was actually an overload; otherwise
12996 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012997 if (!Method->isStatic()) {
12998 ExprResult ObjectArg =
12999 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13000 FoundDecl, Method);
13001 if (ObjectArg.isInvalid())
13002 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013003 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000013004 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013005
13006 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000013007 const FunctionProtoType *Proto =
13008 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013009 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013010 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000013011 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013012
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013013 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013014
Richard Smith55ce3522012-06-25 20:30:08 +000013015 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000013016 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000013017
George Burgess IVaea6ade2015-09-25 17:53:16 +000013018 // In the case the method to call was not selected by the overloading
13019 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000013020 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000013021 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000013022 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000013023 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000013024 diag::err_ovl_no_viable_member_function_in_call)
13025 << Method << Method->getSourceRange();
13026 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000013027 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000013028 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13029 return ExprError();
13030 }
13031 }
13032
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013033 if ((isa<CXXConstructorDecl>(CurContext) ||
13034 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000013035 TheCall->getMethodDecl()->isPure()) {
13036 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13037
Davide Italianoccb37382015-07-14 23:36:10 +000013038 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13039 MemExpr->performsVirtualDispatch(getLangOpts())) {
13040 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000013041 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13042 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13043 << MD->getParent()->getDeclName();
13044
13045 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000013046 if (getLangOpts().AppleKext)
13047 Diag(MemExpr->getLocStart(),
13048 diag::note_pure_qualified_call_kext)
13049 << MD->getParent()->getDeclName()
13050 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000013051 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000013052 }
Nico Weber5a9259c2016-01-15 21:45:31 +000013053
13054 if (CXXDestructorDecl *DD =
13055 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13056 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000013057 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000013058 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
13059 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13060 MemExpr->getMemberLoc());
13061 }
13062
John McCallb268a282010-08-23 23:25:46 +000013063 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013064}
13065
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013066/// BuildCallToObjectOfClassType - Build a call to an object of class
13067/// type (C++ [over.call.object]), which can end up invoking an
13068/// overloaded function call operator (@c operator()) or performing a
13069/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000013070ExprResult
John Wiegley01296292011-04-08 18:41:53 +000013071Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000013072 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013073 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013074 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000013075 if (checkPlaceholderForOverload(*this, Obj))
13076 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013077 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000013078
13079 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000013081 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013082
Nico Weberb58e51c2014-11-19 05:21:39 +000013083 assert(Object.get()->getType()->isRecordType() &&
13084 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000013085 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000013086
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013087 // C++ [over.call.object]p1:
13088 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000013089 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013090 // candidate functions includes at least the function call
13091 // operators of T. The function call operators of T are obtained by
13092 // ordinary lookup of the name operator() in the context of
13093 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000013094 OverloadCandidateSet CandidateSet(LParenLoc,
13095 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000013096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013097
John Wiegley01296292011-04-08 18:41:53 +000013098 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013099 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013100 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013101
John McCall27b18f82009-11-17 02:14:36 +000013102 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13103 LookupQualifiedName(R, Record->getDecl());
13104 R.suppressDiagnostics();
13105
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013106 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000013107 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000013108 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000013109 Object.get()->Classify(Context), Args, CandidateSet,
13110 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000013111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013112
Douglas Gregorab7897a2008-11-19 22:57:39 +000013113 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013114 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013115 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000013116 //
13117 // operator conversion-type-id () cv-qualifier;
13118 //
13119 // where cv-qualifier is the same cv-qualification as, or a
13120 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000013121 // denotes the type "pointer to function of (P1,...,Pn) returning
13122 // R", or the type "reference to pointer to function of
13123 // (P1,...,Pn) returning R", or the type "reference to function
13124 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000013125 // is also considered as a candidate function. Similarly,
13126 // surrogate call functions are added to the set of candidate
13127 // functions for each conversion function declared in an
13128 // accessible base class provided the function is not hidden
13129 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000013130 const auto &Conversions =
13131 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13132 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000013133 NamedDecl *D = *I;
13134 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13135 if (isa<UsingShadowDecl>(D))
13136 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013137
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013138 // Skip over templated conversion functions; they aren't
13139 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000013140 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013141 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000013142
John McCall6e9f8f62009-12-03 04:06:58 +000013143 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013144 if (!Conv->isExplicit()) {
13145 // Strip the reference type (if any) and then the pointer type (if
13146 // any) to get down to what might be a function type.
13147 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13148 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13149 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013150
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013151 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13152 {
13153 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013154 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013155 }
13156 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013157 }
Mike Stump11289f42009-09-09 15:08:12 +000013158
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013159 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13160
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013161 // Perform overload resolution.
13162 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000013163 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +000013164 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013165 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013166 // Overload resolution succeeded; we'll build the appropriate call
13167 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013168 break;
13169
13170 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013171 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013172 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000013173 << Object.get()->getType() << /*call*/ 1
13174 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013175 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013176 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000013177 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013178 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013180 break;
13181
13182 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013183 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013184 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013185 << 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:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013190 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000013191 diag::err_ovl_deleted_object_call)
13192 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013193 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013194 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000013195 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013197 break;
Mike Stump11289f42009-09-09 15:08:12 +000013198 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013199
Douglas Gregorb412e172010-07-25 18:17:45 +000013200 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013201 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013202
John McCall4124c492011-10-17 18:40:02 +000013203 UnbridgedCasts.restore();
13204
Craig Topperc3ec1492014-05-26 06:22:03 +000013205 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013206 // Since there is no function declaration, this is one of the
13207 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013208 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013209 = cast<CXXConversionDecl>(
13210 Best->Conversions[0].UserDefined.ConversionFunction);
13211
Craig Topperc3ec1492014-05-26 06:22:03 +000013212 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13213 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013214 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13215 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013216 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013217 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013218 // We selected one of the surrogate functions that converts the
13219 // object parameter to a function pointer. Perform the conversion
13220 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013221
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013222 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013223 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013224 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13225 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013226 if (Call.isInvalid())
13227 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013228 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013229 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13230 CK_UserDefinedConversion, Call.get(),
13231 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013232
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013233 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013234 }
13235
Craig Topperc3ec1492014-05-26 06:22:03 +000013236 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013237
Douglas Gregorab7897a2008-11-19 22:57:39 +000013238 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13239 // that calls this method, using Object for the implicit object
13240 // parameter and passing along the remaining arguments.
13241 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013242
13243 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013244 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013245 return ExprError();
13246
Chandler Carruth8e543b32010-12-12 08:17:55 +000013247 const FunctionProtoType *Proto =
13248 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013249
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013250 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013251
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013252 DeclarationNameInfo OpLocInfo(
13253 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13254 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013255 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013256 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013257 OpLocInfo.getLoc(),
13258 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013259 if (NewFn.isInvalid())
13260 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013261
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013262 // Build the full argument list for the method call (the implicit object
13263 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013264 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013265 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013266 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013267
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013268 // Once we've built TheCall, all of the expressions are properly
13269 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013270 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013271 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13272 ResultTy = ResultTy.getNonLValueExprType(Context);
13273
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013274 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013275 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013276 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013277
Alp Toker314cc812014-01-25 16:55:45 +000013278 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013279 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013280
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013281 // We may have default arguments. If so, we need to allocate more
13282 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013283 if (Args.size() < NumParams)
13284 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013285
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013286 bool IsError = false;
13287
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013288 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013289 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013290 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013291 Best->FoundDecl, Method);
13292 if (ObjRes.isInvalid())
13293 IsError = true;
13294 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013295 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013296 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013297
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013298 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013299 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013300 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013301 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013302 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013303
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013304 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013305
John McCalldadc5752010-08-24 06:29:42 +000013306 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013307 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013308 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013309 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013310 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013311
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013312 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013313 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013314 } else {
John McCalldadc5752010-08-24 06:29:42 +000013315 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013316 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13317 if (DefArg.isInvalid()) {
13318 IsError = true;
13319 break;
13320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013321
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013322 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013323 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013324
13325 TheCall->setArg(i + 1, Arg);
13326 }
13327
13328 // If this is a variadic call, handle args passed through "...".
13329 if (Proto->isVariadic()) {
13330 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013331 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013332 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13333 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013334 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013335 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013336 }
13337 }
13338
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013339 if (IsError) return true;
13340
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013341 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013342
Richard Smith55ce3522012-06-25 20:30:08 +000013343 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013344 return true;
13345
John McCalle172be52010-08-24 06:09:16 +000013346 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013347}
13348
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013349/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013350/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013351/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013352ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013353Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13354 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013355 assert(Base->getType()->isRecordType() &&
13356 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013357
John McCall4124c492011-10-17 18:40:02 +000013358 if (checkPlaceholderForOverload(*this, Base))
13359 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013360
John McCallbc077cf2010-02-08 23:07:23 +000013361 SourceLocation Loc = Base->getExprLoc();
13362
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013363 // C++ [over.ref]p1:
13364 //
13365 // [...] An expression x->m is interpreted as (x.operator->())->m
13366 // for a class object x of type T if T::operator->() exists and if
13367 // the operator is selected as the best match function by the
13368 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013369 DeclarationName OpName =
13370 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013371 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013372 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013373
John McCallbc077cf2010-02-08 23:07:23 +000013374 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013375 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013376 return ExprError();
13377
John McCall27b18f82009-11-17 02:14:36 +000013378 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13379 LookupQualifiedName(R, BaseRecord->getDecl());
13380 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013381
13382 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013383 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013384 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013385 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013386 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013387
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013388 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13389
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013390 // Perform overload resolution.
13391 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013392 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013393 case OR_Success:
13394 // Overload resolution succeeded; we'll build the call below.
13395 break;
13396
13397 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013398 if (CandidateSet.empty()) {
13399 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013400 if (NoArrowOperatorFound) {
13401 // Report this specific error to the caller instead of emitting a
13402 // diagnostic, as requested.
13403 *NoArrowOperatorFound = true;
13404 return ExprError();
13405 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013406 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13407 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013408 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013409 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013410 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013411 }
13412 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013413 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013414 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013416 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013417
13418 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013419 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13420 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013421 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013422 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013423
13424 case OR_Deleted:
13425 Diag(OpLoc, diag::err_ovl_deleted_oper)
13426 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013427 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013428 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013429 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013430 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013431 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013432 }
13433
Craig Topperc3ec1492014-05-26 06:22:03 +000013434 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013435
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013436 // Convert the object parameter.
13437 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013438 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013439 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013440 Best->FoundDecl, Method);
13441 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013442 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013443 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013444
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013445 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013446 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013447 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013448 if (FnExpr.isInvalid())
13449 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013450
Alp Toker314cc812014-01-25 16:55:45 +000013451 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013452 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13453 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013454 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013455 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013456 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013457
Alp Toker314cc812014-01-25 16:55:45 +000013458 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013459 return ExprError();
13460
13461 if (CheckFunctionCall(Method, TheCall,
13462 Method->getType()->castAs<FunctionProtoType>()))
13463 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013464
13465 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013466}
13467
Richard Smithbcc22fc2012-03-09 08:00:36 +000013468/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13469/// a literal operator described by the provided lookup results.
13470ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13471 DeclarationNameInfo &SuffixInfo,
13472 ArrayRef<Expr*> Args,
13473 SourceLocation LitEndLoc,
13474 TemplateArgumentListInfo *TemplateArgs) {
13475 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013476
Richard Smith100b24a2014-04-17 01:52:14 +000013477 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13478 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013479 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13480 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013481
Richard Smithbcc22fc2012-03-09 08:00:36 +000013482 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13483
Richard Smithbcc22fc2012-03-09 08:00:36 +000013484 // Perform overload resolution. This will usually be trivial, but might need
13485 // to perform substitutions for a literal operator template.
13486 OverloadCandidateSet::iterator Best;
13487 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13488 case OR_Success:
13489 case OR_Deleted:
13490 break;
13491
13492 case OR_No_Viable_Function:
13493 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13494 << R.getLookupName();
13495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13496 return ExprError();
13497
13498 case OR_Ambiguous:
13499 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13500 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13501 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013502 }
13503
Richard Smithbcc22fc2012-03-09 08:00:36 +000013504 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013505 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013506 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013507 SuffixInfo.getLoc(),
13508 SuffixInfo.getInfo());
13509 if (Fn.isInvalid())
13510 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013511
13512 // Check the argument types. This should almost always be a no-op, except
13513 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013514 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013515 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013516 ExprResult InputInit = PerformCopyInitialization(
13517 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13518 SourceLocation(), Args[ArgIdx]);
13519 if (InputInit.isInvalid())
13520 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013521 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013522 }
13523
Alp Toker314cc812014-01-25 16:55:45 +000013524 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013525 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13526 ResultTy = ResultTy.getNonLValueExprType(Context);
13527
Richard Smithc67fdd42012-03-07 08:35:16 +000013528 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013529 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013530 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013531 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13532
Alp Toker314cc812014-01-25 16:55:45 +000013533 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013534 return ExprError();
13535
Craig Topperc3ec1492014-05-26 06:22:03 +000013536 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013537 return ExprError();
13538
13539 return MaybeBindToTemporary(UDL);
13540}
13541
Sam Panzer0f384432012-08-21 00:52:01 +000013542/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13543/// given LookupResult is non-empty, it is assumed to describe a member which
13544/// will be invoked. Otherwise, the function will be found via argument
13545/// dependent lookup.
13546/// CallExpr is set to a valid expression and FRS_Success returned on success,
13547/// otherwise CallExpr is set to ExprError() and some non-success value
13548/// is returned.
13549Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013550Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13551 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013552 const DeclarationNameInfo &NameInfo,
13553 LookupResult &MemberLookup,
13554 OverloadCandidateSet *CandidateSet,
13555 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013556 Scope *S = nullptr;
13557
Richard Smith67ef14f2017-09-26 18:37:55 +000013558 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013559 if (!MemberLookup.empty()) {
13560 ExprResult MemberRef =
13561 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13562 /*IsPtr=*/false, CXXScopeSpec(),
13563 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013564 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013565 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013566 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013567 if (MemberRef.isInvalid()) {
13568 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013569 return FRS_DiagnosticIssued;
13570 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013571 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013572 if (CallExpr->isInvalid()) {
13573 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013574 return FRS_DiagnosticIssued;
13575 }
13576 } else {
13577 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013578 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013579 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013580 NestedNameSpecifierLoc(), NameInfo,
13581 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013582 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013583
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013584 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013585 CandidateSet, CallExpr);
13586 if (CandidateSet->empty() || CandidateSetError) {
13587 *CallExpr = ExprError();
13588 return FRS_NoViableFunction;
13589 }
13590 OverloadCandidateSet::iterator Best;
13591 OverloadingResult OverloadResult =
13592 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13593
13594 if (OverloadResult == OR_No_Viable_Function) {
13595 *CallExpr = ExprError();
13596 return FRS_NoViableFunction;
13597 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013598 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013599 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013600 OverloadResult,
13601 /*AllowTypoCorrection=*/false);
13602 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13603 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013604 return FRS_DiagnosticIssued;
13605 }
13606 }
13607 return FRS_Success;
13608}
13609
13610
Douglas Gregorcd695e52008-11-10 20:40:00 +000013611/// FixOverloadedFunctionReference - E is an expression that refers to
13612/// a C++ overloaded function (possibly with some parentheses and
13613/// perhaps a '&' around it). We have resolved the overloaded function
13614/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013615/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013616Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013617 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013618 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013619 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13620 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013621 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013622 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013623
Douglas Gregor51c538b2009-11-20 19:42:02 +000013624 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013625 }
13626
Douglas Gregor51c538b2009-11-20 19:42:02 +000013627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013628 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13629 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013630 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013631 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013632 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013633 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013634 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013635 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013636
13637 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013638 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013639 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013640 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013641 }
13642
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013643 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13644 if (!GSE->isResultDependent()) {
13645 Expr *SubExpr =
13646 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13647 if (SubExpr == GSE->getResultExpr())
13648 return GSE;
13649
13650 // Replace the resulting type information before rebuilding the generic
13651 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013652 ArrayRef<Expr *> A = GSE->getAssocExprs();
13653 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013654 unsigned ResultIdx = GSE->getResultIndex();
13655 AssocExprs[ResultIdx] = SubExpr;
13656
13657 return new (Context) GenericSelectionExpr(
13658 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13659 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13660 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13661 ResultIdx);
13662 }
13663 // Rather than fall through to the unreachable, return the original generic
13664 // selection expression.
13665 return GSE;
13666 }
13667
Douglas Gregor51c538b2009-11-20 19:42:02 +000013668 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013669 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013670 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013671 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13672 if (Method->isStatic()) {
13673 // Do nothing: static member functions aren't any different
13674 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013675 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013676 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013677 // UnresolvedLookupExpr holding an overloaded member function
13678 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013679 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13680 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013681 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013682 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013683
John McCalld14a8642009-11-21 08:51:07 +000013684 assert(isa<DeclRefExpr>(SubExpr)
13685 && "fixed to something other than a decl ref");
13686 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13687 && "fixed to a member ref with no nested name qualifier");
13688
13689 // We have taken the address of a pointer to member
13690 // function. Perform the computation here so that we get the
13691 // appropriate pointer to member type.
13692 QualType ClassType
13693 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13694 QualType MemPtrType
13695 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013696 // Under the MS ABI, lock down the inheritance model now.
13697 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13698 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013699
John McCall7decc9e2010-11-18 06:31:45 +000013700 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13701 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013702 UnOp->getOperatorLoc(), false);
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013703 }
13704 }
John McCall16df1e52010-03-30 21:47:33 +000013705 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13706 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013707 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013708 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013709
John McCalle3027922010-08-25 11:45:40 +000013710 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013711 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013712 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013713 UnOp->getOperatorLoc(), false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013714 }
John McCalld14a8642009-11-21 08:51:07 +000013715
Richard Smith84a0b6d2016-10-18 23:39:12 +000013716 // C++ [except.spec]p17:
13717 // An exception-specification is considered to be needed when:
13718 // - in an expression the function is the unique lookup result or the
13719 // selected member of a set of overloaded functions
13720 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13721 ResolveExceptionSpec(E->getExprLoc(), FPT);
13722
John McCalld14a8642009-11-21 08:51:07 +000013723 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013724 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013725 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013726 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013727 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13728 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013729 }
13730
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013731 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13732 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013733 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013734 Fn,
John McCall113bee02012-03-10 09:33:50 +000013735 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013736 ULE->getNameLoc(),
13737 Fn->getType(),
13738 VK_LValue,
13739 Found.getDecl(),
13740 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013741 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013742 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13743 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013744 }
13745
John McCall10eae182009-11-30 22:42:35 +000013746 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013747 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013748 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013749 if (MemExpr->hasExplicitTemplateArgs()) {
13750 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13751 TemplateArgs = &TemplateArgsBuffer;
13752 }
John McCall6b51f282009-11-23 01:53:49 +000013753
John McCall2d74de92009-12-01 22:10:20 +000013754 Expr *Base;
13755
John McCall7decc9e2010-11-18 06:31:45 +000013756 // If we're filling in a static method where we used to have an
13757 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013758 if (MemExpr->isImplicitAccess()) {
13759 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013760 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13761 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013762 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013763 Fn,
John McCall113bee02012-03-10 09:33:50 +000013764 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013765 MemExpr->getMemberLoc(),
13766 Fn->getType(),
13767 VK_LValue,
13768 Found.getDecl(),
13769 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013770 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013771 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13772 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013773 } else {
13774 SourceLocation Loc = MemExpr->getMemberLoc();
13775 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013776 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013777 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013778 Base = new (Context) CXXThisExpr(Loc,
13779 MemExpr->getBaseType(),
13780 /*isImplicit=*/true);
13781 }
John McCall2d74de92009-12-01 22:10:20 +000013782 } else
John McCallc3007a22010-10-26 07:05:15 +000013783 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013784
John McCall4adb38c2011-04-27 00:36:17 +000013785 ExprValueKind valueKind;
13786 QualType type;
13787 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13788 valueKind = VK_LValue;
13789 type = Fn->getType();
13790 } else {
13791 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013792 type = Context.BoundMemberTy;
13793 }
13794
13795 MemberExpr *ME = MemberExpr::Create(
13796 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13797 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13798 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13799 OK_Ordinary);
13800 ME->setHadMultipleCandidates(true);
13801 MarkMemberReferenced(ME);
13802 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013804
John McCallc3007a22010-10-26 07:05:15 +000013805 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013806}
13807
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013808ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013809 DeclAccessPair Found,
13810 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013811 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013812}